Home · All Classes · All Functions · Overviews

2D Painting Example

Files:

The 2D Painting example shows how QPainter and QGLWidget can be used together to display accelerated 2D graphics on supported hardware.

The QPainter class is used to draw 2D graphics primitives onto paint devices provided by QPaintDevice subclasses, such as QWidget and QImage.

Since QGLWidget is a subclass of QWidget, it is possible to reimplement its paintEvent() and use QPainter to draw on the device, just as you would with a QWidget. The only difference is that the painting operations will be accelerated in hardware if it is supported by your system's OpenGL drivers.

In this example, we perform the same painting operations on a QWidget and a QGLWidget. The QWidget is shown with anti-aliasing enabled, and the QGLWidget will also use anti-aliasing if the required extensions are supported by your system's OpenGL driver.

Overview

To be able to compare the results of painting onto a QGLWidget subclass with native drawing in a QWidget subclass, we want to show both kinds of widget side by side. To do this, we derive subclasses of QWidget and QGLWidget, using a separate Helper class to perform the same painting operations for each, and lay them out in a top-level widget, itself provided a the Window class.

Helper Class Definition

In this example, the painting operations are performed by a helper class. We do this because we want the same painting operations to be performed for both our QWidget subclass and the QGLWidget subclass.

The Helper class is minimal:

 class Helper
 {
 public:
     Helper();

 public:
     void paint(QPainter *painter, QPaintEvent *event, int elapsed);

 private:
     QBrush background;
     QBrush circleBrush;
     QFont textFont;
     QPen circlePen;
     QPen textPen;
 };

Apart from the constructor, it only provides a paint() function to paint using a painter supplied by one of our widget subclasses.

Helper Class Implementation

The constructor of the class sets up the resources it needs to paint content onto a widget:

 Helper::Helper()
 {
     QLinearGradient gradient(QPointF(50, -20), QPointF(80, 20));
     gradient.setColorAt(0.0, Qt::white);
     gradient.setColorAt(1.0, QColor(0xa6, 0xce, 0x39));

     background = QBrush(QColor(64, 32, 64));
     circleBrush = QBrush(gradient);
     circlePen = QPen(Qt::black);
     circlePen.setWidth(1);
     textPen = QPen(Qt::white);
     textFont.setPixelSize(50);
 }

The actual painting is performed in the paint() function. This takes a QPainter that has already been set up to paint onto a paint device (either a QWidget or a QGLWidget), a QPaintEvent that provides information about the region to be painted, and a measure of the elapsed time (in milliseconds) since the paint device was last updated.

 void Helper::paint(QPainter *painter, QPaintEvent *event, int elapsed)
 {
     painter->fillRect(event->rect(), background);
     painter->translate(100, 100);

We begin painting by filling in the region contained in the paint event before translating the origin of the coordinate system so that the rest of the painting operations will be displaced towards the center of the paint device.

We draw a spiral pattern of circles, using the elapsed time specified to animate them so that they appear to move outward and around the coordinate system's origin:

     painter->save();
     painter->setBrush(circleBrush);
     painter->setPen(circlePen);
     painter->rotate(elapsed * 0.030);

     qreal r = elapsed/1000.0;
     int n = 30;
     for (int i = 0; i < n; ++i) {
         painter->rotate(30);
         qreal radius = 0 + 120.0*((i+r)/n);
         qreal circleRadius = 1 + ((i+r)/n)*20;
         painter->drawEllipse(QRectF(radius, -circleRadius,
                                     circleRadius*2, circleRadius*2));
     }
     painter->restore();

Since the coordinate system is rotated many times during this process, we save() the QPainter's state beforehand and restore() it afterwards.

     painter->setPen(textPen);
     painter->setFont(textFont);
     painter->drawText(QRect(-50, -50, 100, 100), Qt::AlignCenter, "Qt");
 }

We draw some text at the origin to complete the effect.

Widget Class Definition

The Widget class provides a basic custom widget that we use to display the simple animation painted by the Helper class.

 class Helper;
 class QPaintEvent;

 class Widget : public QWidget
 {
     Q_OBJECT

 public:
     Widget(Helper *helper, QWidget *parent);

 public slots:
     void animate();

 protected:
     void paintEvent(QPaintEvent *event);

 private:
     Helper *helper;
     int elapsed;
 };

Apart from the constructor, it only contains a paintEvent() function, that lets us draw customized content, and a slot that is used to animate its contents. One member variable keeps track of the Helper that the widget uses to paint its contents, and the other records the elapsed time since it was last updated.

Widget Class Implementation

