Python QtreeWidget: return tree hierarchy
I got stuck in trying to obtain the hierarchical view of a widget tree.
The code works fine and generates a nice tree like that:
ROOT(Animal):
|
|
|___Not extinct:
. | (red)
. |_____BIRD--------------(blue)
. | (green)
|
| (red)
|_____Mammal------------(blue)
| (green)
|
| (red)
|_____Reptile-----------(blue)
(green)
Here is the code with the tree hierarchy:
def myTreeWDG(self):
....
"""define tree"""
self.obj_animalTreeWDG = QtGui.QTreeWidget(self.obj_viewGroupBox)
self.obj_animalTreeWDG.setGeometry(QtCore.QRect(10, 20, 191, 131))
self.obj_animalTreeWDG.setObjectName("obj_animalTreeWDG")
"""ROOT: animal"""
obj_parent1 = QtGui.QTreeWidgetItem(self.obj_animalTreeWDG)
"""not extinct:"""
obj_childView1_1 = QtGui.QTreeWidgetItem()
obj_parent1.addChild(obj_childView1_1)
"""bird"""
obj_childView1_1_1 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_1)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_1)
"""mamal"""
obj_childView1_1_2 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_2)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_2)
"""reptile"""
obj_childView1_1_3 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_3)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_3)
"""connect event"""
QtCore.QObject.connect(self.obj_animalTreeWDG, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.obj_treeViewInput)
Here is the code to add the leaves into the tree:
def insert_treeLeaves(self,total,tree_directParent):
for i in range(0,total):
"""leaves with color name"""
tree_child_leaf = QtGui.QTreeWidgetItem()
tree_directParent.addChild(tree_child_leaf)
Then, we have the fu开发者_运维百科nction that tells us every time the tree is clicked, and where it was clicked:
def obj_treeViewInput(self,item,col):
print "obj _Qtree : pressed"
print "name:" item.text(col)
The problem is, how can we get if the touched leaf (red) belongs to the Bird or other father, i.e. how to get the following output give some mouse click: Animal - Not extinct - Mammal - (red).
All comments and suggestions are highly appreciated.
What about a method in each QtreeWidgetItem in which you could print the path to this item.
In this method, you could use recursion to get the complete path of the item's parents (you have a "QTreeWidgetItem * parent () const" method to do this) and you add the current item's text to its parent's path ! You stop the recursion when an item do not have any parent.
I hope I understood your question and this helps you a little bit !
Do you have your own QTreeWidgetItem class ? You could use a specific role to achieve this...
精彩评论