PDA

View Full Version : Any way to save the collapsed/expanded states for all items in a QTreeWidget ?



BillGates
2nd January 2011, 20:49
Happy new year !


is there any simple way to save to a Qsettings the collapsed/expanded state of all the items in a QTreeWidget ? Smething like savegeometry :D . Just asking, would be nice.

wysota
2nd January 2011, 22:26
No, you have to iterate over items and store a list of expanded nodes yourself.

d_stranz
2nd January 2011, 22:30
Start at the root of the tree, and recursively work your way down, calling each QTreeWidgetItem's isExpanded() method. If you make a bitstring, you can turn on the bit for each item that is expanded and turn it off for each one that is collapsed. Store this in QSettings. When you retrieve it, work you way back through it again, calling setExpanded() with true for the 1 bits, false for the zero bits.

But this only works if your tree never changes between the time you save it and the time it is loaded again. I don't know what your tree represents, but if the tree contents or structure can be changed from outside your program (like a file system, for example), then saving and restoring the state is meaningless.

wysota
2nd January 2011, 22:59
I don't know what your tree represents, but if the tree contents or structure can be changed from outside your program (like a file system, for example), then saving and restoring the state is meaningless.
Not if you also store the id of the node (like a file path in case of a filesystem tree). Then you match items by the id and not by the order of items in the tree.

d_stranz
2nd January 2011, 23:24
Yes, that would work for trees with externally mutable content. So, instead of storing a bit for every element in the tree, you store only the full paths to the first collapsed item in each branch. By definition, everything above that node must be expanded, and everything below is collapsed. Non-matching items are ignored.

wysota
3rd January 2011, 11:15
Of course there is one more downside. If you have two nodes with the same id during two different runs of the program, it doesn't mean they are the same node, it might be they just have the same id (e.g. you can have a directory called "x", then delete it and then create another directory called "x" with different content and the question is whether it should be expanded or not).