您正在为每个项目创建一个模型。那是错误的。你应该使用.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 中避免类型检查,但这对于你构建你的程序的方式是必要的。tree
。如果您以不同的方式构建它会更好,例如dict
一路走来也许:
tree = {'root': {
'1': {'A':{}, 'B':{}, 'C':{}},
...
}