Development/Architecture/KDE3/Structured Graphics

Introduction: Structured graphics with QCanvas

QPainter offers a powerful imaging model for painting on widgets and pixmaps. However, it can also be cumbersome to use. Each time your widget receives a paint event, it has to analyze the QPaintEvent::region() or QPaintEvent::rect() which has to be redrawn. Then it has to setup a QPainter and paint all objects which overlap with that region. For example, image a vector graphics program which allows to drag objects like polygons, circles and groups of them around. Each time those objects move a bit, the widget's mouse event handler triggers a paint event for the whole area covered by the objects in their old position and in their new position. Figuring out the necessary redraws and doing them in an efficient way can be difficult, and it may also conflict with the object-oriented structure of the program's source code.

As an alternative, Qt contains the class QCanvas in which you put graphical objects like polygons, text, pixmaps. You may also provide additional items by subclassing QCanvasItem or one of its more specialized subclasses. A canvas can be shown on the screen by one or more widgets of the class QCanvasView which you have to subclass in order to handle user interactions. Qt takes care of all repaints of objects in the view, whether they are caused by the widget being exposed, new objects being created or modified or other things. By using double buffering, this can be done in an efficient and flicker-free way.

Canvas items can overlap each other. In this case, the visible one depends on the z order which can be assigned by QCanvasItem::setZ(). Items can also be made visible or invisible. You can also provide a background to be drawn "behind" all items and a foreground. For associating mouse events with objects, in the canvas, there is the method QCanvas::collisions() which returns a list of items overlapping with a given point. Here we show a screenshot of a canvas view in action:

QCanvas screenshot

Here, the mesh is drawn in the background. Furthermore, there is a QCanvasText item and a violet QCanvasPolygon. The butterfly is a QCanvasPixmap. It has transparent areas, so you can see the underlying items through it.

A tutorial on using QCanvas for writing sprite-based games can be found here.

Initial Author: Bernd Gehrmann

This page was last edited on 11 March 2007, at 21:34. Content is available under Creative Commons License SA 4.0 unless otherwise noted.