Let's create a simple demo that shows the effect of different image compositions by following these steps:
- First, set up a new Qt Widgets Application project and remove the menuBar, mainToolBar, and statusBar, as we did in the first recipe.
- Next, add the QPainter class header to the mainwindow.h file:
#include <QPainter>
- After that, declare the paintEvent() virtual function, like so:
virtual void paintEvent(QPaintEvent* event);
- In mainwindow.cpp, we will first load several image files using the QImage class:
void MainWindow::paintEvent(QPaintEvent* event) {
QImage image;
image.load("checker.png");
QImage image2;
image2.load("tux.png");
QImage image3;
image3.load("butterfly.png");
}
- Then, create a QPainter object and use it to draw two pairs of images, where one image is on top of another:
QPainter painter(this);
painter.drawImage(QPoint(10, 10), image);
painter.drawImage(QPoint(10, 10), image2);
painter.drawImage(QPoint(300, 10), image);
painter.drawImage(QPoint(300, 40), image3);
- Compile and run the program now and you should see something like this:
- Next, we will set the composition mode before drawing each image onscreen:
QPainter painter(this);
painter.setCompositionMode(QPainter::CompositionMode_Difference);
painter.drawImage(QPoint(10, 10), image);
painter.setCompositionMode(QPainter::CompositionMode_Multiply);
painter.drawImage(QPoint(10, 10), image2);
painter.setCompositionMode(QPainter::CompositionMode_Xor);
painter.drawImage(QPoint(300, 10), image);
painter.setCompositionMode(QPainter::CompositionMode_SoftLight);
painter.drawImage(QPoint(300, 40), image3);
- Compile and run the program again and you will now see something like this: