Home  Contents

Painting in Qt4

In this part of the Qt4 C++ programming tutorial we will do some painting.

When do we need to paint? There are situations, when we need to create a widget from scratch. In such a case, we need to do painting. Or we want to create charts, special ornaments, effects or widget enhancements.

The QPainter class is instrumental when we do some painting in the Qt4 programming library. The paining is done with the QPainter class inside the paintEvent() method.

Lines

In the first example we will paint some lines on the client area of the window.

lines.h
#ifndef LINES_H #define LINES_H #include <QWidget> class Lines : public QWidget { Q_OBJECT public: Lines(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); }; #endif

The header file.

lines.cpp
#include "lines.h" #include <QApplication> #include <QPainter> Lines::Lines(QWidget *parent) : QWidget(parent) { } void Lines::paintEvent(QPaintEvent *event) { QPen pen(Qt::black, 2, Qt::SolidLine); QPainter painter(this); painter.setPen(pen); painter.drawLine(20, 40, 250, 40); pen.setStyle(Qt::DashLine); painter.setPen(pen); painter.drawLine(20, 80, 250, 80); pen.setStyle(Qt::DashDotLine); painter.setPen(pen); painter.drawLine(20, 120, 250, 120); pen.setStyle(Qt::DotLine); painter.setPen(pen); painter.drawLine(20, 160, 250, 160); pen.setStyle(Qt::DashDotDotLine); painter.setPen(pen); painter.drawLine(20, 200, 250, 200); QVector<qreal> dashes; qreal space = 4; dashes << 1 << space << 5 << space; pen.setStyle(Qt::CustomDashLine); pen.setDashPattern(dashes); painter.setPen(pen); painter.drawLine(20, 240, 250, 240); }

We paint six different lines on the window.

 QPen pen(Qt::black, 2, Qt::SolidLine);

We create a QPen object. The pen is solid, 2px thick and of black colour. The pen is used to draw lines and outlines of shapes.

 QPainter painter(this);

We create a QPainter object.

 painter.drawLine(20, 40, 250, 40);

Here we paint the first line. The four parameters are coordinates of two points on the window.

 pen.setStyle(Qt::DashLine);

This code line sets a different pen style.

main.cpp
#include "lines.h" #include <QDesktopWidget> #include <QApplication> void center(QWidget &widget) { int x, y; int screenWidth; int screenHeight; int WIDTH = 280; int HEIGHT = 270; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - WIDTH) / 2; y = (screenHeight - HEIGHT) / 2; widget.setGeometry(x, y, WIDTH, HEIGHT); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Lines window; window.setWindowTitle("Lines"); window.show(); center(window); return app.exec(); }

Main file.


Lines
Figure: Lines

Colors

A colour is an object representing a combination of Red, Green, and Blue (RGB) intensity values. Valid RGB values are in the range 0 to 255. In the following example, we draw 9 rectangles filled with 9 different colors.

colors.h
#ifndef COLORS_H #define COLORS_H #include <QWidget> class Colors : public QWidget { public: Colors(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); }; #endif

Header file.

colors.cpp
#include "colors.h" #include <QApplication> #include <QPainter> Colors::Colors(QWidget *parent) : QWidget(parent) { } void Colors::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setPen(QColor("#d4d4d4")); painter.setBrush(QBrush("#c56c00")); painter.drawRect(10, 15, 90, 60); painter.setBrush(QBrush("#1ac500")); painter.drawRect(130, 15, 90, 60); painter.setBrush(QBrush("#539e47")); painter.drawRect(250, 15, 90, 60); painter.setBrush(QBrush("#004fc5")); painter.drawRect(10, 105, 90, 60); painter.setBrush(QBrush("#c50024")); painter.drawRect(130, 105, 90, 60); painter.setBrush(QBrush("#9e4757")); painter.drawRect(250, 105, 90, 60); painter.setBrush(QBrush("#5f3b00")); painter.drawRect(10, 195, 90, 60); painter.setBrush(QBrush("#4c4c4c")); painter.drawRect(130, 195, 90, 60); painter.setBrush(QBrush("#785f36")); painter.drawRect(250, 195, 90, 60); }

We draw nine rectangles with different color fills. The outline of the rectangles is gray.

 painter.setBrush(QBrush("#c56c00"));
 painter.drawRect(10, 15, 90, 60);

The QBrush class defines the fill pattern of shapes drawn by QPainter. The drawRect() method draws the rectangle. It draws a rectangle with upper left corner at x, y point and with the given width and height. To specify a color, we used a hexadecimal notation.

