1

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?

Aleksandar
  • 3,541
  • 4
  • 34
  • 57

2 Answers2

5

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)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
1

There are signals on the header objects that you could connect to: http://doc.qt.nokia.com/4.7-snapshot/qheaderview.html

header = self.ui.tableWidget.horizontalHeader()
header.sortIndicatorChanged.connect(self.fixRowSizes)

You can also try setting the resize mode for your rows as you populate:

# grab the header object
row_header = self.ui.tableWidget.verticalHeader()

# populate some data
self.ui.tableWidget.setRowCount(100)
self.ui.tableWidget.setColumnCount(100)
for row in range(100):
    for col in range(100):
        self.ui.tableWidget.setItem(row, col, QTableWidgetItem(str(row * col)))

    # mark each row to automatically resize to contents
    row_header.setResizeMode(row, QHeaderView.ResizeToContens)

The negative of this approach is that the user control over the size is disabled when set to ResizeToContents. As long as your user doesn't ever intend/need to resize manually - this is a good way to go about it.

Eric Hulser
  • 3,912
  • 21
  • 20