On this page

QCanvasPainter Class

The QCanvasPainter class performs hardware-accelerated painting on QRhi. More...

Header: #include <QCanvasPainter>
CMake: find_package(Qt6 REQUIRED COMPONENTS CanvasPainter)
target_link_libraries(mytarget PRIVATE Qt6::CanvasPainter)
Since: Qt 6.11

Public Types

enum class CompositeOperation { SourceOver, SourceAtop, DestinationOut }
enum class ImageFlag { GenerateMipmaps, RepeatX, RepeatY, Repeat, FlipY, …, NativeTexture }
flags ImageFlags
enum class LineCap { Butt, Round, Square }
enum class LineJoin { Round, Bevel, Miter }
enum class PathConnection { NotConnected, Connected }
enum class PathWinding { CounterClockWise, ClockWise }
enum class RenderHint { Antialiasing, HighQualityStroking, DisableWindingEnforce }
flags RenderHints
enum class TextAlign { Left, Right, Center, Start, End }
enum class TextBaseline { Top, Hanging, Middle, Alphabetic, Bottom }
enum class TextDirection { LeftToRight, RightToLeft, Inherit, Auto }
enum class WrapMode { NoWrap, Wrap, WordWrap, WrapAnywhere }

Public Functions

QCanvasPainter()
~QCanvasPainter()
qsizetype activeImageCount() const
qsizetype activeImageMemoryUsage() const
QCanvasImage addImage(const QImage &image, QCanvasPainter::ImageFlags flags = {})
QCanvasImage addImage(QRhiTexture *texture, QCanvasPainter::ImageFlags flags = {})
QCanvasImage addImage(const QCanvasOffscreenCanvas &canvas, QCanvasPainter::ImageFlags flags = {})
void addPath(const QPainterPath &path)
void addPath(const QCanvasPath &path, const QTransform &transform = QTransform())
void addPath(const QCanvasPath &path, qsizetype start, qsizetype count, const QTransform &transform = QTransform())
void arc(float centerX, float centerY, float radius, float a0, float a1, QCanvasPainter::PathWinding direction = PathWinding::ClockWise, QCanvasPainter::PathConnection connection = PathConnection::Connected)
void arc(QPointF centerPoint, float radius, float a0, float a1, QCanvasPainter::PathWinding direction = PathWinding::ClockWise, QCanvasPainter::PathConnection connection = PathConnection::Connected)
void arcTo(float x1, float y1, float x2, float y2, float radius)
void arcTo(QPointF controlPoint1, QPointF controlPoint2, float radius)
void beginHoleSubPath()
void beginPath()
void beginSolidSubPath()
void bezierCurveTo(float cp1X, float cp1Y, float cp2X, float cp2Y, float x, float y)
void bezierCurveTo(QPointF controlPoint1, QPointF controlPoint2, QPointF endPoint)
void circle(float centerX, float centerY, float radius)
void circle(QPointF centerPoint, float radius)
void cleanupResources()
void clearRect(float x, float y, float width, float height)
void clearRect(const QRectF &rect)
void closePath()
QCanvasOffscreenCanvas createCanvas(QSize pixelSize, int sampleCount = 1, QCanvasOffscreenCanvas::Flags flags = {})
void destroyCanvas(QCanvasOffscreenCanvas &canvas)
float devicePixelRatio() const
void drawBoxShadow(const QCanvasBoxShadow &shadow)
void drawImage(const QCanvasImage &image, float x, float y)
void drawImage(const QCanvasImage &image, const QRectF &destinationRect)
void drawImage(const QCanvasImage &image, const QRectF &sourceRect, const QRectF &destinationRect)
void drawImage(const QCanvasImage &image, float x, float y, float width, float height)
void ellipse(float centerX, float centerY, float radiusX, float radiusY)
void ellipse(const QRectF &rect)
void ellipse(QPointF centerPoint, float radiusX, float radiusY)
void fill()
void fill(const QCanvasPath &path, int pathGroup = 0)
void fillRect(float x, float y, float width, float height)
void fillRect(const QRectF &rect)
void fillText(const QString &text, float x, float y, float maxWidth = -1)
void fillText(const QString &text, const QRectF &rect)
void fillText(const QString &text, QPointF point, float maxWidth = -1)
QTransform getTransform() const
void lineTo(float x, float y)
void lineTo(QPointF point)
void moveTo(float x, float y)
void moveTo(QPointF point)
void quadraticCurveTo(float cpX, float cpY, float x, float y)
void quadraticCurveTo(QPointF controlPoint, QPointF endPoint)
void rect(float x, float y, float width, float height)
void rect(const QRectF &rect)
void removeImage(const QCanvasImage &image)
void removePathGroup(int pathGroup)
QCanvasPainter::RenderHints renderHints() const
void reset()
void resetClipping()
void resetTransform()
void restore()
void rotate(float angle)
void roundRect(float x, float y, float width, float height, float radius)
void roundRect(const QRectF &rect, float radius)
void roundRect(const QRectF &rect, float radiusTopLeft, float radiusTopRight, float radiusBottomRight, float radiusBottomLeft)
void roundRect(float x, float y, float width, float height, float radiusTopLeft, float radiusTopRight, float radiusBottomRight, float radiusBottomLeft)
void save()
void scale(float scale)
void scale(float scaleX, float scaleY)
void setAntialias(float antialias)
void setBrushTransform(const QTransform &transform)
void setClipRect(float x, float y, float width, float height)
void setClipRect(const QRectF &rect)
void setFillStyle(const QColor &color)
void setFillStyle(const QCanvasBrush &brush)
void setFont(const QFont &font)
void setGlobalAlpha(float alpha)
void setGlobalBrightness(float value)
void setGlobalCompositeOperation(QCanvasPainter::CompositeOperation operation)
void setGlobalContrast(float value)
void setGlobalSaturate(float value)
void setLineCap(QCanvasPainter::LineCap cap)
void setLineJoin(QCanvasPainter::LineJoin join)
void setLineWidth(float width)
void setMiterLimit(float limit)
void setPathWinding(QCanvasPainter::PathWinding winding)
void setRenderHint(QCanvasPainter::RenderHint hint, bool on = true)
void setRenderHints(QCanvasPainter::RenderHints hints, bool on = true)
void setStrokeStyle(const QColor &color)
void setStrokeStyle(const QCanvasBrush &brush)
void setTextAlign(QCanvasPainter::TextAlign align)
void setTextAntialias(float antialias)
void setTextBaseline(QCanvasPainter::TextBaseline baseline)
void setTextDirection(QCanvasPainter::TextDirection direction)
void setTextLineHeight(float height)
void setTextWrapMode(QCanvasPainter::WrapMode wrapMode)
void setTransform(const QTransform &transform)
void skew(float angleX, float angleY = 0.0f)
void stroke()
void stroke(const QCanvasPath &path, int pathGroup = 0)
void strokeRect(float x, float y, float width, float height)
void strokeRect(const QRectF &rect)
QRectF textBoundingBox(const QString &text, float x, float y, float maxWidth = -1)
QRectF textBoundingBox(const QString &text, const QRectF &rect)
QRectF textBoundingBox(const QString &text, QPointF point, float maxWidth = -1)
void transform(const QTransform &transform)
void translate(float x, float y)
void translate(QPointF point)

Static Public Members

float mmToPx(float mm)
float ptToPx(float pt)

Detailed Description

Qt Canvas Painter (QCanvasPainter) provides painting API optimized for harware-accelerated (GPU) painting. The API follows closely HTML Canvas 2D Context specification, ported to Qt C++. It is also influenced by QPainter, but with a more compact API.

Here is a simple example of using QCanvasPainter to create a round button.

