There are a number of reasons why you might like to draw offscreen: you might want to compose a collection of images and show them one after another (this is called double-buffering, which you can do to avoid screen painting flicker when you draw onscreen), or write a program that generates image files directly.
As I mentioned in the previous section, Qt provides several classes for offscreen drawing, each with different advantages and disadvantages. These classes are QImage
, QPixmap
, QBitmap
, and QPicture
. Under normal circumstances, you need to choose between QImage
and QPixmap
.
On the other hand, if you're working primarily with offscreen rendering for the purposes of display performance or double-buffering, you'll want to use QPixmap
. QPixmap
is optimized to use data structures and the underlying windowing system and interoperates with the native windowing system more quickly than QImage
. QBitmap
is just a convenience subclass of QPixmap
that defines a monochrome bitmap.
QPicture
is an interesting beast that records drawing operations in a resolution-independent format that you can save to a file and replay later. You might want to do that if you want to create lightweight platform-independent vector images, but typically just using a PNG format at the appropriate resolution is probably easier.
To get a painter for one of these classes, simply create an instance of the class and then pass a pointer to the instance of a QPainter
constructor. For example, to perform the drawing in the previous section to an offscreen image and save it to a PNG file, we'd begin by writing:
QImage image(100, 100, QImage::Format_ARGB32); QPainter painter(&image);
The first line creates an image that's 100 pixels square, encoding each pixel a 32-bit integer, 8 bits for each channel of opacity, red, green, and blue. The second line creates a QPainter
instance that can draw on the QImage
instance. Next, we perform the drawing you just saw in the previous section, and when we're done, we write the image to a PNG file with the line:
image.save("face.png");
QImage
supports a number of image formats, including PNG and JPEG. QImage
also has a load
method, where you can load an image from a file or resource.