Home · Overviews · Examples 

QPainter Class Reference
[com.trolltech.qt.gui module]

The QPainter class performs low-level painting on widgets and other paint devices. More...

Inherited by QStylePainter.


Detailed Description

The QPainter class performs low-level painting on widgets and other paint devices.

QPainter provides highly optimized functions to do most of the drawing GUI programs require. It can draw everything from simple lines to complex shapes like pies and chords. It can also draw aligned text and pixmaps. Normally, it draws in a "natural" coordinate system, but it can also do view and world transformation. QPainter can operate on any object that inherits the QPaintDevice class.

The common use of QPainter is inside a widget's paint event: Construct and customize (e.g. set the pen or the brush) the painter. Then draw. Remember to destroy the QPainter object after drawing. For example:

    void SimpleExampleWidget::paintEvent(QPaintEvent *)
    {
        QPainter painter(this);
        painter.setPen(Qt::blue);
        painter.setFont(QFont("Arial", 30));
        painter.drawText(rect(), Qt::AlignCenter, "Qt");
    }

The core functionality of QPainter is drawing, but the class also provide several functions that allows you to customize QPainter's settings and its rendering quality, and others that enable clipping. In addition you can control how different shapes are merged together by specifying the painter's composition mode.

The isActive function indicates whether the painter is active. A painter is activated by the begin function and the constructor that takes a QPaintDevice argument. The end function, and the destructor, deactivates it.

Together with the QPaintDevice and QPaintEngine classes, QPainter form the basis for Qt's paint system. QPainter is the class used to perform drawing operations. QPaintDevice represents a device that can be painted on using a QPainter. QPaintEngine provides the interface that the painter uses to draw onto different types of devices. If the painter is active, device returns the paint device on which the painter paints, and paintEngine returns the paint engine that the painter is currently operating on. For more information, see The Paint System documentation.

Sometimes it is desirable to make someone else paint on an unusual QPaintDevice. QPainter supports a static function to do this, setRedirected.

Warning: When the paintdevice is a widget, QPainter can only be used inside a paintEvent() function or in a function called by paintEvent(); that is unless the Qt::WA_PaintOutsidePaintEvent widget attribute is set. On Mac OS X and Windows, you can only paint in a paintEvent() function regardless of this attribute's setting.

Settings

There are several settings that you can customize to make QPainter draw according to your preferences:

Note that some of these settings mirror settings in some paint devices, e.g. QWidget::font(). The QPainter::begin() function (or equivalently the QPainter constructor) copies these attributes from the paint device.

You can at any time save the QPainter's state by calling the save function which saves all the available settings on an internal stack. The restore function pops them back.

Drawing

QPainter provides functions to draw most primitives: drawPoint, drawPoints, drawLine, drawRect, drawRoundRect, drawEllipse, drawArc, drawPie, drawChord, drawPolyline, drawPolygon, drawConvexPolygon and drawCubicBezier(). The two convenience functions, drawRects and drawLines, draw the given number of rectangles or lines in the given array of QRects or QLines using the current pen and brush.

The QPainter class also provides the fillRect function which fills the given QRect, with the given QBrush, and the eraseRect function that erases the area inside the given rectangle.

All of these functions have both integer and floating point versions.

Basic Drawing Example

The Basic Drawing example shows how to display basic graphics primitives in a variety of styles using the QPainter class.

If you need to draw a complex shape, especially if you need to do so repeatedly, consider creating a QPainterPath and drawing it using drawPath.

Painter Paths example

The QPainterPath class provides a container for painting operations, enabling graphical shapes to be constructed and reused.

The Painter Paths example shows how painter paths can be used to build complex shapes for rendering.

QPainter also provides the fillPath function which fills the given QPainterPath with the given QBrush, and the strokePath function that draws the outline of the given path (i.e. strokes the path).

See also the Vector Deformation demo which shows how to use advanced vector techniques to draw text using a QPainterPath, the Gradients demo which shows the different types of gradients that are available in Qt, and the Path Stroking demo which shows Qt's built-in dash patterns and shows how custom patterns can be used to extend the range of available patterns.

Vector DeformationGradientsPath Stroking

There are functions to draw pixmaps/images, namely drawPixmap, drawImage and drawTiledPixmap. Both drawPixmap and drawImage produce the same result, except that drawPixmap is faster on-screen while drawImage may be faster on a QPrinter or other devices.

Text drawing is done using drawText. When you need fine-grained positioning, boundingRect tells you where a given drawText command will draw.

There is a drawPicture function that draws the contents of an entire QPicture. The drawPicture function is the only function that disregards all the painter's settings as QPicture has its own settings.

Rendering Quality

