我写了一个只包含TableWigdet的小对话框.如何确定表格的水平尺寸?我想调整对话框窗口的大小,以便在没有水平滚动条的情况下显示表格.
你可以使用类似的东西(我希望评论得足够多):
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)
Run Code Online (Sandbox Code Playgroud)
当行标题改变时,整个垂直标题的宽度会改变,但不会在headerDataChanged发出信号后立即改变.
这就是我在实际更新垂直标题宽度之后使用a QTimer来调用updateGeometry(必须在sizeHint更改时 调用)的原因QTableWidget.
据我所知,没有简单的方法可以做到。您必须对表列的宽度求和,然后为标题添加空间。您还必须为垂直滚动条和小部件框架添加空间。这是一种方法,
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())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6581 次 |
| 最近记录: |