QRectF rect(40, 70, 120, 60);
QRectF shadowRect = rect.translated(2, 4);
// Paint shadow
QCanvasBoxShadow shadow(shadowRect, 30, 15, "#60373F26");
p->drawBoxShadow(shadow);
// Paint rounded rect
p->beginPath();
p->roundRect(rect, 30);
p->setFillStyle("#DBEB00");
p->fill();
// Paint text
p->setTextAlign(QCanvasPainter::TextAlign::Center);
p->setTextBaseline(QCanvasPainter::TextBaseline::Middle);
QFont font("Titillium Web", 18);
p->setFont(font);
p->setFillStyle("#373F26");
p->fillText("CLICK!", rect);

Here is another example of painting a simple graph.

// Paint grid
QCanvasGridPattern grid(0, 0, 10, 10, "#404040", "#202020");
p->setFillStyle(grid);
p->fillRect(0, 0, width(), height());
// Paint axis
p->setFillStyle(QColorConstants::White);
p->fillRect(0, 0.5 * height() - 1, width(), 2);
p->fillRect(0.5 * width() - 1, 0, 2, height());
// Paint shadowed graph
p->beginPath();
p->moveTo(20, height() * 0.8);
p->bezierCurveTo(width() * 0.2, height() * 0.4,
                 width() * 0.5, height() * 0.8,
                 width() - 20, height() * 0.2);
p->setAntialias(10);
p->setLineWidth(12);
p->setStrokeStyle("#D0000000");
p->stroke();
p->setAntialias(1);
p->setLineWidth(6);
QCanvasLinearGradient lg(0, 0, 0, height());
lg.setStartColor(QColorConstants::Red);
lg.setEndColor(QColorConstants::Green);
p->setStrokeStyle(lg);
p->stroke();

Features

For the most parts and from the naming perspective, QCanvasPainter follow closely the HTML Canvas 2D Context (https://html.spec.whatwg.org/multipage/canvas.html#2dcontext). This makes the API familiar to use for many developers, and with the ability to easily reuse existing canvas code. But the aim is NOT to be 100% compatible with the HTML canvas. QCanvasPainter misses some of the features to make it simpler, more performant on QRhi hardware accelerated graphics API, and to better target modern UI needs. Due to these reasons, QCanvasPainter also has additional features compared to HTML Canvas 2D Context.

These are some of the functionality we are at least currently missing compared to HTML canvas:

  • Clipping: All clipping is (transformed) rectangle and clipping to path shapes are not supported.
  • Fill mode: Only the default Non-zero fillrule is supported, no support for Even-odd fillrule.
  • Dashes: Strokes are always solid lines, dashed/dotted stroke patterns are not supported.
  • Path testing: There are no isPointInPath() or isPointInStroke() methods.
  • Text stroking: No support for outline stroking of text.
  • Filter: Canvas SVG filter effects are not supported.
  • CompositeModes: The amount of composite modes is limited to 3, which can be supported without rendering into extra buffers.
  • Shadows: Built-in shadow methods are not supported.

On the other hand, some of the additional features QCanvasPainter offers compared to HTML canvas include:

  • Path groups: QCanvasPainter allows painting to static paths and caching these paths as groups for optimal GPU usage.
  • Adjustable antialiasing: Due to path vertex antialiasing and SDF text rendering, the pixel amount of antialiasing can be freely adjusted for smoother painting.
  • Box Gradient: In addition to linear, radial and conical gradients, QCanvasPainter supports also rounded rectangle box gradient.
  • Box Shadow: QCanvasPainter supports also CSS box-shadow type of brush. The rendering uses SDF approach similar to Qt Quick RectangularShadow, making it very performant.
  • Grid patterns: QCanvasPainter supports QCanvasGridPattern for dynamic grid and bar pattern styles.
  • Custom brushes: QCanvasPainter also allows filling & stroking with custom vertex and fragment shaders (QCanvasCustomBrush). These custom brushes can also be used for text.
  • Text wrapping: QCanvasPainter supports automatic wrapping of text into multiple lines, with different wrapping modes.
  • Color effects: With addition to globalAlpha, QCanvasPainter supports also global brightness, contrast and saturation.
  • Tinted images: QCanvasPainter adds tint color support for painted images and image patterns.

QCanvasPainter is architecture agnostic, and usable for both Qt Quick and Qt Widgets applications. Actually, it is usable even without either of those, with just QWindow and QRhi. To utilize QCanvasPainter, use it from one of these classes, dending on the architecture of your application:

Winding rules

QCanvasPainter uses nonzero (WindingFill) fillrule. To select the filling based on the path points direction, disable the winding forcing by setting DisableWindingEnforce rendering hint with setRenderHint().

p->setRenderHint(QCanvasPainter::RenderHint::DisableWindingEnforce);
p->beginPath();
// Outer shape, counterclockwise
p->moveTo(20, 20);
p->lineTo(100, 180);
p->lineTo(180, 20);
p->closePath();
// Inner shape, clockwise
p->moveTo(100, 40);
p->lineTo(125, 90);
p->lineTo(75, 90);
p->closePath();
p->fill();
p->stroke();

However, a more common case is relying on winding enforcing and setting the preferred winding using setPathWinding() or beginHoleSubPath() and beginSolidSubPath() helpers.

p->beginPath();
p->roundRect(20, 20, 160, 160, 30);
// Start painting holes
p->beginHoleSubPath();
p->roundRect(40, 40, 120, 120, 10);
// Start painting solid
p->beginSolidSubPath();
p->rect(60, 60, 80, 20);
p->circle(100, 120, 20);
p->fill();
p->stroke();

Member Type Documentation

enum class QCanvasPainter::CompositeOperation

Qt Canvas Painter supports 3 composite operations:

ConstantValueDescription
QCanvasPainter::CompositeOperation::SourceOver0The default value. Draws new shapes on top of the existing content.
QCanvasPainter::CompositeOperation::SourceAtop1The new shape is only drawn where it overlaps the existing content.
QCanvasPainter::CompositeOperation::DestinationOut2The existing content is kept where it doesn't overlap with the new shape.

See also setGlobalCompositeOperation().

enum class QCanvasPainter::ImageFlag
flags QCanvasPainter::ImageFlags

This enum specifies flags related to images. Use with addImage() to set the flags.

ConstantValueDescription
QCanvasPainter::ImageFlag::GenerateMipmaps1 << 0Set this to generate mipmaps for the image. Mipmaps should be used when smoother output is preferred for images which are scaled to smaller than the original size.
QCanvasPainter::ImageFlag::RepeatX1 << 1Use with image pattern to repeate image in X-coordinate.
QCanvasPainter::ImageFlag::RepeatY1 << 2Use with image pattern to repeate image in Y-coordinate.
QCanvasPainter::ImageFlag::RepeatRepeatX | RepeatYUse with image pattern to repeate image in both coordinates.
QCanvasPainter::ImageFlag::FlipY1 << 3Flips (inverses) image in Y direction when rendered.
QCanvasPainter::ImageFlag::Premultiplied1 << 4Image data has premultiplied alpha.
QCanvasPainter::ImageFlag::Nearest1 << 5Image interpolation is Nearest instead Linear
QCanvasPainter::ImageFlag::NativeTexture1 << 6Signifies this is a texture outside of QCanvasPainter.

The ImageFlags type is a typedef for QFlags<ImageFlag>. It stores an OR combination of ImageFlag values.

enum class QCanvasPainter::LineCap

LineCap is used to define how the end of the line (cap) is drawn.

ConstantValueDescription
QCanvasPainter::LineCap::Butt0(default) Square line ending that does not cover the end point of the line.
QCanvasPainter::LineCap::Round1Round line ending.
QCanvasPainter::LineCap::Square2Square line ending that covers the end point and extends beyond it by half the line width.

See also setLineCap().

enum class QCanvasPainter::LineJoin

LineJoin is used to define how the joins between two connected lines are drawn.

ConstantValueDescription
QCanvasPainter::LineJoin::Round0Circular arc between the two lines is filled.
QCanvasPainter::LineJoin::Bevel1The triangular notch between the two lines is filled.
QCanvasPainter::LineJoin::Miter2(default) The outer edges of the lines are extended to meet at an angle, and this area is filled.

See also setLineJoin() and setMiterLimit().

enum class QCanvasPainter::PathConnection

With some drawing methods PathConnection is used to specify if the new path should be connected to the last point of the previous path.

ConstantValueDescription
QCanvasPainter::PathConnection::NotConnected0There is no line drawn from the last point of the previous path to the first point of the current path.
QCanvasPainter::PathConnection::Connected1The last point of the previous path will be connected to the first point of the current path.

See also arc().

enum class QCanvasPainter::PathWinding

PathWinding is used to specify the direction of path drawing. This direction is used to determine if a subpath is solid or hole in the path.

ConstantValueDescription
QCanvasPainter::PathWinding::CounterClockWise0(default) Counter-clockwise winding for solid shapes.
QCanvasPainter::PathWinding::ClockWise1Clockwise winding for holes.

See also setPathWinding().

enum class QCanvasPainter::RenderHint
flags QCanvasPainter::RenderHints

This enum specifies flags to QCanvasPainter related to rendering. Use setRenderHint() to set the flags.

ConstantValueDescription
QCanvasPainter::RenderHint::Antialiasing1 << 0Setting this to false disables antialiasing. Enabling it results into higher rendering cost. The default value is true.
QCanvasPainter::RenderHint::HighQualityStroking1 << 1Setting this to true gives a more correct rendering in some less common cases where stroking overlaps and doesn't have full opacity. Enabling it results into higher rendering cost. The default value is false.
QCanvasPainter::RenderHint::DisableWindingEnforce1 << 2Setting this to true disables enforcing of path winding to match what has been set into setPathWinding(). Disabling allows e.g. creating holes into paths by adding the points in clock wise order. Disabling can also increase the performance.

The RenderHints type is a typedef for QFlags<RenderHint>. It stores an OR combination of RenderHint values.

enum class QCanvasPainter::TextAlign

TextAlign is used to define how the text is aligned horizontally.

ConstantValueDescription
QCanvasPainter::TextAlign::Left0Align the left side of the text horizontally to the specified position.
QCanvasPainter::TextAlign::Right1Align the right side of the text horizontally to the specified position.
QCanvasPainter::TextAlign::Center2Align the center of the text horizontally to the specified position.
QCanvasPainter::TextAlign::Start3(default) The text is aligned at the normal start of the line (left-aligned for left-to-right locales, right-aligned for right-to-left locales).
QCanvasPainter::TextAlign::End4The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales).