To get the optimal rendering result using QPainter, you should use the platform independent QImage as paint device; i.e. using QImage will ensure that the result has an identical pixel representation on any platform.

The QPainter class also provides a means of controlling the rendering quality through its RenderHint enum and the support for floating point precision: All the functions for drawing primitives has a floating point version. These are often used in combination with the QPainter::AntiAliasing render hint.

Concentric Circles Example

The Concentric Circles example shows the improved rendering quality that can be obtained using floating point precision and anti-aliasing when drawing custom widgets.

The application's main window displays several widgets which are drawn using the various combinations of precision and anti-aliasing.

The RenderHint enum specifies flags to QPainter that may or may not be respected by any given engine. QPainter::AntiAliasing indicates that the engine should antialias edges of primitives if possible, QPainter::TextAntialiasing indicates that the engine should antialias text if possible, and the QPainter::SmoothPixmapTransform indicates that the engine should use a smooth pixmap transformation algorithm. HighQualityAntialiasing is an OpenGL-specific rendering hint indicating that the engine should use fragment programs and offscreen rendering for antialiasing.

The renderHints function returns a flag that specifies the rendering hints that are set for this painter. Use the setRenderHint function to set or clear the currently set RenderHints.

Coordinate Transformations

Normally, the QPainter operates on the device's own coordinate system (usually pixels), but QPainter has good support for coordinate transformations.

noprotatescaletranslate

The most commonly used transformations are scaling, rotation, translation and shearing. Use the scale function to scale the coordinate system by a given offset, the rotate function to rotate it clockwise and translate to translate it (i.e. adding a given offset to the points). You can also twist the coordinate system around the origin using the shear function. See the Affine Transformations demo for a visualization of a sheared coordinate system.

See also the Transformations example which shows how transformations influence the way that QPainter renders graphics primitives. In particular it shows how the order of transformations affects the result.

Affine Transformations Demo

The Affine Transformations demo show Qt's ability to perform affine transformations on painting operations. The demo also allows the user to experiment with the transformation operations and see the results immediately.

All the tranformation operations operate on the transformation worldMatrix. A matrix transforms a point in the plane to another point. For more information about the transformation matrix, see the The Coordinate System and QMatrix documentation.

The setWorldMatrix function can replace or add to the currently set worldMatrix. The resetMatrix function resets any transformations that were made using translate, scale, shear, rotate, setWorldMatrix, setViewport and setWindow functions. The deviceMatrix returns the matrix that transforms from logical coordinates to device coordinates of the platform dependent paint device. The latter function is only needed when using platform painting commands on the platform dependent handle, and the platform does not do transformations nativly.

When drawing with QPainter, we specify points using logical coordinates which then are converted into the physical coordinates of the paint device. The mapping of the logical coordinates to the physical coordinates are handled by QPainter's combinedMatrix, a combination of viewport and window and worldMatrix. The viewport represents the physical coordinates specifying an arbitrary rectangle, the window describes the same rectangle in logical coordinates, and the worldMatrix is identical with the transformation matrix.

See also The Coordinate System documentation.

Clipping

QPainter can clip any drawing operation to a rectangle, a region, or a vector path. The current clip is available using the functions clipRegion and clipPath. Whether paths or regions are preferred (faster) depends on the underlying paintEngine. For example, the QImage paint engine prefers paths while the X11 paint engine prefers regions. Setting a clip is done in the painters logical coordinates.

After QPainter's clipping, the paint device may also clip. For example, most widgets clip away the pixels used by child widgets, and most printers clip away an area near the edges of the paper. This additional clipping is not reflected by the return value of clipRegion or hasClipping.

Composition Modes

QPainter provides the CompositionMode enum which defines the Porter-Duff rules for digital image compositing; it describes a model for combining the pixels in one image, the source, with the pixels in another image, the destination.

The two most common forms of composition are Source and SourceOver. Source is used to draw opaque objects onto a paint device. In this mode, each pixel in the source replaces the corresponding pixel in the destination. In SourceOver composition mode, the source object is transparent and is drawn on top of the destination.

Note that composition transformation operates pixelwise. For that reason, there is a difference between using the grahic primitive itself and its bounding rectangle: The bounding rect contains pixels with alpha == 0 (i.e the pixels surrounding the primitive). These pixels will overwrite the other image's pixels, affectively clearing those, while the primitive only overwrites its own area.

Composition Modes Demo

The Composition Modes demo, available in Qt's demo directory, allows you to experiment with the various composition modes and see the results immediately.

See also QPaintDevice, QPaintEngine, QtSvg Module, and Basic Drawing Example.


Copyright © 2008 Trolltech Trademarks
Qt Jambi 4.3.5_01