Quote Originally Posted by SiLiZiUMM View Post
I am rendering a QTreeView using a custom model based on QAbstractItemModel. My data model has a bool property called "expanded": that property indicate whether if the node must be expanded or collapsed.
Hmm??? Why? Expansion state is the property of the view, not the model...

Up to now, after I call setModel() on the model object, I use a for-loop to iterate through my model (if the property isExpanded is set in the data model, I call expand() on the tree view).
Well... that's exactly the same as you were doing before, only that instead of iterating items you are now iterating indexes. I'd suggest to keep the state in the view though...

Works well, but it doesn't look like the optimal solution here.
The operation has O(n) complexity, you can't do better if you don't have a list of expanded items stored anywhere.

I would have thought that a delegate would take care of this,
The delegate? It is responsible for rendering a single item, not the whole tree. And it doesn't track nor change the state of data in the model.

but as far as I understand it, it is the View's job to manage the tree items... do I have it right?
Yes, the view is responsible for it.

If so, do I have to subclass QTreeView in order to do what I want
No, just "load" the list of expanded items from wherever you have it stored and expand those indexes that need expanding.

(The view is for the display only, when the model is loaded, the nodes are reset to the state indicated in the data, we do not save the node state afterwards)?
Why do you keep the expansion state in the model? It's against any logic relevant to model-view architecture... Visualization state of the model is not related to the data. If I expand or collapse an item in one of the views, there is no change to the data. What if I have two views of the same data and in one of them an index is collapsed and in the other it is expanded? If you really want to break the architecture, then subclass the view, reimplement its setModel() method and hook to the dataChanged signal so that you can react on changes to the model, make the model emit dataChanged when its item changes expansion state and make the view operate on a custom role of the model with setData while expanding or collapsing the item. It will work, although I don't really see a point of doing that....