Simplicity and Clarity by Design

Use QImage to Create a Composite Image (i.e. One Image With Another Overlaid on Top of It.)

qt.pngToday I wanted to combine two images of similar size to create a new image. The new image was going to be used for a toolbar button. I have purchased a set of commercial images in the PNG format for use on application toolbars. The set came with a bunch of overlay images that could be used to modify each of the base images. The overlays included things like arrows, warning signs, arrows, people, etc. My first though for using these images was to fire up Adobe Illustrator and just create a new icon by merging the base and overlay together. Then I realized that Qt could do the job for me at runtime, and with a little work I could dynamically overlay different badges on a base icon.

The code below can be used to construct a composite image. You pass in references to a base image and an overlay image. These images are used to construct a third image, and that is returned to the caller.

QImage createImageWithOverlay(const QImage& baseImage, const QImage& overlayImage)
    QImage imageWithOverlay = QImage(baseImage.size(), QImage::Format_ARGB32_Premultiplied);
    QPainter painter(&imageWithOverlay);

    painter.fillRect(imageWithOverlay.rect(), Qt::transparent);

    painter.drawImage(0, 0, baseImage);

    painter.drawImage(0, 0, overlayImage);


    return imageWithOverlay;

Here is an example of using this routine to create an image that might be used to represent something being transfered from a network attached machine.

QImage baseImage(":/Resources/connect_pc_64.png");
    QImage overlayLogoff(":/Resources/overlay_arrow_east_64.png");
    QImage logoffImage = createImageWithOverlay(baseImage, overlayLogoff)

The two source images and resulting composite are shown below.

  1. :/Resources/connect_pc_64.png

  2. :/Resources/overlay_arrow_east_64.png

  3. Generated Composite Image