1 回答
TA贡献1802条经验 获得超10个赞
如果您想根据子项是展开还是折叠来更改 QTreeWidget 的高度,则必须使用展开和折叠信号。您还必须计算所需的高度。
from PyQt5 import QtCore, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.tree = QtWidgets.QTreeWidget()
self.tree.header().hide()
root_item = QtWidgets.QTreeWidgetItem(self.tree)
root_item.setText(0, "root")
root_item.setFlags(
root_item.flags() | QtCore.Qt.ItemIsTristate | QtCore.Qt.ItemIsUserCheckable
)
for i in range(10):
child = QtWidgets.QTreeWidgetItem(root_item)
child.setFlags(child.flags() | QtCore.Qt.ItemIsUserCheckable)
child.setText(0, "Child-{}".format(i))
child.setCheckState(0, QtCore.Qt.Unchecked)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.tree)
lay.addStretch(1)
self.tree.collapsed.connect(self.handle_collapsed)
self.tree.expanded.connect(self.handle_expanded)
def handle_collapsed(self, index):
h = self.tree.rowHeight(index) + self.tree.header().height() + 1
self.adjust_height(h)
def handle_expanded(self):
h = self.tree.sizeHint().height()
self.adjust_height(h)
def adjust_height(self, height):
self.tree.setFixedHeight(height)
def showEvent(self, event):
index = self.tree.indexFromItem(self.tree.topLevelItem(0))
if self.tree.isExpanded(index):
QtCore.QTimer.singleShot(0, self.handle_expanded)
else:
QtCore.QTimer.singleShot(
0, lambda index=index: self.handle_collapsed(index)
)
super().showEvent(event)
app = QtWidgets.QApplication([])
w = MainWindow()
w.show()
app.exec_()
添加回答
举报