QTableView: Fill 100% or more of the width

33 Views Asked by At

I have a QTableView where I use the following code:

h_header = self.horizontalHeader()
h_header.setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
h_header.setStretchLastSection(True)

My problem is now that this limits the width of the content to the width of the widget, and replaces the content of columns that are too long with "...".

When I remove setStretchLastSection(True) then it shows longer content with a horizontal scrollbar, but shorter content with empty space on the right.

Is there a way to only stretch the table if the content is less wide than the widget, but else show the complete content with a scrollbar?

Thanks.

Edit: Here a more complete example using TableWidget (I also learned about setTextElideMode):

import sys

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
    QApplication,
    QTableWidget,
    QTableWidgetItem,
    QHeaderView,
    QHBoxLayout,
    QDialog,
    QAbstractItemView,
)


class TableList(QTableWidget):
    def __init__(self, *args):
        super().__init__(*args)

        self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
        self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
        self.setAlternatingRowColors(True)

        self.setTextElideMode(Qt.ElideNone)

        self.horizontalHeader().hide()
        self.verticalHeader().hide()

        self.setTabKeyNavigation(False)

        h_header = self.horizontalHeader()
        h_header.setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
        h_header.setStretchLastSection(True)


class MainWindow(QDialog):
    def __init__(self):
        super().__init__()

        self.table = TableList()
        self.table.setColumnCount(3)
        self.table.setRowCount(1)

        self.table.setItem(0, 0, QTableWidgetItem("A"))
        self.table.setItem(0, 1, QTableWidgetItem("This is a longer text"))
        self.table.setItem(0, 2, QTableWidgetItem("This is another long text"))

        self.table.setFixedWidth(250)

        layout = QHBoxLayout()
        layout.addWidget(self.table)
        self.setLayout(layout)


app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
0

There are 0 best solutions below