See also setTextAlign(), setTextDirection(), and fillText().

enum class QCanvasPainter::TextBaseline

TextBaseline is used to define how the text is aligned (baselined) vertically.

ConstantValueDescription
QCanvasPainter::TextBaseline::Top0Align the top of the text vertically to the specified position.
QCanvasPainter::TextBaseline::Hanging1Align the hanging baseline of the text vertically to the specified position.
QCanvasPainter::TextBaseline::Middle2Align the middle of the text vertically to the specified position.
QCanvasPainter::TextBaseline::Alphabetic3(default) Align the baseline of the text vertically to the specified position.
QCanvasPainter::TextBaseline::Bottom4Align the bottom of the text vertically to the specified position.

See also setTextBaseline() and fillText().

enum class QCanvasPainter::TextDirection

TextDirection is used to define how the text is aligned horizontally.

ConstantValueDescription
QCanvasPainter::TextDirection::LeftToRight0The text direction is left-to-right.
QCanvasPainter::TextDirection::RightToLeft1The text direction is right-to-left.
QCanvasPainter::TextDirection::Inherit2(default) The text direction is inherited from QGuiApplication layoutDirection. See https://doc.qt.io/qt-6/qguiapplication.html#layoutDirection-prop.
QCanvasPainter::TextDirection::Auto3The text direction is detected automatically based from the text string. See QString::isRightToLeft().

Note: As this requires analyzing the text, it is potentially slower that other options.

See also setTextDirection(), setTextAlign(), and fillText().

enum class QCanvasPainter::WrapMode

WrapMode is used to define how the text is wrapped to multiple lines.

ConstantValueDescription
QCanvasPainter::WrapMode::NoWrap0(default) No wrapping will be performed. If the text contains insufficient newlines, then contentWidth will exceed a set width.
QCanvasPainter::WrapMode::Wrap1If possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word.
QCanvasPainter::WrapMode::WordWrap2Wrapping is done on word boundaries only. If a word is too long, content width will exceed a set width.
QCanvasPainter::WrapMode::WrapAnywhere3Wrapping is done at any point on a line, even if it occurs in the middle of a word.

See also setTextWrapMode() and fillText().

Member Function Documentation

QCanvasPainter::QCanvasPainter()

Constructs a painter.

[noexcept] QCanvasPainter::~QCanvasPainter()

Destroys the painter.

qsizetype QCanvasPainter::activeImageCount() const

Returns the number of active QCanvasImage objects registered with this QCanvasPainter. This also includes the internally created images for gradients.

QCanvasImage objects created by registering QCanvasOffscreenCanvas instances or externally managed textures are not taken into account by this function.

See also activeImageMemoryUsage(), addImage(), and removeImage().

qsizetype QCanvasPainter::activeImageMemoryUsage() const

Returns an approximation in kilobytes of the memory used by the image (pixel) data for all active QCanvasImage instances for this painter that were created by the addImage() overload taking a QImage. It also includes the data from internally created images for gradients.

QCanvasPainter does not keep copies of the CPU-side QImage data once addImage() has returned. Therefore, the result of this function is an approximation of the GPU memory that is used for textures.

Note: The value is only an estimate based on the image format and dimensions. Qt has no knowledge of how the data for textures is stored and laid out in memory on the GPU side.

Offscreen canvases and externally managed textures registered via the other addImage() overloads are not taken into account by this function.

For every valid QCanvasImage, the individual size in bytes can always be queried by calling sizeInBytes(). That function returns valid results also when the QCanvasImage was created from a QCanvasOffscreenCanvas or QRhiTexture, but it does not consider mipmap or multisample data.

See also activeImageCount(), addImage(), and removeImage().

QCanvasImage QCanvasPainter::addImage(const QImage &image, QCanvasPainter::ImageFlags flags = {})

Adds image with flags available for the painter as a texture. Returns QCanvasImage with the texture id and other information about the image. Returned QCanvasImage can then be used with drawImage and QCanvasImagePattern. After calling this method, image QImage does not need be kept in memory.

Calling with the same image is a cheap operation, since a cache hit is expected.

Care must be taken when optimizing to call addImage() only once. That is not always sufficient, depending on the application design. For example, if the underlying graphics resources are lost, e.g. because the painter is associated with a new QRhi under the hood due to moving a widget to a new top-level, then calling this function is essential in order to re-create the native graphics textures from image.

See also drawImage() and removeImage().

QCanvasImage QCanvasPainter::addImage(QRhiTexture *texture, QCanvasPainter::ImageFlags flags = {})

Adds texture with flags available for the painter as a texture. The flag NativeTexture is set implicitly. The returned QCanvasImage can be used with drawImage and QCanvasImagePattern.

Note: The ownership of texture is not taken.

This is an overloaded function.

See also drawImage() and removeImage().

QCanvasImage QCanvasPainter::addImage(const QCanvasOffscreenCanvas &canvas, QCanvasPainter::ImageFlags flags = {})

Registers canvas with flags to the painter so that it is available as an image. The returned QCanvasImage can be used with drawImage and QCanvasImagePattern.

Note: canvas continues to manage the underlying native graphics resources, meaning removeImage() does not render canvas invalid.

This is an overloaded function.

See also drawImage() and removeImage().

void QCanvasPainter::addPath(const QPainterPath &path)

Adds path into the current path.

Note: QCanvasPainter uses WindingFill (nonzero) fillrule, which means that all QPainterPaths don't render correctly. This is notable for example when path contains text characters with holes in them.

