PDA

View Full Version : how does QPersistentModelIndex "work"?



goertzenator
19th October 2010, 14:35
I am struggling to understand QPersistentModelIndex. The documentation says that it allows me to "save" indexes. What does "save" mean... save to disk and reload when I run the program again? Or is it limited to the lifetime of the model?

I note that there are some functions relating to persistent indexes in QAbstractItemModel; do I need to add persistent index support to my model by myself?

In a nutshell, how do QPersistentModelIndexes "work"?

Thanks,
Dan.

faldzip
19th October 2010, 15:03
It is unsafe to store QModelIndexes as for example class members, because they can become invalid. For example you have a delegate and in some special circumstances (on mose hover) you want to draw blue background. But when mouse cursor goes off this index to another, you have to determine which one was last to set its background to normal (I hope it is clear enough). So you have you delegate class with QModelIndex member. While painting blue background you store index in your member variable and in next call you are using this stored index to determine on which index you have to draw normal background (this last index where mouse was in) and now draw the blue background in current index. This solution is unsafe, as this stored QModelIndex might become invalid between calls, so you have to use QPersistentModelIndex which remains valid (ofcourse until you destroy model).

goertzenator
19th October 2010, 17:36
I've dug into the source code and now everything makes perfect sense. :)

My key misunderstanding is what persistant actually meant in this context. It means "persist across calls to the model, but not across model instance lifetimes." The documentation was not clear on this.

Whenever an operation on the model is performed that would invalidate regular model indexes, the model will actively "fixup" all persistent model indexes so that they remain useable. Under the hood, the model calls index() to create updated indexes for the persistent indexes.

faldzip, thank you for the nudge in the right direction.

Dan.

faldzip
19th October 2010, 21:50
But having persistent indexes slows down operations on model, so use them only if you really need.

ChrisW67
19th October 2010, 23:26
If you are using QSqlTableModel committing changes to the database (i.e. submitAll()) will invalidate persistent model indexes and possibly other model indexes.