QTreeWidget select all children of a selected item
-
Hello,
I have following tree:-Parent1
................|_Child 1
................|_Child 2
................................|_Child of Child 2ExtendedSelection is enabled. Now I select Parent1 and click a Button and I want Child1, Child2 and Child of Child 2 to be selected to retrieve data from selectedItems()
To do something like:
selectedones = self.tw.selectedItems()
for item in selectedones:
print(item.text(2))Hope you can understand and help me.
Kind regards,
Zweat -
Hi and welcome to devnet,
Recursively go through all the item children and call setSelected on them.
-
Thanks for welcoming me and the answer. Due to the fact I am pretty new to programming I am questioning myself how I could go through the item children. I tried to read through the Qtreewidget manual but I couldn't get to a conclusion. Therefore, maybe you could provide me a small codesnippet?
Kind regards,
Zweat -
That's because you are looking at the wrong class.
QTreeWidgetItem::childCount and QTreeWidgetItem::child are what you are looking for.
-
Hi,
now I got I was realy looking for the wrong class.
Following is what I am doing to select the Items, as the Items are from a SQL Database, I don't know, how many children a child of a child etc. can have. Is there a better way, than write 20 for loops to get deeper?for item in selectedones: for i in range(0,item.childCount()): item.child(i).setSelected(True) for n in range(0,item.child(i).childCount()): item.child(i).child(n).setSelected(True) for o in range(0,item.child(i).child(n).childCount()): item.child(i).child(n).child(o).setSelected(True)Kind regards and thanks for advice!
-
Use a recursive function
-
@JoeCFD said in QTreeWidget select all children of a selected item:
@SGaist Use iterative loops if possible. Recursion may cause stack overflow.
Joe, my friend, that is not the right approach! It's a very broad statement. Recursing in order to visit this tree to any likely depth is the correct algorithm to use. It will not go anywhere near overflowing the stack for any imaginable depth. And further the recursive function will be incredibly light on local, stack variable sizes; it is when one codes to occupy, say, megabytes of stack space with local variables on each recursive function call that one would have to beware of stack overflow, and that is not the case in Qt-type programming.
The OP should be encouraged to use a simple recursive function here (which I was going to say myself yesterday, but didn't bother) as the correct approach, not forced to worry about an unnecessary iterative replacement.