Note: This method is available mostly for the compatibility with QPainter and QPainterPath. It does not increase performance compared to painting the path directly with QCanvasPainter methods.

void QCanvasPainter::addPath(const QCanvasPath &path, const QTransform &transform = QTransform())

Adds path into the current path, optionally using transform to alter the path points. When transform is not provided (or it is identity matrix), this operation is very fast as it reuses the path data.

// m_path is QCanvasPath
if (m_path.isEmpty())
    m_path.circle(60, 60, 40);
p->beginPath();
p->addPath(m_path);
p->addPath(m_path, QTransform::fromTranslate(80, 80));
p->fill();
p->stroke();

void QCanvasPainter::addPath(const QCanvasPath &path, qsizetype start, qsizetype count, const QTransform &transform = QTransform())

Adds path into the current path, starting from the command at start and including count amount of commands. Optionally using transform to alter the path points. The range of start and count is checked, so that commands are not accessed more than QCanvasPath::commandsSize(). In case the path shouldn't continue from the current path position, call first moveTo() e.g. with path.positionAt(start - 1).

// m_path is QCanvasPath
if (m_path.isEmpty()) {
    m_path.moveTo(20, 60);
    for (int i = 1; i < 160; i++) {
        m_path.lineTo(20 + i,
                      60 + 20 * sin(0.1 * i));
    }
}
p->stroke(m_path);
p->beginPath();
p->addPath(m_path, 20, 100,
           QTransform::fromTranslate(0, 80));
p->stroke();

void QCanvasPainter::arc(float centerX, float centerY, float radius, float a0, float a1, QCanvasPainter::PathWinding direction = PathWinding::ClockWise, QCanvasPainter::PathConnection connection = PathConnection::Connected)

Creates new circle arc shaped sub-path. The arc center is at centerX, centerY, with radius, and the arc is drawn from angle a0 to a1, and swept in direction (ClockWise or CounterClockWise). When connection is NotConnected, arc does not add a line from the previous path position to the start of the arc. Angles are specified in radians.

p->beginPath();
p->moveTo(100, 100);
p->arc(100, 100, 80, 0, 1.5 * M_PI);
p->closePath();
p->fill();
p->stroke();

Note: While HTML canvas 2D context uses arc() for painting circles, with QCanvasPainter it is recommended to use circle() or ellipse() for those.

void QCanvasPainter::arc(QPointF centerPoint, float radius, float a0, float a1, QCanvasPainter::PathWinding direction = PathWinding::ClockWise, QCanvasPainter::PathConnection connection = PathConnection::Connected)

Creates new circle arc shaped sub-path. The arc center is at centerPoint, with radius, and the arc is drawn from angle a0 to a1, and swept in direction (ClockWise or CounterClockWise). When connection is NotConnected, arc does not add a line from the previous path position to the start of the arc. Angles are specified in radians.

Note: While HTML canvas 2D context uses arc() for painting circles, with QCanvasPainter it is recommended to use circle() or ellipse() for those.

This is an overloaded function.

void QCanvasPainter::arcTo(float x1, float y1, float x2, float y2, float radius)

Adds an arc segment at the corner defined by the last path point, and two specified points (x1, y1 and x2, y2) with radius. The arc is automatically connected to the path's latest point with a straight line if necessary.

p->beginPath();
p->moveTo(20, 20);
p->arcTo(240, 20, 20, 220, 50);
p->arcTo(20, 220, 20, 20, 30);
p->stroke();

void QCanvasPainter::arcTo(QPointF controlPoint1, QPointF controlPoint2, float radius)

Adds an arc segment at the corner defined by the last path point, and two specified points (controlPoint1 and controlPoint2) with radius. The arc is automatically connected to the path's latest point with a straight line if necessary.

This is an overloaded function.

void QCanvasPainter::beginHoleSubPath()

Start a hole subpath. This is equivalent to setPathWinding(QCanvasPainter::PathWinding::ClockWise))

p->beginPath();
p->circle(100, 100, 80);
p->beginHoleSubPath();
p->rect(60, 60, 80, 80);
p->beginSolidSubPath();
p->circle(100, 100, 20);
p->fill();
p->stroke();

See also beginSolidSubPath().

void QCanvasPainter::beginPath()

Begins drawing a new path while clearing the current path.

void QCanvasPainter::beginSolidSubPath()

Start a solid subpath. This is equivalent to setPathWinding(QCanvasPainter::PathWinding::CounterClockWise))

See also beginHoleSubPath().

void QCanvasPainter::bezierCurveTo(float cp1X, float cp1Y, float cp2X, float cp2Y, float x, float y)

Adds cubic bezier segment from last point in the path via two control points (cp1X, cp1Y and cp2X, cp2Y) to the specified point (x, y).

p->beginPath();
p->moveTo(20, 20);
p->bezierCurveTo(150, 50, 50, 250, 180, 120);
p->stroke();

void QCanvasPainter::bezierCurveTo(QPointF controlPoint1, QPointF controlPoint2, QPointF endPoint)

Adds cubic bezier segment from last point in the path via two control points (controlPoint1 and controlPoint2) to the specified point endPoint.

This is an overloaded function.

void QCanvasPainter::circle(float centerX, float centerY, float radius)

Creates new circle shaped sub-path into ( centerX, centerY) with radius.

p->beginPath();
p->circle(100, 100, 80);
p->fill();
p->stroke();

void QCanvasPainter::circle(QPointF centerPoint, float radius)

Creates new circle shaped sub-path into centerPoint with radius.

This is an overloaded function.

void QCanvasPainter::cleanupResources()

Schedules dropping unused textures from the cache.

Additionally, other caches and pools may get shrunk upon calling this function, in order to minimize memory usage. This may potentially lead to more expensive drawing calls afterwards.

void QCanvasPainter::clearRect(float x, float y, float width, float height)

Erases the pixels in a rectangular area by filling the rectangle specified by x, y, width, height with transparent black. As clearing does not need blending, it can be faster than fillRect().

p->beginPath();
p->circle(100, 100, 80);
p->fill();
p->stroke();
p->clearRect(60, 0, 80, 120);

void QCanvasPainter::clearRect(const QRectF &rect)

Erases the pixels in a rectangular area by filling the rectangle specified by rect with transparent black. This is an overloaded method using QRectF.

This is an overloaded function.

void QCanvasPainter::closePath()

Closes the current sub-path with a line segment. This is equivalent to lineTo([starting point]) as the last path element.

QCanvasOffscreenCanvas QCanvasPainter::createCanvas(QSize pixelSize, int sampleCount = 1, QCanvasOffscreenCanvas::Flags flags = {})

Returns a new offscreen canvas with the given pixelSize, sampleCount, and flags.

The size of the canvas is specified in pixels. The pixelSize, sampleCount, and flags properties are immutable afterwards. To get a canvas with a different size, sample count, or flags, create a new one.

To target an offscreen canvas with with draw commands, call the appropriate QCanvasRhiPaintDriver::beginPaint() overload when working with the lower level API, or QCanvasPainterWidget::beginCanvasPainting() or QCanvasPainterItemRenderer::beginCanvasPainting() when using the convenience widget or Qt Quick item classes.

Normally the contents of the canvas is cleared when painting to it. To disable this, pass PreserveContents in flags.

To request multisample rendering onto the canvas (multisample antialiasing, MSAA), set a sample count larger than 1, such as 4 or 8. Preserving the canvas contents between render passes is not supported however when multisampling is enabled, and the PreserveContents flag will not work in this case.

void QCanvasPainter::destroyCanvas(QCanvasOffscreenCanvas &canvas)

Destroys the resources backing canvas. canvas becomes a null canvas then.

The painter automatically does this upon its destruction. Therefore, calling this function is only necessary when releasing the associated resources is desired right away.

float QCanvasPainter::devicePixelRatio() const

Returns the ratio between physical pixels and device-independent pixels. The default value is 1.0.

