PySide6.QtCanvasPainter.QCanvasPath¶
- class QCanvasPath¶
QCanvasPathis the native path format ofQCanvasPainter. More…Synopsis¶
Methods¶
def
__init__()def
addPath()def
arc()def
arcTo()def
bezierCurveTo()def
circle()def
clear()def
closePath()def
commandsSize()def
ellipse()def
isEmpty()def
lineTo()def
moveTo()def
__ne__()def
__eq__()def
positionAt()def
rect()def
reserve()def
roundRect()def
setPathWinding()def
sliced()def
squeeze()def
swap()
Note
This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE
Detailed Description¶
A painter path is an object composed of a number of graphical building blocks, such as rectangles, ellipses, lines, and curves.
QCanvasPathAPI matches toQCanvasPainterpath painting, making it easy to adjust code between painting directly or painting into a path. The main reason useQCanvasPathis to avoid recreating paths that are static and used in every frame of the rendering, and to possibly enable the caching of the path-related rendering data (such, as the vertex and index data generated from it), instead of regenerating it every time the path is filled or stroked.Compared to QPainterPath,
QCanvasPathis more optimized for rendering with fewer features for comparing or adjusting the paths. In particular:There are no methods for intersection or subtraction between two paths.
There is no method for translating the path.
There is no method for adding text.
The fill rule is always
WindingFill(nonzero),OddEvenFillis not supported.
From a functionality point of view,
QCanvasPathis more similar to HTML Canvas Path2D , with some additions and the API matching toQCanvasPainter.Painting paths through
QCanvasPathallows the engine to cache the path geometry (vertices). This improves the performance of static paths, while potentially increasing CPU and GPU memory consumption.When painting paths using
fill()orstroke()that takeQCanvasPathas a parameter, it is possible to set apathGroupas a second parameter.By default,
pathGroupis-1, which means that the path data will not be attempted to be cached, and so rendering happens mostly identically to when doing direct painting using beginPath(), followed by path definition commands, and finally a fill or stroke.Setting
pathGroupto a value of0or any higher number will enable the caching and reuse of the path’s generated geometry. Arranging paths into path groups allows efficient optimization of the rendering performance and memory usage. Paths that belong together and often change at the same time should be in the same group for optimal results.When the path changes, its data, even if it was cached, is automatically updated. Things that cause a geometry update of the path group are:
Clearing the path elements or adding new elements.
Changing the stroke line width (
setLineWidth(), relevant for strokes).Adjusting antialiasing amount (
setAntialias(), relevant both for fills and strokes).Changing line cap or line join type (
setLineCap(),setLineJoin(), relevant for strokes).Adjusting
render hints(relevant both for fills and strokes).
Note that changing the state transform (
transform(),rotate()etc.) does not invalidate the path, so moving/scaling/rotating a cached path is very efficient.As an example, consider a
QCanvasPathpwith a very large number of commands in it. Stroking or filling this pathpcan be an expensive operation due to the amount of work performed on the CPU side. The vertex data may be regenerated and uploaded into GPU buffers for each of those stroke or fill operation, in every frame. That is not ideal when the path is static and all we want is to draw it again and again in every frame as efficiently as possible.When a path group is specifed, for example replacing
stroke(p)withstroke(p, 5), then the renderer has the option to maintain dedicated vertex and index buffers for pathp, and any other path that has the same group (5) specified in a stroke or fill command.Assuming that path
p(the commands in theQCanvasPath) do not change, repeatedly filling or stroking this path will become a cheap operation, because all data is already there in the GPU buffers dedicated to path group5. Transforming is also cheap, since with cached path groups transformations happen in the vertex shader, not on the geometry itself.In the following code snippet, when
m_pathis complex enough, its commands do not change, and it is stroked with the same stroke width, antialiasing amount, etc. in every frame, then the following can be significantly more efficient than not using path groups:// m_path is QCanvasPath with lots of commands in it const int pathGroup = 5; // in every frame: painter->stroke(m_path, pathGroup); // ... other draw commands painter->translate(100, 0); painter->stroke(*m_path, pathGroup); // ... other draw commands
When stroking
m_paththe second, third, and later times, the rendering will be very cheap compared to not using path groups, because no path geometry processing will need to happen on the CPU side. Changing the transform by applying a translation does not invalidate the cached path group data, hence the translated stroke() call is just as fast.What happens if one of the relevant states listed above change? For example, if the path is drawn with two different stroke widths:
// m_path is QCanvasPath with lots of commands in it const int pathGroup = 5; // in every frame: painter->setStrokeWidth(4); painter->stroke(m_path, pathGroup); // ... other draw commands painter->translate(100, 0); painter->setStrokeWidth(8); painter->stroke(*m_path, pathGroup); // ... other draw commands
This is still very efficient, since the path vertex data will be cached and reused for both stroke width 4 and 8, but the resource usage will increase slightly, since the GPU buffer for path group
5will now contain both the stroke width 4 and 8 version of the path geometry.One way to think of path groups is a caching mechanism where the path group value is treated as the first level cache key, while the
QCanvasPathobject, the antialiasing amount, the render hints, and, in case of stroking, the stroke width, line cap, and line join form the second level cache key (within the path group).Changing the path commands (the elements in the
QCanvasPath) is always expensive, because that will always lead to rebuilding the associated data on the CPU and GPU side. As a somewhat extreme example, if aQCanvasPathchanges its commands in every frame, then there is no point in using path groups (andQCanvasPath, even) for that particular path, as there are no benefits compared to direct path drawing viaQCanvasPainterfunctions.In cases where the path group will not be used anymore in drawing, or the application wants to free up memory as much as possible, the cache can be released by calling
removePathGroup(). This isn’t usually needed, as the cached paths are automatically released during the painter destructor.See also
- __init__()¶
Constructs an empty path.
- __init__(path)
- Parameters:
path –
QCanvasPath
Constructs a path that is a copy of the given
path.- __init__(commandsSize[, commandsDataSize=-1])
- Parameters:
commandsSize – int
commandsDataSize – int
Constructs an empty path, allocating space for
commandsSizeamount of commands and optionallycommandsDataSizeamount of data. IfcommandsDataSizeparameter is not given, space is automatically reserved for2 * commandsSizeamount of data, which is optimal amount when the path commands are straight lines (moveTo(),lineTo(),rect()).Reserving correct space is an optimization for path creation and memory usage. It isn’t mandatory as sufficient space will automatically be ensured while adding commands to the path.
See also
- addPath(path[, transform=QTransform()])¶
- Parameters:
path –
QCanvasPathtransform –
QTransform
Adds
pathinto this path, optionally usingtransformto alter the path points. Whentransformis not provided (or it is identity matrix), this operation is very fast as it reuses the path data.- addPath(path, start, count[, transform=QTransform()])
- Parameters:
path –
QCanvasPathstart – int
count – int
transform –
QTransform
Adds
pathinto the current path, starting from the command atstartand includingcountamount of commands. Optionally usingtransformto alter the path points. The range ofstartandcountis checked, so that commands are not accessed more thancommandsSize(). In case the path shouldn’t continue from the current path position, call firstmoveTo()withpath.positionAt(start - 1).- arc(centerPoint, radius, a0, a1[, direction=QCanvasPainter.PathWinding.ClockWise[, connection=QCanvasPainter.PathConnection.Connected]])¶
- Parameters:
centerPoint –
QPointFradius – float
a0 – float
a1 – float
direction –
PathWindingconnection –
PathConnection
Creates an arc centered on
centerPointwith the givenradius, starting at an angle ofa0radians and ending ata1radians. The arc spans the givendirection. WhenconnectionisNotConnected, the previous path is closed and a new sub-path is started.- arc(centerX, centerY, radius, a0, a1[, direction=QCanvasPainter.PathWinding.ClockWise[, connection=QCanvasPainter.PathConnection.Connected]])
- Parameters:
centerX – float
centerY – float
radius – float
a0 – float
a1 – float
direction –
PathWindingconnection –
PathConnection
Creates an arc centered on QPointF(
centerX,centerY) with the givenradius, starting at an angle ofa0radians and ending ata1radians. The arc spans the givendirection. WhenconnectionisNotConnected, the previous path is closed and a new sub-path is started.- arcTo(controlPoint1, controlPoint2, radius)¶
Creates an arc using the points
point1andpoint2with the givenradius.- arcTo(c1x, c1y, c2x, c2y, radius)
- Parameters:
c1x – float
c1y – float
c2x – float
c2y – float
radius – float
Creates an arc using the points QPointF(
x1,y1) and QPointF(x2,y2) with the givenradius.- beginHoleSubPath()¶
Start a hole subpath. This is equivalent to
setPathWinding(QCanvasPainter::PathWinding::ClockWise))See also
- beginSolidSubPath()¶
Start a solid subpath. This is equivalent to
setPathWinding(QCanvasPainter::PathWinding::CounterClockWise))See also
- bezierCurveTo(controlPoint1, controlPoint2, endPoint)¶
Adds a cubic Bezier curve between the current position and the given
endPointusing the control points specified bycontrolPoint1, andcontrolPoint2.After the curve is added, the current position is updated to be at the end point of the curve.
- bezierCurveTo(c1x, c1y, c2x, c2y, x, y)
- Parameters:
c1x – float
c1y – float
c2x – float
c2y – float
x – float
y – float
Adds a cubic Bezier curve between the current position and the end point specified by
xandy, using the control points specified bycp1X,cp1Y,cp2X, andcp2Y.After the curve is added, the current position is updated to be at the end point of the curve.
Adds a circle with center at
centerPointand the givenradiusto the path.- circle(x, y, radius)
- Parameters:
x – float
y – float
radius – float
Adds a circle with center at QPointF(
x,y) and the givenradiusto the path.- clear()¶
Clears the path commands and data.
Call this when the path commands change to recreate the path. This does not affect the memory usage, use
reserve()andsqueeze()for that.- closePath()¶
Closes the current subpath by drawing a line to the beginning of the subpath, automatically starting a new path.
- commandsCapacity()¶
- Return type:
int
Returns the capacity of commands in the path.
See also
- commandsDataCapacity()¶
- Return type:
int
Returns the capacity of commands data in the path.
See also
- commandsDataSize()¶
- Return type:
int
Returns the amount of commands data in the path.
Commands data basically means the points required by the commands.
Note
Some path elements require several data points. For example
closePath()requires0,moveTo()andlineTo()require2,bezierCurveTo()requires 6 androundRect()requires34data points.- commandsSize()¶
- Return type:
int
Returns the amount of commands in the path.
Note
Some path elements require several commands. For example
moveTo()andlineTo()require1command,bezierCurveTo()requires6commands androundRect()10commands.Returns the current position of the path. This means position where previous path command (
moveTo(),lineTo(),bezierCurveTo()etc.) has ended. When the path is empty, returns (0.0, 0.0).Creates an ellipse within the rectangle
rectand adds it to the path as a closed subpath.- ellipse(x, y, radiusX, radiusY)
- Parameters:
x – float
y – float
radiusX – float
radiusY – float
Creates an ellipse centered at (
x,y), with radii defined byradiusX,radiusYand adds it to the path as a closed subpath.- isEmpty()¶
- Return type:
bool
Returns true when the path is empty.
See also
Adds a straight line from the current position to the given
point. After the line is drawn, the current position is updated to be at the end point of the line.- lineTo(x, y)
- Parameters:
x – float
y – float
Draws a line from the current position to the point (
x,y).Moves the current point to the given
point, implicitly starting a new subpath and closing the previous one.- moveTo(x, y)
- Parameters:
x – float
y – float
Moves the current position to (
x,y) and starts a new subpath, implicitly closing the previous path.- __ne__(rhs)¶
- Parameters:
rhs –
QCanvasPath- Return type:
bool
- __eq__(rhs)¶
- Parameters:
rhs –
QCanvasPath- Return type:
bool
Returns the position of the path at
index. This means position where path command (moveTo(),lineTo(),bezierCurveTo()etc.) is atindex. The index need to be between0andcommandsSize()- 1. When the path is empty, returns (0.0, 0.0).Adds a quadratic Bezier curve between the current position and the given
endPointwith the control point specified bycontrolPoint.- quadraticCurveTo(cx, cy, x, y)
- Parameters:
cx – float
cy – float
x – float
y – float
Adds a quadratic Bezier curve between the current point and the endpoint (
x,y) with the control point specified by (cpX,cpY).Creates a rectangle specified by
rect- rect(x, y, width, height)
- Parameters:
x – float
y – float
width – float
height – float
Creates a rectangle positioned at QPointF(
x,y) with the givenwidthandheight.- reserve(commandsSize)¶
- Parameters:
commandsSize – int
Reserves a given amounts of space in
QCanvasPath‘s internal memory.Attempts to allocate memory for at least
commandsSizecommands. Some path elements require multiple commands, seecommandsSize()andcommandsDataSize().Space is automatically reserved for
2 * commandsSizeamount of data, which is optimal amount when the path commands are straight lines (moveTo(),lineTo(),rect()).Reserving correct space is an optimization for path creation and memory usage. It isn’t mandatory as sufficient space will automatically be ensured while adding commands into the path.
- reserve(commandsSize, commandsDataSize)
- Parameters:
commandsSize – int
commandsDataSize – int
Reserves a given amounts of space in
QCanvasPath‘s internal memory.Attempts to allocate memory for at least
commandsSizecommands andcommandsDataSizedata points. Some path elements require multiple commands, seecommandsSize()andcommandsDataSize().Reserving correct space is an optimization for path creation and memory usage. It isn’t mandatory as sufficient space will automatically be ensured while adding commands into the path.
Adds the given rectangle
rectwith rounded corners to the path. The corners are quarter circles with the givenradius.- roundRect(rect, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft)
- Parameters:
rect –
QRectFradiusTopLeft – float
radiusTopRight – float
radiusBottomRight – float
radiusBottomLeft – float
Adds the rectangle
rectwith rounded corners to the path. The corners are quarter circles with radiusradiusTopLeft,radiusTopRightradiusBottomRightandradiusBottomLeft, respectively.- roundRect(x, y, width, height, radius)
- Parameters:
x – float
y – float
width – float
height – float
radius – float
Adds the given rectangle
x,y,width,heightwith rounded corners to the path. The corners are quarter circles with the givenradius.- roundRect(x, y, width, height, radiusTopLeft, radiusTopRight, radiusBottomRight, radiusBottomLeft)
- Parameters:
x – float
y – float
width – float
height – float
radiusTopLeft – float
radiusTopRight – float
radiusBottomRight – float
radiusBottomLeft – float
Adds the rectangle
x,y,width,heightwith rounded corners to the path. The corners are quarter circles with radiusradiusTopLeft,radiusTopRightradiusBottomRightandradiusBottomLeft, respectively.- setPathWinding(winding)¶
- Parameters:
winding –
PathWinding
Sets the current sub-path
windingto eitherQCanvasPainter::CounterClockWise(default) orQCanvasPainter::ClockWise. CounterClockWise draws solid subpaths while ClockWise draws holes.Note
This is a command, similar to
lineTo(),moveTo(), etc., and therefore setting the winding should be done before the rest of the commands to which the changed winding is meant to be applied to.- sliced(start, count[, transform=QTransform()])¶
- Parameters:
start – int
count – int
transform –
QTransform
- Return type:
Returns a new path containing the commands from this path, starting from the command at
startand includingcountamount of commands, optionally usingtransformto alter the path points.The range of
startandcountis checked, so that commands are not accessed more thancommandsSize(). In case the command atstartis notMoveTo, the first command will be replaced withMoveToso that this slice is an individual path.- squeeze()¶
Releases any memory not required to store the path commands and data. This can be used to reduce the memory usage after calling the
reserve().Normally this is not needed to be used, but it can be useful when the path size has been big due to reserving or adding many elements (
lineTo(),bezierCurveTo()etc.) and then size is expected to be much smaller in future so calling firstreserve()and thensqueeze(), will release some memory.See also
- swap(other)¶
- Parameters:
other –
QCanvasPath
Swaps this path with
other. This operation is very fast and never fails.