main.cpp
#include "colors.h" #include <QDesktopWidget> #include <QApplication> void center(QWidget &widget) { int x, y; int screenWidth; int screenHeight; int WIDTH = 350; int HEIGHT = 280; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - WIDTH) / 2; y = (screenHeight - HEIGHT) / 2; widget.setGeometry(x, y, WIDTH, HEIGHT); widget.setFixedSize(WIDTH, HEIGHT); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Colors window; window.setWindowTitle("Colors"); window.show(); center(window); return app.exec(); }

Main file.


Colors
Figure: Colors

Patterns

The following programming code example is similar to the previous one. This time we fill the rectangles with various predefined patterns.

brushes.h
#ifndef BRUSHES_H #define BRUSHES_H #include <QWidget> class Brushes : public QWidget { Q_OBJECT public: Brushes(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); }; #endif

Header file.

brushes.cpp
#include "brushes.h" #include <QApplication> #include <QPainter> Brushes::Brushes(QWidget *parent) : QWidget(parent) { } void Brushes::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setPen(Qt::NoPen); painter.setBrush(Qt::HorPattern); painter.drawRect(10, 15, 90, 60); painter.setBrush(Qt::VerPattern); painter.drawRect(130, 15, 90, 60); painter.setBrush(Qt::CrossPattern); painter.drawRect(250, 15, 90, 60); painter.setBrush(Qt::Dense7Pattern); painter.drawRect(10, 105, 90, 60); painter.setBrush(Qt::Dense6Pattern); painter.drawRect(130, 105, 90, 60); painter.setBrush(Qt::Dense5Pattern); painter.drawRect(250, 105, 90, 60); painter.setBrush(Qt::BDiagPattern); painter.drawRect(10, 195, 90, 60); painter.setBrush(Qt::FDiagPattern); painter.drawRect(130, 195, 90, 60); painter.setBrush(Qt::DiagCrossPattern); painter.drawRect(250, 195, 90, 60); }

We draw 9 rectangles with various brush patterns.

  painter.setBrush(Qt::HorPattern);
  painter.drawRect(10, 15, 90, 60);

We draw a rectangle with a specific pattern. The Qt::HorPattern is a constant used to create a pattern of horizontal lines.

main.cpp
#include "brushes.h" #include <QDesktopWidget> #include <QApplication> void center(QWidget &widget) { int x, y; int screenWidth; int screenHeight; int WIDTH = 350; int HEIGHT = 280; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - WIDTH) / 2; y = (screenHeight - HEIGHT) / 2; widget.setGeometry(x, y, WIDTH, HEIGHT); widget.setFixedSize(WIDTH, HEIGHT); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Brushes window; window.setWindowTitle("Brushes"); window.show(); center(window); return app.exec(); }

Main file.


Patterns
Figure: Patterns

Donut

In the following example, we will create a donut using the painting API of the Qt4 programming library.

donut.h
#ifndef DONUT_H #define DONUT_H #include <QWidget> class Donut : public QWidget { Q_OBJECT public: Donut(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); }; #endif

Header file.

donut.cpp
#include "donut.h" #include <QApplication> #include <QPainter> Donut::Donut(QWidget *parent) : QWidget(parent) { } void Donut::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setPen(QPen(QBrush("#535353"), 0.5)); painter.setRenderHint(QPainter::Antialiasing); int h = height(); int w = width(); painter.translate(QPoint(w/2, h/2)); for (qreal rot=0; rot < 360.0; rot+=5.0 ) { painter.drawEllipse(-125, -40, 250, 80); painter.rotate(5.0); } }

The "Donut" is an advanced geometrical shape resembling this kind of food. We create it by drawing 72 rotated ellipses.

 painter.setRenderHint(QPainter::Antialiasing);

We will paint in antialiased mode. The rendering will be of higher quality.

 int h = height();
 int w = width();

 painter.translate(QPoint(w/2, h/2));

These lines move the beginning of the coordinate system into the middle of the window. By default, it is positioned at 0, 0 point. In another words, at the upper left corner of the window. By moving the coordinate system, the drawing will be much easier.

 for (qreal rot=0; rot < 360.0; rot+=5.0 ) {
     painter.drawEllipse(-125, -40, 250, 80);
     painter.rotate(5.0);
 }

In this for cycle, we draw 72 rotated ellipses.