void QCanvasPainter::drawBoxShadow(const QCanvasBoxShadow &shadow)

Draws a box shadow. The shadow will be painted with the position, size, color, blur etc. set in the shadow. Calling beginPath() before this method is not required.

Note: To visually see the area covered by drawBoxShadow(), set QCPAINTER_DEBUG_SHADOW_RECT environment variable.

QRectF rect(40, 40, 120, 120);
QRectF shadowRect = rect.translated(-2, 4);
QCanvasBoxShadow shadow(shadowRect, 0, 30);
p->drawBoxShadow(shadow);
p->beginPath();
p->roundRect(rect, 30);
p->setFillStyle("#2CDE85");
p->fill();

See also QCanvasBoxShadow.

void QCanvasPainter::drawImage(const QCanvasImage &image, float x, float y)

Draw image into x, y, at its default size.

static QImage logo(":/qt_logo.png");
QCanvasImage image = p->addImage(logo);
p->drawImage(image, 36, 36);

See also addImage().

void QCanvasPainter::drawImage(const QCanvasImage &image, const QRectF &destinationRect)

Draw image into position and size of destinationRect.

This is an overloaded function.

See also addImage().

void QCanvasPainter::drawImage(const QCanvasImage &image, const QRectF &sourceRect, const QRectF &destinationRect)

Draw image into position and size of destinationRect, from sourceRect area of image.

static QImage logo(":/qt_logo.png");
QCanvasImage image = p->addImage(logo);
QRectF sourceRect(20, 30, 54, 76);
QRectF destinationRect(0, 0, 200, 200);
p->drawImage(image, sourceRect, destinationRect);

This is an overloaded function.

See also addImage().

void QCanvasPainter::drawImage(const QCanvasImage &image, float x, float y, float width, float height)

Draw image into x, y, at given width and height.

static QImage logo(":/qt_logo.png");
QCanvasImage image = p->addImage(logo);
p->drawImage(image, 50, 0, 100, 200);

This is an overloaded function.

See also addImage().

void QCanvasPainter::ellipse(float centerX, float centerY, float radiusX, float radiusY)

Creates new ellipse shaped sub-path into ( centerX, centerY) with radiusX and radiusY.

p->beginPath();
p->ellipse(100, 100, 80, 60);
p->fill();
p->stroke();

void QCanvasPainter::ellipse(const QRectF &rect)

Creates new ellipse shaped sub-path into rect. This ellipse will cover the rect area.

QRectF rect(40, 20, 120, 160);
p->fillRect(rect);
p->beginPath();
p->ellipse(rect);
p->stroke();

This is an overloaded function.

void QCanvasPainter::ellipse(QPointF centerPoint, float radiusX, float radiusY)

Creates new ellipse shaped sub-path into centerPoint with radiusX and radiusY.

This is an overloaded function.

void QCanvasPainter::fill()

Fills the current path with current fill style.

p->beginPath();
p->rect(20, 20, 40, 160);
p->rect(140, 20, 40, 160);
p->circle(100, 100, 60);
p->fill();

See also setFillStyle().

void QCanvasPainter::fill(const QCanvasPath &path, int pathGroup = 0)

Fills the path with current fill style and belonging into pathGroup. Painting through QCanvasPath is optimal when the path contains more commands is mostly static. By default, pathGroup is 0, so using the first group. When pathGroup is -1, the path will not be cached on GPU side. More information about using path cache groups in QCanvasPath documentation. Calling beginPath() before this method is not required.

// m_path is QCanvasPath
if (m_path.isEmpty()) {
    for (int i = 0; i < 16; i++) {
        float w = 100 + 60 * sin(i);
        m_path.rect(100 - w * 0.5,
                    22 + i * 10,
                    w, 6);
    }
}
p->fill(m_path);

This is an overloaded function.

See also setFillStyle().

void QCanvasPainter::fillRect(float x, float y, float width, float height)

Draws a filled rectangle into specified position ( x, y) at size width, height.

Note: This is provided for convenience. When filling more than just a single rect, prefer using rect().

p->fillRect(20, 20, 160, 160);
// The above code does same as:
//  p->beginPath();
//  p->rect(20, 20, 160, 160);
//  p->fill();

void QCanvasPainter::fillRect(const QRectF &rect)

Draws a filled rectangle into rect. This is an overloaded method using QRectF.

Note: This is provided for convenience. When filling more than just a single rect, prefer using rect().

This is an overloaded function.

void QCanvasPainter::fillText(const QString &text, float x, float y, float maxWidth = -1)

Draws text string at specified location ( x, y), with current textAlign and textBaseline. To make the text wrap into multiple lines, set optional maxWidth parameter to preferred row width in pixels. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are split at nearest character (i.e. no hyphenation).

void QCanvasPainter::fillText(const QString &text, const QRectF &rect)

Draws text string inside rect, with current textAlign and textBaseline. Width of the rect parameter is used as maxWidth.

This is an overloaded method using QRectF. It is often useful to set the text baseline to TextBaseline::Top or TextBaseline::Middle when painting text with this method.

This is an overloaded function.

void QCanvasPainter::fillText(const QString &text, QPointF point, float maxWidth = -1)

Draws text string at specified point, with current textAlign and textBaseline. To make the text wrap into multiple lines, set optional maxWidth parameter to preferred row width in pixels. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are split at nearest character (i.e. no hyphenation).

This is an overloaded method using QPointF.

This is an overloaded function.

QTransform QCanvasPainter::getTransform() const

Returns the current transform.

void QCanvasPainter::lineTo(float x, float y)

Adds line segment from the last point in the path to the ( x, y) point.

p->beginPath();
p->moveTo(20, 20);
p->lineTo(140, 180);
p->lineTo(180, 120);
p->stroke();

void QCanvasPainter::lineTo(QPointF point)

Adds line segment from the last point in the path to the point.

This is an overloaded function.

[static] float QCanvasPainter::mmToPx(float mm)

Static helper method to convert millimeters mm into pixels. This allows doing resolution independent drawing. For example to set the line width to 2mm use:

painter->setLineWidth(QCanvasPainter::mmToPx(2));

void QCanvasPainter::moveTo(float x, float y)

Starts new sub-path with ( x, y) as first point.

void QCanvasPainter::moveTo(QPointF point)

Starts new sub-path with point as first point.

This is an overloaded function.

[static] float QCanvasPainter::ptToPx(float pt)

Static helper method to convert points pt into pixels.

void QCanvasPainter::quadraticCurveTo(float cpX, float cpY, float x, float y)

Adds quadratic bezier segment from last point in the path via a control point (cpX, cpY) to the specified point (x, y).

p->beginPath();
p->moveTo(20, 20);
p->quadraticCurveTo(150, 50, 180, 180);
p->quadraticCurveTo(20, 220, 20, 20);
p->fill();
p->stroke();

void QCanvasPainter::quadraticCurveTo(QPointF controlPoint, QPointF endPoint)

Adds quadratic bezier segment from last point in the path via a controlPoint to the specified endPoint.

This is an overloaded function.

void QCanvasPainter::rect(float x, float y, float width, float height)

Creates new rectangle shaped sub-path in position x, y with size width, height.

p->beginPath();
p->rect(20, 20, 160, 160);
p->fill();
p->stroke();

void QCanvasPainter::rect(const QRectF &rect)

Creates new rectangle shaped sub-path at rect. This is an overloaded method using QRectF.

This is an overloaded function.

void QCanvasPainter::removeImage(const QCanvasImage &image)

Releases the resources associated with image and removes the image from the painter.

Note: This does not need to be normally called, because resources such as textures are released in the painter destructor anyway. This function is useful when there is a need to reduce memory usage due to having a lot images, and some of them are not used anymore.

Note: Removed images can not be used in paint operations anymore.

Note: Resources such as the textures created with the underlying 3D API may not get released immediately. Such operations may get defered to subsequent frames, typically when this QCanvasPainter begins painting again after the active set of draw calls has been submitted.

