gpt4 book ai didi

python - 多级QTreeView

转载 作者:太空狗 更新时间:2023-10-30 02:30:17 27 4
gpt4 key购买 nike

我很难理解如何使用 QTreeView 和 QStandardItemModel 设置多级 QTree。

这是我所拥有的:

from PySide.QtGui import *
import sys

class MainFrame(QWidget):
def __init__(self):
QWidget.__init__(self)

tree = {'root': {
"1": ["A", "B", "C"],
"2": {
"2-1": ["G", "H", "I"],
"2-2": ["J", "K", "L"]},
"3": ["D", "E", "F"]}
}

self.tree = QTreeView(self)
root_model = QStandardItemModel()
self.tree.setModel(root_model)

for r,root in enumerate(sorted(tree)):
root_item = QStandardItem(root)
root_model.setItem(r,root_item)

for c,child in enumerate(sorted(tree[root])):
child_model = QStandardItemModel(root_model)
child_item = QStandardItem(child)
child_model.setItem(c, child_item)

for gc, grand_child in enumerate(sorted(tree[root][child])):
grand_child_model = QStandardItemModel(child_model)
grand_child_item = QStandardItem(grand_child)
grand_child_model.setItem(gc,grand_child_item)

if type(tree[root][child]) == dict:
for ggc, gran_grand_child in enumerate(sorted(tree[root][child][grand_child])):
gran_grand_child_model = QStandardItemModel(grand_child_model)
gran_grand_child_item = QStandardItem(gran_grand_child)
gran_grand_child_model.setItem(ggc, gran_grand_child_item)

if __name__ == "__main__":
app = QApplication(sys.argv)
main = MainFrame()
main.show()
sys.exit(app.exec_())

我希望它看起来像这样:

tree

到目前为止,只有“根”项目显示出来,它没有抛出任何错误。

此外,我制作这个 for 循环有点匆忙,它有点难以阅读/理解,因为它有太多嵌套的 for 循环。我想知道是否有更好的方法来根据初始字典扩展树。

最佳答案

您正在为每个项目创建一个模型。那是错误的。您应该在项目上使用 .appendRow/.insertRow 来添加子项目。

至于你的循环,我可能会使用递归方法来填充树。这是我要做的:

from PySide.QtGui import *
import sys
import types

class MainFrame(QWidget):
def __init__(self):
QWidget.__init__(self)

tree = {'root': {
"1": ["A", "B", "C"],
"2": {
"2-1": ["G", "H", "I"],
"2-2": ["J", "K", "L"]},
"3": ["D", "E", "F"]}
}

self.tree = QTreeView(self)
layout = QHBoxLayout(self)
layout.addWidget(self.tree)

root_model = QStandardItemModel()
self.tree.setModel(root_model)
self._populateTree(tree, root_model.invisibleRootItem())

def _populateTree(self, children, parent):
for child in sorted(children):
child_item = QStandardItem(child)
parent.appendRow(child_item)
if isinstance(children, types.DictType):
self._populateTree(children[child], child_item)

if __name__ == "__main__":
app = QApplication(sys.argv)
main = MainFrame()
main.show()
sys.exit(app.exec_())

PS:您也没有对主窗口使用任何布局。我在上面添加了它。

PSv2:如果可能的话,最好避免在 Python 中进行类型检查,但在构建 时这是必要的。如果你以不同的方式构建它会更好,比如 dict 可能:

tree = {'root': {
'1': {'A':{}, 'B':{}, 'C':{}},
...
}

关于python - 多级QTreeView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27898718/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com