I\'m having a hard time understanding how to set a multilevel QTree using the QTreeView and QStandardItemModel.
Here\'s what I have:
from PySide.QtGui im
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 dict
s all the way maybe:
tree = {'root': {
'1': {'A':{}, 'B':{}, 'C':{}},
...
}