See also addImage().

void QCanvasPainter::removePathGroup(int pathGroup)

Removes pathGroup from the painter cache. Calling fill() or stroke() for pathGroup after this, will regenerate the path into the group cache.

Note: This does not need to be normally called as paths are removed in the painter destructor. Only use this to reduce memory usage when pathGroup is not needed anymore or e.g. when the path has a lot less commands that it has had in the past and buffer size should be reduced.

See also fill() and stroke().

QCanvasPainter::RenderHints QCanvasPainter::renderHints() const

Returns a flag that specifies the rendering hints that are set for this painter.

See also setRenderHints() and setRenderHint().

void QCanvasPainter::reset()

Resets the current painter state to default values.

Note: This method differs from the HTML canvas 2D context reset() method so that it doesn't visually clear the canvas buffers.

// Adjust the paint state
p->setStrokeStyle("#00414A");
p->setFillStyle("#2CDE85");
p->setLineWidth(10);
QRectF rect(20, 40, 160, 50);
p->translate(rect.center());
p->rotate(qDegreesToRadians(-25));
p->translate(-rect.center());
p->beginPath();
p->roundRect(rect, 20);
p->fill();
p->stroke();
// Reset to default paint state
p->reset();
p->fillRect(20, 140, 60, 40);
p->strokeRect(120, 140, 60, 40);

See also save() and restore().

void QCanvasPainter::resetClipping()

Resets and disables clipping.

See also setClipRect().

void QCanvasPainter::resetTransform()

Resets current transform to a identity matrix.

void QCanvasPainter::restore()

Pops and restores current render state. So previously saved state will be restored. If save() has not been called and the state stack is empty, calling this does nothing.

See also save().

void QCanvasPainter::rotate(float angle)

Rotates current coordinate system clockwise by angle.

The angle is specified in radians. Use qDegreesToRadians() to convert from degrees to radians.

QRectF rect(20, 70, 160, 60);
p->translate(rect.center());
p->rotate(-M_PI / 4);
p->translate(-rect.center());
p->beginPath();
p->roundRect(rect, 10);
p->fill();
p->stroke();
p->setFillStyle(QColorConstants::Black);
p->fillText("Cute!", rect);

void QCanvasPainter::roundRect(float x, float y, float width, float height, float radius)

Creates new rounded rectangle shaped sub-path in position x, y with size width, height. Corners rounding will be radius.

p->beginPath();
p->roundRect(20, 20, 160, 160, 30);
p->fill();
p->stroke();

void QCanvasPainter::roundRect(const QRectF &rect, float radius)

Creates new rounded rectangle shaped sub-path at rect with radius corners. This is an overloaded method using QRectF.

This is an overloaded function.

void QCanvasPainter::roundRect(const QRectF &rect, float radiusTopLeft, float radiusTopRight, float radiusBottomRight, float radiusBottomLeft)

Creates new rounded rectangle shaped sub-path at rect. Corners rounding can be varying per-corner, with radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft.

This is an overloaded function.

void QCanvasPainter::roundRect(float x, float y, float width, float height, float radiusTopLeft, float radiusTopRight, float radiusBottomRight, float radiusBottomLeft)

Creates new rounded rectangle shaped sub-path in position x, y with size width, height. Corners rounding can be varying per-corner, with radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft.

p->beginPath();
p->roundRect(20, 20, 160, 160,
             0, 40, 20, 80);
p->fill();
p->stroke();

This is an overloaded function.

void QCanvasPainter::save()

Pushes and saves the current render state into a state stack. A matching restore() must be used to restore the state.

p->strokeRect(20, 20, 160, 40);
// Save and adjust the paint state
p->save();
p->setStrokeStyle(QColorConstants::Black);
p->setLineWidth(3);
p->rotate(0.1);
p->strokeRect(20, 80, 180, 20);
// Restore the saved paint state
p->restore();
p->strokeRect(20, 140, 160, 40);

See also restore().

void QCanvasPainter::scale(float scale)

Scales the current coordinat system by scale. Both x and y coordinates are scaled evenly.

QRectF rect(20, 20, 160, 160);
for (int i = 0; i < 20; i++) {
    p->beginPath();
    p->roundRect(rect, 10);
    p->stroke();
    p->translate(rect.center());
    p->scale(0.8);
    p->translate(-rect.center());
}

void QCanvasPainter::scale(float scaleX, float scaleY)

Scales the current coordinat system by scaleX and scaleY.

This is an overloaded function.

void QCanvasPainter::setAntialias(float antialias)

Set the current antialiasing amount to antialias in pixels. More antialias means smoother painting. This only affects fill and stroke painting, not images or texts. The default value is 1.0 and the maximum value is 10.0.

Antialiasing can be modified per-path so it can be set before each stroke/fill. To disable antialiasing from the whole canvas painter, use QCanvasPainter::RenderHint::Antialiasing render hint.

p->setLineWidth(6);
for (int i = 1; i < 10 ; i++) {
    int y = i * 20;
    p->setAntialias(i);
    p->beginPath();
    p->moveTo(20, y);
    p->bezierCurveTo(80, y + 20, 120,
                     y - 20, 180, y);
    p->stroke();
}

See also setRenderHints() and setTextAntialias().

void QCanvasPainter::setBrushTransform(const QTransform &transform)

Sets the current brush transform to transform. This transform is applied to both stroke and fill brushes.

void QCanvasPainter::setClipRect(float x, float y, float width, float height)

Sets the current scissor rectangle to (x, y, width, height). The scissor rectangle is transformed by the current transform.

Note: Clipping has some performance cost and it should only be used when needed.

QRectF viewArea(20, 20, 160, 160);
p->setClipRect(viewArea);
p->beginPath();
p->circle(40, 40, 110);
p->fill();
p->setFillStyle(Qt::black);
p->fillText("Clip me...", 40, 100);
p->strokeRect(viewArea);

See also resetClipping().

void QCanvasPainter::setClipRect(const QRectF &rect)

Sets the current scissor rectangle to rect. The scissor rectangle is transformed by the current transform.

Note: Clipping has some performance cost and it should only be used when needed.

This is an overloaded function.

See also resetClipping().

void QCanvasPainter::setFillStyle(const QColor &color)

Sets the fill style to a solid color. The default fill style is solid black color (0, 0, 0, 1).

p->setFillStyle(QColorConstants::Black);
p->fillRect(20, 20, 160, 160);
p->setFillStyle(QColor(0, 65, 74));
p->fillRect(40, 40, 120, 120);
p->setFillStyle("#2CDE85");
p->fillRect(60, 60, 80, 80);

void QCanvasPainter::setFillStyle(const QCanvasBrush &brush)

Sets the fill style to brush. The default fill style is solid black color (0, 0, 0, 1).

QCanvasRadialGradient g2(140, 40, 300);
g2.setStartColor(QColor(44, 222, 133));
g2.setEndColor(QColor(0, 65, 74));
p->setFillStyle(g2);
p->fillRect(20, 20, 160, 160);
g2.setCenterPosition(100, 100);
p->setFillStyle(g2);
p->fillRect(40, 40, 120, 120);

This is an overloaded function.

void QCanvasPainter::setFont(const QFont &font)

Sets the font as currently active font.

void QCanvasPainter::setGlobalAlpha(float alpha)

Sets the global alpha (transparency) value to alpha. This alpha value is applied to all rendered shapes. Already transparent paths will get proportionally more transparent as well. Alpha should be between 0.0 (fully transparent) and 1.0 (fully opaque). By default alpha is 1.0.

static QImage logo(":/qt_logo2.png");
QCanvasImage image = p->addImage(logo);
p->setFillStyle("#d9f720");
for (int i = 0; i < 4; i++) {
    float x = 100 * (i % 2);
    float y = 100 * (i / 2);
    QRectF rect(x, y, 100, 100);
    p->setGlobalAlpha(1.0 - i * 0.3);
    p->fillRect(rect);
    p->drawImage(image, rect);
}

