python - 如何自动扩展 QTreeWidget 项

标签 python pyqt

下面的代码创建了一个简单的 QTreeWidget,其中包含两个父项。 我希望从一开始就展开项目(这样用户就不必单击箭头来展开项目):

这是默认情况下的样子:

enter image description here

这是我希望的样子(扩展:项目“C”可见):

enter image description here

需要设置什么属性才能使其工作?

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__() 
        parentItem=QtGui.QTreeWidgetItem('P')
        self.addTopLevelItem(parentItem)
        childItem=QtGui.QTreeWidgetItem('C')
        parentItem.insertChild(0, childItem)
        self.show()
tree=Tree()
sys.exit(app.exec_())

最佳答案

您可以使用 QTreeWidget.expandToDepth() .

在你的情况下:

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__() 
        parentItem=QtGui.QTreeWidgetItem('P')
        self.addTopLevelItem(parentItem)
        childItem=QtGui.QTreeWidgetItem('C')
        parentItem.insertChild(0, childItem)
        self.expandToDepth(0)
        self.show()
tree=Tree()
sys.exit(app.exec_())

你也可以使用 expandAll()扩展一切,而不仅仅是扩展到一定深度。

关于python - 如何自动扩展 QTreeWidget 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166305/

相关文章:

python - 枚举与字符串作为函数中的参数

python - 将迭代器分配给 Python 切片

python - Django DynamoDB 数据库后端

python - 在 PyQT4 程序中无法获得多语言支持

python - 添加新小部件时,滚动区域无法扩展(滚动)

python - 如何在 PyQt 向导中显示页面后连接信号?

python - 为什么 Python 在特定情况下支持使用百分号运算符的元组和字典格式?

python - 断言错误 : Found different types with the same name in the schema

python - 删除qt中的子布局?

python - 从可检查的组合框中捕获操作