pythonsortingpyqt4signals-slotsqtablewidget

Python-QTableWidget: How to catch signal when sorting in header is clicked


While filling tableWidget with some text I've used self.ui.tableWidget.resizeRowToContents for every row. After that and: self.ui.tableWidget.setSortingEnabled(1) ,sorting is working as expected but rows are not resize to content anymore, in fact they preserve previous height.

name                              name v                 name v
---------                         ---------              ---------
text2                             text1line1             text1line1
---------  after sort is clicked: ---------   expected:  text1line2
text1line1                                               text1line3
text1line2                        text2                  ---------
text1line3                                               text2
---------                         ---------              ---------

My idea is to catch signal when sorting in header is clicked, and go again with self.ui.tableWidget.resizeRowToContents through all rows. How to catch that signal?


Solution

  • There's no need to call resizeRowToContents for every row that is added.

    Instead, after the table is filled, call the resizeRowsToContents slot, which will resize all the rows at once.

    You can then connect the same slot to the sortIndicatorChanged signal, so that the rows are resized whenever the columns are sorted:

    # ... fill table, then:
    self.ui.tableWidget.setSortingEnabled(True)
    self.ui.tableWidget.resizeRowsToContents()
    self.ui.tableWidget.horizontalHeader().sortIndicatorChanged.connect(
        self.ui.tableWidget.resizeRowsToContents)