Any way to save the collapsed/expanded states for all items in a QTreeWidget ?
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.
Re: Any way to save the collapsed/expanded states for all items in a QTreeWidget ?
No, you have to iterate over items and store a list of expanded nodes yourself.
Re: Any way to save the collapsed/expanded states for all items in a QTreeWidget ?
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.
Re: Any way to save the collapsed/expanded states for all items in a QTreeWidget ?
Quote:
Originally Posted by
d_stranz
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.
Re: Any way to save the collapsed/expanded states for all items in a QTreeWidget ?
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.
Re: Any way to save the collapsed/expanded states for all items in a QTreeWidget ?
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).