QAbstractItemModel - Should QModelIndex objects be cached when created?

310 views Asked by At

When subclassing a QAbstractItemModel and re-implementing the index() method, I had been simply returning a new index each time with createIndex(). But I noticed that the index() method gets called thousands of times when the model is used in conjunction with a view, for all sorts of paint events and whatnot.

Should I instead be caching the QModelIndex object after I generate it the first time in index(), and then be returning the cached index when index() is subsequently called on the same row/col? It's not mentioned in the documentation, and it seems that indexes themselves can become invalidated under certain circumstances, so I am unsure of what to do here.

In my particular case, I'm working with Pyside6, but I imaging this could apply to any implementation of the Qt framework.

1

There are 1 answers

0
mugiseyebrows On

If your model supports inserting or removing rows, your indexes are not persistent. You can still use cache but you must invalidate it every time model shape changes. If creating index logic is complicated there might be benefit in caching. Size of QModelIndex is about four ints (row, column and pointer/id and pointer), so it's relatively lightweight, creating and moving it around is cheap. Either way there's only one way to be sure: try caching and measure perfomance gain.