Multi-level QTreeView

放肆的年华 提交于 2019-12-04 10:16:32

You're creating a model for each item. That's wrong. You should use .appendRow/.insertRow on an item to add child items.

As for your loops, I'd probably use a recursive method to populate the tree. Here is what I'd do:

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: You're also not using any layouts for the main window. I added it above.

PSv2: Type-checking is best avoided in python, if possible, but it's kind of necessary the way you structured your tree. It'd be better if you structured it differently, like dicts all the way maybe:

tree = {'root': {
            '1': {'A':{}, 'B':{}, 'C':{}},
             ...
       }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!