I have a custom Widget derived from QFrame. I will need to draw on it very frequently (basically, a picture is updated with every mouse move). I checked the Qt Basic drawing example: They override paintEvent, create a painter and do their drawing (and the painter dies at the end of its lifetime, facing the final cur…ly bracket).
For my small testing app, performance is no issue, but I would like to better understand painting operations (or rather: the cost of instantiating temporary objects in a frequently called method), so I was wondering: If the custom QFrame held a pointer to a (permanent) painter and uses it for painting, would that be preferable over creating and deleting one with every call of paintEvent?
Thanks for your time,
Louise
Simply put: don’t worry about it.
Qt does some magic behind the scenes to make the creation of a QPainter fast – notably, the “heavy” part of the state (the paint engine) is shared by all QPainters that operate on the same paint device. (See here.)
Now if you call a bunch of functions that need a painter from your
paintEventhandler, pass them reference to the QPainter – no need to create one for each separate call.But generally, don’t worry about it. Use the same idioms as you see in the examples, and only try and do “smarter” stuff if you actually measure that instantiating QPainters is a bottleneck in your code.
(This isn’t limited to QPainter – Qt does a lot of “behind the scenes” sharing, copy-on-write type manipulations for heavy objects. The examples and tutorials show how you’re supposed to use the API (and they are generally pretty high quality). Follow the examples and only try to outsmart them if you have specific reasons/use cases where more intricate management is required.)