0

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
  • It is not safe to cache QModelIndex: see the note in the qt docs. You should also be wary of using QPersistentModelIndex, since it carries a significant performance penalty. The bottom line is that you should do some real-world profiling and see whether there are any significant performance issues in the context in which your model is designed to be used (i.e. avoid premature optimisation). Commented May 6, 2021 at 9:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.