void QCanvasPainter::setGlobalBrightness(float value)

Sets the global brightness to value. This brightess is applied to all rendered shapes. A value of 0 will cause painting to be completely black. Value can also be bigger than 1.0, to increase the brightness. By default, brightness is 1.0.

static QImage logo(":/qt_logo2.png");
QCanvasImage image = p->addImage(logo);
p->setFillStyle("#d9f720");
for (int i = 0; i < 4; i++) {
    float x = 100 * (i % 2);
    float y = 100 * (i / 2);
    QRectF rect(x, y, 100, 100);
    p->setGlobalBrightness(1.5 - i * 0.45);
    p->fillRect(rect);
    p->drawImage(image, rect);
}

void QCanvasPainter::setGlobalCompositeOperation(QCanvasPainter::CompositeOperation operation)

Sets the global composite operation mode to operation. This mode is applied to all painting operations. The default mode is QCanvasPainter::CompositeOperation::SourceOver.

void QCanvasPainter::setGlobalContrast(float value)

Sets the global contrast to value. This contrast is applied to all rendered shapes. A value of 0 will cause painting to be completely gray (0.5, 0.5, 0.5). Value can also be bigger than 1.0, to increase the contrast. By default, contrast is 1.0.

static QImage logo(":/qt_logo2.png");
QCanvasImage image = p->addImage(logo);
p->setFillStyle("#d9f720");
for (int i = 0; i < 4; i++) {
    float x = 100 * (i % 2);
    float y = 100 * (i / 2);
    QRectF rect(x, y, 100, 100);
    p->setGlobalContrast(1.5 - i * 0.45);
    p->fillRect(rect);
    p->drawImage(image, rect);
}

void QCanvasPainter::setGlobalSaturate(float value)

Sets the global saturations to value. This saturations is applied to all rendered shapes. A value of 0 will disable saturation and cause painting to be completely grayscale. Value can also be bigger than 1.0, to increase the saturation. By default, saturation is 1.0.

static QImage logo(":/qt_logo2.png");
QCanvasImage image = p->addImage(logo);
p->setFillStyle("#d9f720");
for (int i = 0; i < 4; i++) {
    float x = 100 * (i % 2);
    float y = 100 * (i / 2);
    QRectF rect(x, y, 100, 100);
    p->setGlobalSaturate(1.5 - i * 0.5);
    p->fillRect(rect);
    p->drawImage(image, rect);
}

void QCanvasPainter::setLineCap(QCanvasPainter::LineCap cap)

Sets the end of the line of stoke to cap. The default line cap is QCanvasPainter::LineCap::Butt.

QCanvasPath path;
path.moveTo(40, 60);
path.lineTo(160, 60);
p->setLineCap(QCanvasPainter::LineCap::Butt);
p->stroke(path, -1);
p->setLineCap(QCanvasPainter::LineCap::Square);
p->translate(0, 40);
p->stroke(path, -1);
p->setLineCap(QCanvasPainter::LineCap::Round);
p->translate(0, 40);
p->stroke(path, -1);

void QCanvasPainter::setLineJoin(QCanvasPainter::LineJoin join)

Sets the line join of stroke to join. The default line join is QCanvasPainter::LineJoin::Miter.

QCanvasPath path;
path.moveTo(40, 20);
path.lineTo(100, 80);
path.lineTo(160, 40);
path.lineTo(160, 70);
p->setLineJoin(QCanvasPainter::LineJoin::Miter);
p->stroke(path, -1);
p->setLineJoin(QCanvasPainter::LineJoin::Bevel);
p->translate(0, 50);
p->stroke(path, -1);
p->setLineJoin(QCanvasPainter::LineJoin::Round);
p->translate(0, 50);
p->stroke(path, -1);

See also setMiterLimit().

void QCanvasPainter::setLineWidth(float width)

Sets the line width of stroke to width in pixels. The default line width is 1.0. When the antialiasing is enabled, the line widths under a single pixel automatically fade the opacity, creating a smooth output.

for (int i = 1; i < 10 ; i++) {
    int y = i * 20;
    p->setLineWidth(0.5 * i);
    p->beginPath();
    p->moveTo(20, y);
    p->bezierCurveTo(80, y + 20, 120,
                     y - 20, 180, y);
    p->stroke();
}

See also stroke().

void QCanvasPainter::setMiterLimit(float limit)

Sets the miter limit to limit. Miter limit controls when a sharp corner is beveled. When the corner length would become longer than this limit, QCanvasPainter::LineJoin::Bevel will be applied between the lines instead. This has only effect with the QCanvasPainter::LineJoin::Miter line join. The default limit is 10.0.

See also setLineJoin().

void QCanvasPainter::setPathWinding(QCanvasPainter::PathWinding winding)

Sets the current sub-path winding to either CounterClockWise (default) or ClockWise. CounterClockWise draws solid subpaths while ClockWise draws holes.

p->beginPath();
p->roundRect(20, 20, 160, 160, 40);
p->setPathWinding(QCanvasPainter::PathWinding::ClockWise);
p->circle(140, 60, 20);
p->rect(60, 120, 80, 30);
p->fill();
p->stroke();

See also beginHoleSubPath() and beginSolidSubPath().

void QCanvasPainter::setRenderHint(QCanvasPainter::RenderHint hint, bool on = true)

Sets the given render hint on the painter if on is true; otherwise clears the render hint.

See also setRenderHints() and renderHints().

void QCanvasPainter::setRenderHints(QCanvasPainter::RenderHints hints, bool on = true)

Sets the given render hints on the painter if on is true; otherwise clears the render hints.

See also setRenderHint() and renderHints().

void QCanvasPainter::setStrokeStyle(const QColor &color)

Sets the stroke style to a solid color. The default stroke style is solid black color (0, 0, 0, 1).

p->setStrokeStyle(QColorConstants::Black);
p->strokeRect(20, 20, 160, 160);
p->setStrokeStyle(QColor(0, 65, 74));
p->strokeRect(40, 40, 120, 120);
p->setStrokeStyle("#2CDE85");
p->strokeRect(60, 60, 80, 80);

void QCanvasPainter::setStrokeStyle(const QCanvasBrush &brush)

Sets the stroke style to brush. The default stroke style is solid black color (0, 0, 0, 1).

QCanvasLinearGradient g1(180, 20, 20, 180);
g1.setStartColor(QColor(44, 222, 133));
g1.setEndColor(Qt::black);
p->setStrokeStyle(g1);
p->strokeRect(20, 20, 160, 160);
g1.setEndColor(Qt::yellow);
p->setStrokeStyle(g1);
p->strokeRect(40, 40, 120, 120);

This is an overloaded function.

void QCanvasPainter::setTextAlign(QCanvasPainter::TextAlign align)

Sets the horizontal alignment of text to align. The default alignment is QCanvasPainter::TextAlign::Start.

QFont font("Titillium Web", 22);
p->setFont(font);
p->fillRect(100, 0, 1, 200);
p->setTextAlign(QCanvasPainter::TextAlign::Left);
p->fillText("Left", 100, 40);
p->setTextAlign(QCanvasPainter::TextAlign::Center);
p->fillText("Center", 100, 70);
p->setTextAlign(QCanvasPainter::TextAlign::Right);
p->fillText("Right", 100, 100);
p->setTextAlign(QCanvasPainter::TextAlign::Start);
p->fillText("Start", 100, 130);
p->setTextAlign(QCanvasPainter::TextAlign::End);
p->fillText("End", 100, 160);

See also setTextBaseline().

void QCanvasPainter::setTextAntialias(float antialias)

Set the current text antialiasing amount. The value antialias is multiplier to normal antialiasing, meaning that 0.0 disables antialiasing and 2.0 doubles it. The default value is 1.0.

Note: Due to the used text antialiasing technique (SDF), the maximum antialiasing amount is quite limited and this affects less when the font size is small.