The constructor only initializes the member variables, storing the Helper object supplied and calling the base class's constructor, and enforces a fixed size for the widget:

 Widget::Widget(Helper *helper, QWidget *parent)
     : QWidget(parent), helper(helper)
 {
     elapsed = 0;
     setFixedSize(200, 200);
 }

The animate() slot is called whenever a timer, which we define later, times out:

 void Widget::animate()
 {
     elapsed = (elapsed + qobject_cast<QTimer*>(sender())->interval()) % 1000;
     repaint();
 }

Here, we determine the interval that has elapsed since the timer last timed out, and we add it to any existing value before repainting the widget. Since the animation used in the Helper class loops every second, we can use the modulo operator to ensure that the elapsed variable is always less than 1000.

Since the Helper class does all of the actual painting, we only have to implement a paint event that sets up a QPainter for the widget and calls the helper's paint() function:

 void Widget::paintEvent(QPaintEvent *event)
 {
     QPainter painter;
     painter.begin(this);
     painter.setRenderHint(QPainter::Antialiasing);
     helper->paint(&painter, event, elapsed);
     painter.end();
 }

GLWidget Class Definition

The GLWidget class definition is basically the same as the Widget class except that it is derived from QGLWidget.

 class Helper;
 class QPaintEvent;
 class QWidget;

 class GLWidget : public QGLWidget
 {
     Q_OBJECT

 public:
     GLWidget(Helper *helper, QWidget *parent);

 public slots:
     void animate();

 protected:
     void paintEvent(QPaintEvent *event);

 private:
     Helper *helper;
     int elapsed;
 };

Again, the member variables record the Helper used to paint the widget and the elapsed time since the previous update.

GLWidget Class Implementation

The constructor differs a little from the Widget class's constructor:

 GLWidget::GLWidget(Helper *helper, QWidget *parent)
     : QGLWidget(QGLFormat(QGL::SampleBuffers), parent), helper(helper)
 {
     elapsed = 0;
     setFixedSize(200, 200);
     setAutoFillBackground(false);
 }

As well as initializing the elapsed member variable and storing the Helper object used to paint the widget, the base class's constructor is called with the format that specifies the QGL::SampleBuffers flag. This enables anti-aliasing if it is supported by your system's OpenGL driver.

The animate() slot is exactly the same as that provided by the Widget class:

 void GLWidget::animate()
 {
     elapsed = (elapsed + qobject_cast<QTimer*>(sender())->interval()) % 1000;
     repaint();
 }

The paintEvent() is almost the same as that found in the Widget class:

 void GLWidget::paintEvent(QPaintEvent *event)
 {
     QPainter painter;
     painter.begin(this);
     painter.setRenderHint(QPainter::Antialiasing);
     helper->paint(&painter, event, elapsed);
     painter.end();
 }

Since anti-aliasing will be enabled if available, we only need to set up a QPainter on the widget and call the helper's paint() function to display the widget's contents.

Window Class Definition

The Window class has a basic, minimal definition:

 class Window : public QWidget
 {
     Q_OBJECT

 public:
     Window();

 private:
     Helper helper;
 };

It contains a single Helper object that will be shared between all widgets.

Window Class Implementation

The constructor does all the work, creating a widget of each type and inserting them with labels into a layout:

 Window::Window()
     : QWidget()
 {
     Widget *native = new Widget(&helper, this);
     GLWidget *openGL = new GLWidget(&helper, this);
     QLabel *nativeLabel = new QLabel(tr("Native"));
     nativeLabel->setAlignment(Qt::AlignHCenter);
     QLabel *openGLLabel = new QLabel(tr("OpenGL"));
     openGLLabel->setAlignment(Qt::AlignHCenter);

     QGridLayout *layout = new QGridLayout;
     layout->addWidget(native, 0, 0);
     layout->addWidget(openGL, 0, 1);
     layout->addWidget(nativeLabel, 1, 0);
     layout->addWidget(openGLLabel, 1, 1);
     setLayout(layout);

     QTimer *timer = new QTimer(this);
     connect(timer, SIGNAL(timeout()), native, SLOT(animate()));
     connect(timer, SIGNAL(timeout()), openGL, SLOT(animate()));
     timer->start(50);

     setWindowTitle(tr("2D Painting on Native and OpenGL Widgets"));
 }

A timer with a 50 millisecond time out is constructed for animation purposes, and connected to the animate() slots of the Widget and GLWidget objects. Once started, the widgets should be updated at around 20 frames per second.

Running the Example

The example shows the same painting operations performed at the same time in a Widget and a GLWidget. The quality and speed of rendering in the GLWidget depends on the level of support for multisampling and hardware acceleration that your system's OpenGL driver provides. If support for either of these is lacking, the driver may fall back on a software renderer that may trade quality for speed.


Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt 4.6.0