设置包含QTableWidget的对话窗口的最佳大小

时间:2011-08-25 11:07:02

标签: pyqt pyqt4

我写了一个只包含TableWigdet的小对话框。如何确定表格的水平尺寸?我想调整对话框窗口的大小,以便在没有水平滚动条的情况下显示表格。

2 个答案:

答案 0 :(得分:6)

你可以使用类似的东西(我希望得到足够的评论):

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyTableWidget(QTableWidget):  
    def __init__(self, x, y, parent = None):
        super(MyTableWidget, self).__init__(x, y, parent)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)

        # To force the width to use sizeHint().width()
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)

        # To readjust the size automatically...
        # ... when columns are added or resized
        self.horizontalHeader().geometriesChanged \
             .connect(self.updateGeometryAsync)
        self.horizontalHeader().sectionResized \
             .connect(self.updateGeometryAsync)        
        # ... when a row header label changes and makes the
        # width of the vertical header change too
        self.model().headerDataChanged.connect(self.updateGeometryAsync)

    def updateGeometryAsync(self):      
        QTimer.singleShot(0, self.updateGeometry)

    def sizeHint(self):
        height = QTableWidget.sizeHint(self).height()

        # length() includes the width of all its sections
        width = self.horizontalHeader().length() 

        # you add the actual size of the vertical header and scrollbar
        # (not the sizeHint which would only be the preferred size)                  
        width += self.verticalHeader().width()        
        width += self.verticalScrollBar().width()       

        # and the margins which include the frameWidth and the extra 
        # margins that would be set via a stylesheet or something else
        margins = self.contentsMargins()
        width += margins.left() + margins.right()

        return QSize(width, height)

当行标题发生变化时,整个垂直标题的宽度会发生变化,但在发出信号headerDataChanged之后不会立即改变。
这就是为什么我使用QTimer来调用在updateGeometry实际更新垂直标题宽度后,sizeHint(必须在QTableWidget更改时调用)。

答案 1 :(得分:4)

据我所知,没有简单的方法可以做到这一点。您必须总结表的列的宽度,然后为标题添加空间。您还必须为垂直滚动条和小部件框架添加空间。这是一种方法,

class myTableWidget(QtGui.QTableWidget):

    def sizeHint(self):
        width = 0
        for i in range(self.columnCount()):
            width += self.columnWidth(i)

        width += self.verticalHeader().sizeHint().width()

        width += self.verticalScrollBar().sizeHint().width()
        width += self.frameWidth()*2

        return QtCore.QSize(width,self.height())