我想要一个QTreeWidget
,它有一个首选高度,显示所有内容而没有滚动条。用例是双重的:1)QVBoxLayout
中的树木占据与其内容成比例的空间; 2)QScrollArea
中的树木,其中所有树木应该只有一个滚动条而不是单个滚动条。< / p>
我尝试查询树及其视口,但无论它们有多少内容,它们总是返回相同的值:
size = PySide.QtCore.QSize(100, 30)
sizeHint = PySide.QtCore.QSize(256, 192)
minimumSize = PySide.QtCore.QSize(0, 0)
minimumSizeHint = PySide.QtCore.QSize(76, 76)
maximumSize = PySide.QtCore.QSize(16777215, 16777215)
baseSize = PySide.QtCore.QSize(0, 0)
frameSize = PySide.QtCore.QSize(100, 30)
viewport.size = PySide.QtCore.QSize(94, 5)
viewport.sizeHint = PySide.QtCore.QSize(-1, -1)
viewport.minimumSize = PySide.QtCore.QSize(0, 0)
viewport.minimumSizeHint = PySide.QtCore.QSize(-1, -1)
viewport.maximumSize = PySide.QtCore.QSize(16777215, 16777215)
viewport.baseSize = PySide.QtCore.QSize(0, 0)
viewport.frameSize = PySide.QtCore.QSize(94, 5)
接下来,我尝试通过为每个项目添加所有大小提示来计算大小:
size = super().sizeHint()
height = self.horizontalScrollBar().sizeHint().height()
rows = 0
it = QtGui.QTreeWidgetItemIterator(self)
while it.value() is not None:
rows += 1
size = it.value().sizeHint(0)
height += size.height()
it += 1
size = QtCore.QSize(size.width(), height)
但所有项目返回的大小为(-1,-1)。即使在显示树之后,也不仅仅是在施工期间。
那我该如何计算树的高度?
答案 0 :(得分:2)
诀窍似乎是查询宽度的标题,单个行高的树,并在所有方面添加frameWidth,如下所示:
class TreeWidget(QtGui.QTreeWidget):
def sizeHint(self):
print("TreeWidget.sizeHint()")
print(" frameWidth = {0}".format(self.frameWidth()))
height = 2 * self.frameWidth() # border around tree
if not self.isHeaderHidden():
header = self.header()
headerSizeHint = header.sizeHint()
print(" headerSizeHint = {0}".format(headerSizeHint))
height += headerSizeHint.height()
rows = 0
it = QtGui.QTreeWidgetItemIterator(self)
while it.value() is not None:
rows += 1
index = self.indexFromItem(it.value())
print(" rowHeight = {0}".format(self.rowHeight(index)))
height += self.rowHeight(index)
it += 1
print(" computed height for {0} rows = {1}".format(rows, height))
return QtCore.QSize(header.length() + 2 * self.frameWidth(), height)