[Qt-interest] Why destroy QPainter after drawing?

Brad Howes howes at ll.mit.edu
Thu Jul 1 15:29:17 CEST 2010


On Jun 30, 2010, at 12:37 PM, Rohan Prabhu wrote:

> In the documentation for QPainter, it says that "Remember to destroy
> the QPainter object after drawing", but doesn't provide a rationale as
> to why. Why does it say so? Why is destroying QPainter necessary after
> painting?

You don't. However, you need to make sure that the QPaintDevice is no longer being used by the QPainter object. The easiest way to do so is by using RAII, creating a QPainter on the stack with a QPaintDevice given as the sole argument to the constructor. When the method goes out of scope, the QPainter destructor releases the QPaintDevice and all is well in the universe.

You can instead create a QPainter object in the heap, and use the begin() and end() methods to manage ownership of a QPaintDevice object. Note that the begin() method specifically states that all painter settings are reset to default values by a begin() so there appears not be much use in having a heap-based QPainter vs. a stack-based one.

Brad

-- 
Brad Howes
Group 42
MIT Lincoln Laboratory • 244 Wood St. • Lexington, MA 02173
Phone: 781.981.5292 • Fax: 781.981.3495 • Secretary: 781.981.7420









More information about the Qt-interest-old mailing list