qtqtreeviewqmodelindex

setModel on a QTreeView invalids previous model indexes?


I have a QTreeView to which I have attached a custom model.

In my code, I do:

treeView->setModel(modelPtr)

...

...

...

treeView->setModel(modelPtr)

Can I rely that after the 2nd setModel() call, the model indexes will remain same as after the 1st call to setModel()?

I read somewhere that they cannot be relied and can change.

a) Please confirm if this understanding is correct.

Request the experts of this forum to confirm and add any other important information related to when a model index can get invalidated.

b) Suppose, I have attached my tree view to a model.

_dtreeView->setModel(modelPtr)

Then, I attach it to a proxy model:

_dtreeView->setModel(_proxyModelPtr)

Will the model index of a item in the model represented by modelPtr remain same even after setting the view to proxy model?

I think it would remain same since the view has been changed to proxy model but the actual model is not changed.

Request the experts to please confirm.


Solution

  • It's not safe to save the QModelIndex. The documentation says:

    Note: Model indexes should be used immediately and then discarded. You should not rely on indexes to remain valid after calling model functions that change the structure of the model or delete items. If you need to keep a model index over time use a QPersistentModelIndex.

    See QModelIndex and QPersistentModelIndex.

    You can store QPersistentModelIndex. If the model remains valid (not deleted) you can rely on QPersistentModelIndex even if you change the model of the view. The index is related to the model and it doesn't depend on the view (you can display the same model on more views).