开发者

Reimplementing sizeHintForColumn() to resizeColumnsToContents() over all cells (not only shown) in QTableView

开发者 https://www.devze.com 2023-03-14 09:08 出处:网络
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 elem

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 recie开发者_Python百科ved by the table widget?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消