Reputation: 171
I am developing a PyQt application that has a QTableWidget, that could, potentially, be used to display a large amount of rows. I would like that each column width would be defined by the maximal element width of the whole column, not only by the largest element that is displayed at the moment of programmatical adding of cells data to the table widget.
The Qt docs in the resizeColumnToContents() method description state that
Only visible columns will be resized. Reimplement sizeHintForColumn() to resize hidden columns as well.
The question is, how exactly should I do this correctly? Unfortunately, I have no real experience in PyQt, and I was unable to find any sources of this method to give me any leads on how should I do this.
And is it possible to do resizing based on the current content displayed at any given moment, i.e. resize after any paintEvents recieved by the table widget?
Upvotes: 2
Views: 2154
Reputation: 6279
You just need to subclass QTableWidget and override the sizeHintForColumn method, returning an integer that describes the width in pixels you want. You can calculate the width by using the width
method of QFontMetrics on the longest string.
class MyTable(QtGui.QTableWidget):
def sizeHintForColumn(self, column):
fm = self.fontMetrics()
max_width = 0
for i in range(self.rowCount()):
width = fm.width(self.item(i,column).text()) + 10
if width > max_width:
max_width = width
return max_width
If you're going to be doing a lot of adding elements and calling resizeColumnToContents
afterwards, you will probably want to store the result somehow. That way you won't have to loop over all rows each time.
Upvotes: 6