main.cpp
#include "donut.h" #include <QDesktopWidget> #include <QApplication> void center(QWidget &widget) { int x, y; int screenWidth; int screenHeight; int WIDTH = 350; int HEIGHT = 280; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - WIDTH) / 2; y = (screenHeight - HEIGHT) / 2; widget.setGeometry(x, y, WIDTH, HEIGHT); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Donut window; window.setWindowTitle("Donut"); window.show(); center(window); return app.exec(); }

Main file.


Donut
Figure: Donut

Shapes

The Qt4 painting API can draw various shapes. The following programming code example will show some of them.

shapes.h
#ifndef SHAPES_H #define SHAPES_H #include <QWidget> class Shapes : public QWidget { Q_OBJECT public: Shapes(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); }; #endif

Header file.

shapes.cpp
#include "shapes.h" #include <QApplication> #include <QPainter> #include <QPainterPath> Shapes::Shapes(QWidget *parent) : QWidget(parent) { } void Shapes::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(QPen(QBrush("#575555"), 1)); QPainterPath path1; path1.moveTo(5, 5); path1.cubicTo(40, 5, 50, 50, 99, 99); path1.cubicTo(5, 99, 50, 50, 5, 5); painter.drawPath(path1); painter.drawPie(130, 20, 90, 60, 30*16, 120*16); painter.drawChord(240, 30, 90, 60, 0, 16*180); painter.drawRoundRect(20, 120, 80, 50); QPolygon polygon; polygon << QPoint(130, 140) << QPoint(180, 170) << QPoint(180, 140) << QPoint(220, 110) << QPoint(140, 100); painter.drawPolygon(polygon); painter.drawRect(250, 110, 60, 60); QPointF baseline(20, 250); QFont font("Georgia", 55); QPainterPath path2; path2.addText(baseline, font, "Q"); painter.drawPath(path2); painter.drawEllipse(140, 200, 60, 60); painter.drawEllipse(240, 200, 90, 60); }

The programming code example draws nine different shapes.

 QPainterPath path1;

 path1.moveTo(5, 5);
 path1.cubicTo(40, 5,  50, 50,  99, 99);
 path1.cubicTo(5, 99,  50, 50,  5, 5);
 painter.drawPath(path1);

The QPainterPath is an object used to create complex shapes. We use it to draw bezier curves.

 painter.drawPie(130, 20, 90, 60, 30*16, 120*16);
 painter.drawChord(240, 30, 90, 60, 0, 16*180);
 painter.drawRoundRect(20, 120, 80, 50);

These code lines draw a pie, a chord and a rounded rectangle.

 QPolygon polygon;
 polygon << QPoint(130, 140) << QPoint(180, 170)
         << QPoint(180, 140) << QPoint(220, 110)
         << QPoint(140, 100);
 painter.drawPolygon(polygon);

Here we draw a polygon consisting of five points.

 QPointF baseline(20, 250);
 QFont font("Georgia", 55);
 QPainterPath path2;
 path2.addText(baseline, font, "Q");
 painter.drawPath(path2);

The Qt4 programming library can be used to create a path based on a font character.

 painter.drawEllipse(140, 200, 60, 60);
 painter.drawEllipse(240, 200, 90, 60);

The drawEllipse() method can be used to draw an ellipse and a circle as well. The circle is a special case of an ellipse.

main.cpp
#include "shapes.h" #include <QDesktopWidget> #include <QApplication> void center(QWidget &widget) { int x, y; int screenWidth; int screenHeight; int WIDTH = 350; int HEIGHT = 280; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - WIDTH) / 2; y = (screenHeight - HEIGHT) / 2; widget.setGeometry(x, y, WIDTH, HEIGHT); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Shapes window; window.setWindowTitle("Shapes"); window.show(); center(window); return app.exec(); }

Main file.


Shapes
Figure: Shapes

Gradients

In computer graphics, gradient is a smooth blending of shades from light to dark or from one color to another. In 2D drawing programs and paint programs, gradients are used to create colorful backgrounds and special effects as well as to simulate lights and shadows. (answers.com)

The following code example will show, how to create gradients in Qt4 programming library.

gradients.h
#ifndef GRADIENT_H #define GRADIENT_H #include <QWidget> class Gradient : public QWidget { public: Gradient(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); }; #endif

Header file.

