pythonqtableviewpyside6

Looking for a function equivalent to "resizeRowToIndex" for QTableView


I am working with a QTableView, and I'd like for the row to change its height to accommodate the content of the selected index.

The function resizeRowToContents is not really what I am looking for. If I click on a cell [A] that doesn't need to change its height to display everything but a cell [B] in the row needs to, the row will increase its height to accommodate [B].

Using sizeHintForRow would result in the same behaviour as using resizeRowToContents

The function sizeHintForIndex doesn't return the correct value for some reason.

In the C++ source of Qt there is a private function heightHintForIndex that would be exactly what I need (because it's used by resizeRowToContents).

Is there a function that I am missing, or does anyone know a way to do it?

I am using my own QStyledItemDelegate for those cells.


Solution

  • Basically, I wrote the function heightHintForIndex in Python.

    def on_selection_changed(self, selected: QModelIndex , deselected: QModelIndex):
        
        self.setRowHeight(deselected.row(), 1)
        editor = self.indexWidget(selected)
        hint = 0
        if (editor is not None) and (self.isPersistentEditorOpen(selected)):
            hint = max(hint, editor.sizeHint().height())
            min_ = editor.minimumSize().height()
            max_ = editor.maximumSize().height()
            hint = max(min_, min(max_, hint))
            
        option = QStyleOptionViewItem()
        self.initViewItemOption(option)
        option.rect.setY(self.rowViewportPosition(selected.row()))
        height = self.rowHeight(selected.row())
        if height == 0:
            height = 1
        option.rect.setHeight(self.rowHeight(selected.row()))
        option.rect.setX(self.columnViewportPosition(selected.column()))
        option.rect.setWidth(self.columnWidth(selected.column()))
    
        if self.showGrid():
            option.rect.setWidth(option.rect.width() - 1)
    
        new_height = max(hint, self.itemDelegateForIndex(selected).sizeHint(option, selected).height())
    
        self.setRowHeight(selected.row(), new_height)