There are a number of reasons why you might like to draw off screen: 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 on screen), 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. In 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 in 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 Portable Network Graphics (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 the following code:
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 following 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.
That's it; we have not only learned how to draw an image on screen, but also how to draw it off screen and save it into an image file. Next, we will proceed to learn how to create our own custom widgets in Qt.