QFont font("Titillium Web", 20);
p->setFont(font);
p->setTextAntialias(1.0);
p->fillText("Antialiasing: 1.0", 100, 25);
p->setTextAntialias(2.0);
p->fillText("Antialiasing: 2.0", 100, 75);
p->setTextAntialias(3.0);
p->fillText("Antialiasing: 3.0", 100, 125);
p->setTextAntialias(4.0);
p->fillText("Antialiasing: 4.0", 100, 175);

void QCanvasPainter::setTextBaseline(QCanvasPainter::TextBaseline baseline)

Sets the vertical alignment (baseline) of text to baseline. The default alignment is QCanvasPainter::TextBaseline::Alphabetic.

QFont font("Titillium Web", 16);
p->setFont(font);
p->fillRect(0, 60, 200, 1);
p->fillRect(0, 140, 200, 1);
p->setTextBaseline(QCanvasPainter::TextBaseline::Bottom);
p->fillText("Bottom", 40, 60);
p->setTextBaseline(QCanvasPainter::TextBaseline::Middle);
p->fillText("Middle", 100, 60);
p->setTextBaseline(QCanvasPainter::TextBaseline::Top);
p->fillText("Top", 160, 60);
p->setTextBaseline(QCanvasPainter::TextBaseline::Alphabetic);
p->fillText("Alphabetic", 50, 140);
p->setTextBaseline(QCanvasPainter::TextBaseline::Hanging);
p->fillText("Hanging", 150, 140);

See also setTextAlign().

void QCanvasPainter::setTextDirection(QCanvasPainter::TextDirection direction)

Sets the direction of text to direction. The default direction is QCanvasPainter::TextDirection::Inherit.

void QCanvasPainter::setTextLineHeight(float height)

Sets the line height adjustment in pixels to height for wrapped text. The default line height is 0.

QRectF r1(40, 5, 120, 60);
QRectF r2(40, 70, 120, 60);
QRectF r3(40, 135, 120, 60);
p->strokeRect(r1);
p->strokeRect(r2);
p->strokeRect(r3);
p->setTextLineHeight(-10);
p->fillText("Text with line height: -10", r1);
p->setTextLineHeight(0);
p->fillText("Text with line height: 0", r2);
p->setTextLineHeight(10);
p->fillText("Text with line height: 10", r3);

void QCanvasPainter::setTextWrapMode(QCanvasPainter::WrapMode wrapMode)

Sets the text wrap mode to wrapMode. The default wrap mode is QCanvasPainter::WrapMode::NoWrap.

QRectF r1(50, 5, 100, 60);
QRectF r2(50, 70, 100, 60);
QRectF r3(50, 135, 100, 60);
p->strokeRect(r1);
p->strokeRect(r2);
p->strokeRect(r3);
QString s("This is a long string.");
p->setTextWrapMode(QCanvasPainter::WrapMode::NoWrap);
p->fillText(s, r1);
p->setTextWrapMode(QCanvasPainter::WrapMode::Wrap);
p->fillText(s, r2);
p->setTextWrapMode(QCanvasPainter::WrapMode::WrapAnywhere);
p->fillText(s, r3);

void QCanvasPainter::setTransform(const QTransform &transform)

Resets the current transform and uses transform instead.

p->beginPath();
p->roundRect(80, 20, 40, 40, 10);
p->fill();
p->stroke();
QTransform t;
t.translate(100, 20);
t.rotate(45);
t.scale(2.0, 2.0);
p->setTransform(t);
p->beginPath();
p->roundRect(20, 20, 40, 40, 10);
p->fill();
p->stroke();

See also transform().

void QCanvasPainter::skew(float angleX, float angleY = 0.0f)

Skews (shears) the current coordinate system along X axis by angleX and along Y axis by angleY. Angles are specifid in radians.

QRectF rect(40, 70, 120, 60);
p->translate(rect.center());
p->skew(-0.6);
p->translate(-rect.center());
p->beginPath();
p->roundRect(rect, 10);
p->fill();
p->stroke();
p->setFillStyle(QColorConstants::Black);
p->fillText("Cute!", rect);

void QCanvasPainter::stroke()

Strokes the current path with current stroke style.

p->beginPath();
p->rect(20, 20, 40, 160);
p->rect(140, 20, 40, 160);
p->circle(100, 100, 60);
p->stroke();

See also setStrokeStyle().

void QCanvasPainter::stroke(const QCanvasPath &path, int pathGroup = 0)

Strokes the path with current stroke style and belonging into pathGroup. Painting through QCanvasPath is optimal when the path contains more commands is mostly static. By default, pathGroup is 0, so using the first group. When pathGroup is -1, the path will not be cached on GPU side. More information about using path cache groups in QCanvasPath documentation. Calling beginPath() before this method is not required.

// m_path is QCanvasPath
if (m_path.isEmpty()) {
    for (int i = 0; i < 16; i++) {
        int h = 100 + 60 * sin(i);
        m_path.rect(22 + i * 10,
                    180 - h,
                    6, h);
    }
}
p->stroke(m_path);

This is an overloaded function.

See also setStrokeStyle().

void QCanvasPainter::strokeRect(float x, float y, float width, float height)

Draws a stoked rectangle into specified position ( x, y) at size width, height.

Note: This is provided for convenience. When stroking more than just a single rect, prefer using rect().

p->strokeRect(20, 20, 160, 160);
// The above code does same as:
// p->beginPath();
// p->rect(20, 20, 160, 160);
// p->stroke();

void QCanvasPainter::strokeRect(const QRectF &rect)

Draws a stoked rectangle into rect. This is an overloaded method using QRectF.

Note: This is provided for convenience. When stroking more than just a single rect, prefer using rect().

This is an overloaded function.

QRectF QCanvasPainter::textBoundingBox(const QString &text, float x, float y, float maxWidth = -1)

Measures bounding box of a text string at (x, y). To measure multi-line text, set optional maxWidth parameter to preferred row width in pixels. Returns QRectF with values [xmin, ymin, width, height]. Measured values are returned in local coordinate space.

QString s("Built with Qt");
QPointF pos1(20, 20);
QRectF box1 = p->textBoundingBox(s, pos1);
p->strokeRect(box1);
p->fillText(s, pos1);
p->setTextWrapMode(QCanvasPainter::WrapMode::WordWrap);
p->setTextAlign(QCanvasPainter::TextAlign::Center);
QPointF pos2(100, 80);
QRectF box2 = p->textBoundingBox(s, pos2, 100);
p->strokeRect(box2);
p->fillText(s, pos2, 100);

QRectF QCanvasPainter::textBoundingBox(const QString &text, const QRectF &rect)

Measures bounding box of a text string at rect. Returns QRectF with values [xmin, ymin, width, height]. Measured values are returned in local coordinate space.

This is an overloaded function.

QRectF QCanvasPainter::textBoundingBox(const QString &text, QPointF point, float maxWidth = -1)

Measures bounding box of a text string at point. To measure multi-line text, set optional maxWidth parameter to preferred row width in pixels. Returns QRectF with values [xmin, ymin, width, height]. Measured values are returned in local coordinate space.

This is an overloaded function.

void QCanvasPainter::transform(const QTransform &transform)

Multiplies the current coordinate system by specified transform.

QTransform t;
t.translate(100, 100);
t.rotate(36);
t.translate(-100, -100);
for (int i = 0; i < 10; i++) {
    p->transform(t);
    p->beginPath();
    p->roundRect(80, 15, 40, 20, 10);
    p->fill();
    p->stroke();
}

See also setTransform().

void QCanvasPainter::translate(float x, float y)

Translates current coordinate system by x and y.

auto paintRect = [p]() {
    p->beginPath();
    p->roundRect(20, 20, 160, 60, 10);
    p->fill();
    p->stroke();
};
paintRect();
p->translate(0, 100);
paintRect();

void QCanvasPainter::translate(QPointF point)

Translates current coordinate system by point.

This is an overloaded function.

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.