Search code examples
qtpyqtqt5pyqt5qheaderview

QHeaderView: Stretch or ResizeToContents based on columns' content size


I have a QTableWidget with a last column that contains text of variable length.

I want to either stretch or resize the last section of the QHeaderView to its contents based on the size of the section. If the content size does not exceed the remaining space in the widget, I want to stretch it (to prevent an ugly, unfilled space in the widget). I can achieve this by using setStretchLastSection(True). However, if the content size exceeds the stretched column, the last parts of my contents are cut, as the column is not resized. QHeaderView provides the ResizeToContents ResizeMode for this case, but this leaves the widget with unfilled space in the case of short contents.

I thought about manually resizing the column size. Unfortunately, I cannot access the content size directly, as sectionSizeFromContents() is protected. I guess I could subclass QHeaderView and reimplement it, but I was wondering if there is a better solution.


Solution

  • I misunderstood the functionality of QHeaderView::sectionSizeFromContents(). I assumed that it returns the section size of the cells belonging to the section, but this information can of course not be stored in the header. Instead, it returns the size of the header content, i.e. the given label.

    However, it is possible to get a column's content size by QTableWidget::sizeHintForColumn(). My table has only two columns, so to compute the remaining space for the second column I can use:

    stretched_size = table.viewport().size().width() - table.horizontalHeader().sectionSize(0)
    

    which equals the column size in the ResizeMode::Stretch. I can therefore solve my problem by setting the section size to the maximum of the stretched size and the column's size hint:

    size = max(table.sizeHintForColumn(1), stretched_size)
    table.horizontalHeader().resizeSection(1, size)