gradients.cpp
#include "gradients.h" #include <QApplication> #include <QPainter> Gradient::Gradient(QWidget *parent) : QWidget(parent) { } void Gradient::paintEvent(QPaintEvent *event) { QPainter painter(this); QLinearGradient grad1(0, 20, 0, 110); grad1.setColorAt(0.1, Qt::black); grad1.setColorAt(0.5, Qt::yellow); grad1.setColorAt(0.9, Qt::black); painter.fillRect(20, 20, 300, 90, grad1); QLinearGradient grad2(0, 55, 250, 0); grad2.setColorAt(0.2, Qt::black); grad2.setColorAt(0.5, Qt::red); grad2.setColorAt(0.8, Qt::black); painter.fillRect(20, 140, 300, 100, grad2); }

In the code example, we will draw two rectagles and fill them with gradients.

 QLinearGradient grad1(0, 20, 0, 110);

 grad1.setColorAt(0.1, Qt::black);
 grad1.setColorAt(0.5, Qt::yellow);
 grad1.setColorAt(0.9, Qt::black);

The colors in a gradient are defined using stop points. The setColorAt() creates a stop point at the given position with the given color.

 painter.fillRect(20, 20, 300, 90, grad1);

We fill the rectangle with the gradient.

main.cpp
#include "gradients.h" #include <QDesktopWidget> #include <QApplication> void center(QWidget &widget) { int x, y; int screenWidth; int screenHeight; int WIDTH = 350; int HEIGHT = 260; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - WIDTH) / 2; y = (screenHeight - HEIGHT) / 2; widget.setGeometry(x, y, WIDTH, HEIGHT); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Gradient window; window.setWindowTitle("Gradients"); window.show(); center(window); return app.exec(); }

Main file.


Gradients
Figure: Gradients

Puff

In the last example of this C++ Qt4 tutorial chapter, we create a puff effect. The example will display a growing centered text, that will gradully fade out from some point. This is a very common effect, which you can often see in flash animations on the web.

puff.h
#ifndef PUFF_H #define PUFF_H #include <QWidget> class Puff : public QWidget { Q_OBJECT public: Puff(QWidget *parent = 0); protected: void paintEvent(QPaintEvent *event); void timerEvent(QTimerEvent *event); private: int x; qreal opacity; int timerId; }; #endif

In the header file, we have two event handlers defined. Paint event handler and timer handler.

puff.cpp
#include "puff.h" #include <QApplication> #include <QPainter> #include <QPainterPath> #include <QTimer> #include <iostream> Puff::Puff(QWidget *parent) : QWidget(parent) { x = 1; opacity = 1.0; timerId = startTimer(15); } void Puff::paintEvent(QPaintEvent *event) { QPainter painter(this); QString text = "ZetCode"; painter.setPen(QPen(QBrush("#575555"), 1)); QFont font("Courier", x, QFont::DemiBold); QFontMetrics fm(font); int textWidth = fm.width(text); painter.setFont(font); if (x > 10) { opacity -= 0.01; painter.setOpacity(opacity); } if (opacity <= 0) { killTimer(timerId); std::cout << "timer stopped" << std::endl; } int h = height(); int w = width(); painter.translate(QPoint(w/2, h/2)); painter.drawText(-textWidth/2, 0, text); } void Puff::timerEvent(QTimerEvent *event) { x += 1; repaint(); }

Puff::Puff(QWidget *parent)
    : QWidget(parent)
{
  x = 1;
  opacity = 1.0;
  timerId = startTimer(15);
}

At the constructor, we start the timer. Each 15ms a timer event is generated.

void Puff::timerEvent(QTimerEvent *event)
{
  x += 1;
  repaint();
}

Inside the timerEvent() we increase the font size and repaint the widget.

 if (x > 10) {
   opacity -= 0.01;
   painter.setOpacity(opacity);
 }

If the font size is greater than 10 points, we gradually decrease the opacity. The text fades away.

 if (opacity <= 0) {
   killTimer(timerId);
   std::cout << "timer stopped" << std::endl;
 }

If the text fades away, we kill the timer.

main.cpp
#include "puff.h" #include <QDesktopWidget> #include <QApplication> void center(QWidget &widget) { int x, y; int screenWidth; int screenHeight; int WIDTH = 350; int HEIGHT = 280; QDesktopWidget *desktop = QApplication::desktop(); screenWidth = desktop->width(); screenHeight = desktop->height(); x = (screenWidth - WIDTH) / 2; y = (screenHeight - HEIGHT) / 2; widget.setGeometry(x, y, WIDTH, HEIGHT); } int main(int argc, char *argv[]) { QApplication app(argc, argv); Puff window; window.setWindowTitle("Puff"); window.show(); center(window); return app.exec(); }

Main file.


Puff effect
Figure: Puff effect