PySide6.QtGui.QPainter¶
- class QPainter¶
The
QPainterclass performs low-level painting on widgets and other paint devices. More…Inherited by:
QStylePainterSynopsis¶
Methods¶
def
__init__()def
__enter__()def
__exit__()def
background()def
backgroundMode()def
begin()def
boundingRect()def
brush()def
brushOrigin()def
clipPath()def
clipRegion()def
device()def
drawArc()def
drawChord()def
drawEllipse()def
drawGlyphRun()def
drawImage()def
drawLine()def
drawLines()def
drawPath()def
drawPicture()def
drawPie()def
drawPixmap()def
drawPoint()def
drawPoints()def
drawPointsNp()def
drawPolygon()def
drawPolyline()def
drawRect()def
drawRects()def
drawStaticText()def
drawText()def
drawTextItem()def
end()def
eraseRect()def
fillPath()def
fillRect()def
font()def
fontInfo()def
fontMetrics()def
hasClipping()def
isActive()def
opacity()def
paintEngine()def
pen()def
renderHints()def
resetTransform()def
restore()def
rotate()def
save()def
scale()def
setBackground()def
setBrush()def
setBrushOrigin()def
setClipPath()def
setClipRect()def
setClipRegion()def
setClipping()def
setFont()def
setOpacity()def
setPen()def
setRenderHint()def
setRenderHints()def
setTransform()def
setViewport()def
setWindow()def
shear()def
strokePath()def
testRenderHint()def
transform()def
translate()def
viewport()def
window()def
worldTransform()
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¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
QPainterprovides 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.QPaintercan operate on any object that inherits theQPaintDeviceclass.The common use of
QPainteris inside a widget’s paint event: Construct and customize (e.g. set the pen or the brush) the painter. Then draw. Remember to destroy theQPainterobject after drawing. For example:def paintEvent(self, arg__0): painter = QPainter(self) painter.setPen(Qt.GlobalColor.blue) painter.setFont(QFont("Arial", 30)) painter.drawText(rect(), Qt.AlignmentFlag.AlignCenter, "Qt")
The core functionality of
QPainteris drawing, but the class also provide several functions that allows you to customizeQPainter‘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 thebegin()function and the constructor that takes aQPaintDeviceargument. Theend()function, and the destructor, deactivates it.Together with the
QPaintDeviceandQPaintEngineclasses,QPainterform the basis for Qt’s paint system.QPainteris the class used to perform drawing operations.QPaintDevicerepresents a device that can be painted on using aQPainter.QPaintEngineprovides 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, andpaintEngine()returns the paint engine that the painter is currently operating on. For more information, see the Paint System .Sometimes it is desirable to make someone else paint on an unusual
QPaintDevice.QPaintersupports a static function to do this, setRedirected().Warning
When the paintdevice is a widget,
QPaintercan only be used inside a paintEvent() function or in a function called by paintEvent().Settings¶
There are several settings that you can customize to make
QPainterdraw according to your preferences:font()is the font used for drawing text. If the painterisActive(), you can retrieve information about the currently set font, and its metrics, using thefontInfo()andfontMetrics()functions respectively.brush()defines the color or pattern that is used for filling shapes.pen()defines the color or stipple that is used for drawing lines or boundaries.backgroundMode()defines whether there is abackground()or not, i.e it is either Qt::OpaqueMode or Qt::TransparentMode.background()only applies whenbackgroundMode()is Qt::OpaqueMode andpen()is a stipple. In that case, it describes the color of the background pixels in the stipple.brushOrigin()defines the origin of the tiled brushes, normally the origin of widget’s background.viewport(),window(),worldTransform()make up the painter’s coordinate transformation system. For more information, see theCoordinate Transformationssection and the Coordinate System documentation.hasClipping()tells whether the painter clips at all. (The paint device clips, too.) If the painter clips, it clips toclipRegion().layoutDirection()defines the layout direction used by the painter when drawing text.worldMatrixEnabled()tells whether world transformation is enabled.viewTransformEnabled()tells whether view transformation is enabled.
Note that some of these settings mirror settings in some paint devices, e.g. QWidget::font(). The
begin()function (or equivalently theQPainterconstructor) copies these attributes from the paint device.You can at any time save the
QPainter‘s state by calling thesave()function which saves all the available settings on an internal stack. Therestore()function pops them back.Drawing¶
QPainterprovides functions to draw most primitives:drawPoint(),drawPoints(),drawLine(),drawRect(),drawRoundedRect(),drawEllipse(),drawArc(),drawPie(),drawChord(),drawPolyline(),drawPolygon(),drawConvexPolygon()and drawCubicBezier(). The two convenience functions,drawRects()anddrawLines(), draw the given number of rectangles or lines in the given array of QRects or QLines using the current pen and brush.The
QPainterclass also provides thefillRect()function which fills the given QRect, with the givenQBrush, and theeraseRect()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
QPainterclass.If you need to draw a complex shape, especially if you need to do so repeatedly, consider creating a
QPainterPathand drawing it usingdrawPath().Painter Paths example
The
QPainterPathclass 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.

QPainteralso provides thefillPath()function which fills the givenQPainterPathwith the givenQBrush, and thestrokePath()function that draws the outline of the given path (i.e. strokes the path).See also the Vector Deformation example which shows how to use advanced vector techniques to draw text using a
QPainterPath, the Gradients example which shows the different types of gradients that are available in Qt, and the Path Stroking example which shows Qt’s built-in dash patterns and shows how custom patterns can be used to extend the range of available patterns.Vector Deformation
Gradients
Path Stroking



Text drawing is done using
drawText(). When you need fine-grained positioning,boundingRect()tells you where a givendrawText()command will draw.Drawing Pixmaps and Images¶
There are functions to draw pixmaps/images, namely
drawPixmap(),drawImage()anddrawTiledPixmap(). BothdrawPixmap()anddrawImage()produce the same result, except thatdrawPixmap()is faster on-screen whiledrawImage()may be faster on a QPrinter or other devices.There is a
drawPicture()function that draws the contents of an entireQPicture. ThedrawPicture()function is the only function that disregards all the painter’s settings asQPicturehas its own settings.Drawing High Resolution Versions of Pixmaps and Images¶
High resolution versions of pixmaps have a device pixel ratio value larger than 1 (see
QImageReader,devicePixelRatio()). Should it match the value of the underlyingQPaintDevice, it is drawn directly onto the device with no additional transformation applied.This is for example the case when drawing a
QPixmapof 64x64 pixels size with a device pixel ratio of 2 onto a high DPI screen which also has a device pixel ratio of 2. Note that the pixmap is then effectively 32x32 pixels in user space. Code paths in Qt that calculate layout geometry based on the pixmap size will use this size. The net effect of this is that the pixmap is displayed as high DPI pixmap rather than a large pixmap.Rendering Quality¶
To get the optimal rendering result using
QPainter, you should use the platform independentQImageas paint device; i.e. usingQImagewill ensure that the result has an identical pixel representation on any platform.The
QPainterclass also provides a means of controlling the rendering quality through itsRenderHintenum and the support for floating point precision: All the functions for drawing primitives have floating point versions.painter.drawEllipse(QRectF(-diameter / 2.0, -diameter / 2.0, diameter, diameter))
These are often used in combination with the
Antialiasingrender hint.painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
Comparing concentric circles with int and float, and with or without anti-aliased rendering. Using the floating point precision versions produces evenly spaced rings. Anti-aliased rendering results in smooth circles.

The
RenderHintenum specifies flags toQPainterthat may or may not be respected by any given engine.Antialiasingindicates that the engine should antialias edges of primitives if possible,TextAntialiasingindicates that the engine should antialias text if possible, and theSmoothPixmapTransformindicates that the engine should use a smooth pixmap transformation algorithm.The
renderHints()function returns a flag that specifies the rendering hints that are set for this painter. Use thesetRenderHint()function to set or clear the currently setRenderHints.Coordinate Transformations¶
Normally, the
QPainteroperates on the device’s own coordinate system (usually pixels), butQPainterhas good support for coordinate transformations.The most commonly used transformations are scaling, rotation, translation and shearing. Use the
scale()function to scale the coordinate system by a given offset, therotate()function to rotate it clockwise andtranslate()to translate it (i.e. adding a given offset to the points). You can also twist the coordinate system around the origin using theshear()function. See the Affine Transformations example for a visualization of a sheared coordinate system.See also the Transformations example which shows how transformations influence the way that
QPainterrenders graphics primitives. In particular it shows how the order of transformations affects the result.Affine Transformations Example
The Affine Transformations example shows 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 transformation operations operate on the transformation
worldTransform(). A matrix transforms a point in the plane to another point. For more information about the transformation matrix, see the Coordinate System andQTransformdocumentation.The
setWorldTransform()function can replace or add to the currently setworldTransform(). TheresetTransform()function resets any transformations that were made usingtranslate(),scale(),shear(),rotate(),setWorldTransform(),setViewport()andsetWindow()functions. ThedeviceTransform()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 byQPainter‘scombinedTransform(), a combination ofviewport()andwindow()andworldTransform(). Theviewport()represents the physical coordinates specifying an arbitrary rectangle, thewindow()describes the same rectangle in logical coordinates, and theworldTransform()is identical with the transformation matrix.See also Coordinate System
Clipping¶
QPaintercan clip any drawing operation to a rectangle, a region, or a vector path. The current clip is available using the functionsclipRegion()andclipPath(). Whether paths or regions are preferred (faster) depends on the underlyingpaintEngine(). For example, theQImagepaint 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 ofclipRegion()orhasClipping().Composition Modes¶
QPainterprovides theCompositionModeenum 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
SourceandSourceOver.Sourceis used to draw opaque objects onto a paint device. In this mode, each pixel in the source replaces the corresponding pixel in the destination. InSourceOvercomposition 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 graphic 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, effectively clearing those, while the primitive only overwrites its own area.

Composition Modes Example
The Composition Modes example, available in Qt’s examples directory, allows you to experiment with the various composition modes and see the results immediately.
Limitations¶
If you are using coordinates with Qt’s raster-based paint engine, it is important to note that, while coordinates greater than +/- 2 15 can be used, any painting performed with coordinates outside this range is not guaranteed to be shown; the drawing may be clipped. This is due to the use of
short intin the implementation.The outlines generated by Qt’s stroker are only an approximation when dealing with curved shapes. It is in most cases impossible to represent the outline of a bezier curve segment using another bezier curve segment, and so Qt approximates the curve outlines by using several smaller curves. For performance reasons there is a limit to how many curves Qt uses for these outlines, and thus when using large pen widths or scales the outline error increases. To generate outlines with smaller errors it is possible to use the
QPainterPathStrokerclass, which has the setCurveThreshold member function which let’s the user specify the error tolerance. Another workaround is to convert the paths to polygons first and then draw the polygons instead.Performance¶
QPainteris a rich framework that allows developers to do a great variety of graphical operations, such as gradients, composition modes and vector graphics. AndQPaintercan do this across a variety of different hardware and software stacks. Naturally the underlying combination of hardware and software has some implications for performance, and ensuring that every single operation is fast in combination with all the various combinations of composition modes, brushes, clipping, transformation, etc, is close to an impossible task because of the number of permutations. As a compromise we have selected a subset of theQPainterAPI and backends, where performance is guaranteed to be as good as we can sensibly get it for the given combination of hardware and software.The backends we focus on as high-performance engines are:
Raster - This backend implements all rendering in pure software and is always used to render into QImages. For optimal performance only use the format types
Format_ARGB32_Premultiplied,Format_RGB32orFormat_RGB16. Any other format, includingFormat_ARGB32, has significantly worse performance. This engine is used by default for QWidget andQPixmap.OpenGL 2.0 (ES) - This backend is the primary backend for hardware accelerated graphics. It can be run on desktop machines and embedded devices supporting the OpenGL 2.0 or OpenGL/ES 2.0 specification. This includes most graphics chips produced in the last couple of years. The engine can be enabled by using
QPainteronto a QOpenGLWidget.
These operations are:
Simple transformations, meaning translation and scaling, pluss 0, 90, 180, 270 degree rotations.
drawPixmap()in combination with simple transformations and opacity with non-smooth transformation mode (QPainter::SmoothPixmapTransformnot enabled as a render hint).Rectangle fills with solid color, two-color linear gradients and simple transforms.
Rectangular clipping with simple transformations and intersect clip.
Composition Modes
QPainter::CompositionMode_SourceandCompositionMode_SourceOver.Rounded rectangle filling using solid color and two-color linear gradients fills.
3x3 patched pixmaps, via qDrawBorderPixmap.
This list gives an indication of which features to safely use in an application where performance is critical. For certain setups, other operations may be fast too, but before making extensive use of them, it is recommended to benchmark and verify them on the system where the software will run in the end. There are also cases where expensive operations are ok to use, for instance when the result is cached in a
QPixmap.See also
QPaintDeviceQPaintEngineQt SVGBasic Drawing ExampleDrawing Utility Functions- class RenderHint¶
(inherits
enum.Flag) Renderhints are used to specify flags toQPainterthat may or may not be respected by any given engine.Constant
Description
QPainter.Antialiasing
Indicates that the engine should antialias edges of primitives if possible.
QPainter.TextAntialiasing
Indicates that the engine should antialias text if possible. To forcibly disable antialiasing for text, do not use this hint. Instead, set
NoAntialiason your font’s style strategy.QPainter.SmoothPixmapTransform
Indicates that the engine should use a smooth pixmap transformation algorithm (such as bilinear) rather than nearest neighbor.
QPainter.VerticalSubpixelPositioning
Allow text to be positioned at fractions of pixels vertically as well as horizontally, if this is supported by the font engine. This is currently supported by Freetype on all platforms when the hinting preference is
PreferNoHinting, and also on macOS. For most use cases this will not improve visual quality, but may increase memory consumption and some reduction in text rendering performance. Therefore, enabling this is not recommended unless the use case requires it. One such use case could be aligning glyphs with other visual primitives. This value was added in Qt 6.1.QPainter.LosslessImageRendering
Use a lossless image rendering, whenever possible. Currently, this hint is only used when
QPainteris employed to output a PDF file through QPrinter orQPdfWriter, wheredrawImage()/drawPixmap()calls will encode images using a lossless compression algorithm instead of lossy JPEG compression. This value was added in Qt 5.13.QPainter.NonCosmeticBrushPatterns
When painting with a brush with one of the predefined pattern styles, transform the pattern too, along with the object being painted. The default is to treat the pattern as cosmetic, so that the pattern pixels will map directly to device pixels, independently of any active transformations. This value was added in Qt 6.4.
See also
renderHints()setRenderHint()Rendering Quality
- class PixmapFragmentHint¶
Constant
Description
QPainter.OpaqueHint
(inherits
enum.Flag) Indicates that the pixmap fragments to be drawn are opaque. Opaque fragments are potentially faster to draw.See also
drawPixmapFragments()PixmapFragment
- class CompositionMode¶
Defines the modes supported for digital image compositing. Composition modes are used to specify how the pixels in one image, the source, are merged with the pixel in another image, the destination.
Please note that the bitwise raster operation modes, denoted with a RasterOp prefix, are only natively supported in the X11 and raster paint engines. This means that the only way to utilize these modes on the Mac is via a
QImage. The RasterOp denoted blend modes are not supported for pens and brushes with alpha components. Also, turning on theAntialiasingrender hint will effectively disable the RasterOp modes.
The most common type is SourceOver (often referred to as just alpha blending) where the source pixel is blended on top of the destination pixel in such a way that the alpha component of the source defines the translucency of the pixel.
Several composition modes require an alpha channel in the source or target images to have an effect. For optimal performance the image format
Format_ARGB32_Premultipliedis preferred.When a composition mode is set it applies to all painting operator, pens, brushes, gradients and pixmap/image drawing.
Constant
Description
QPainter.CompositionMode_SourceOver
This is the default mode. The alpha of the source is used to blend the pixel on top of the destination.
QPainter.CompositionMode_DestinationOver
The alpha of the destination is used to blend it on top of the source pixels. This mode is the inverse of CompositionMode_SourceOver.
QPainter.CompositionMode_Clear
The pixels in the destination are cleared (set to fully transparent) independent of the source.
QPainter.CompositionMode_Source
The output is the source pixel. (This means a basic copy operation and is identical to SourceOver when the source pixel is opaque).
QPainter.CompositionMode_Destination
The output is the destination pixel. This means that the blending has no effect. This mode is the inverse of CompositionMode_Source.
QPainter.CompositionMode_SourceIn
The output is the source, where the alpha is reduced by that of the destination.
QPainter.CompositionMode_DestinationIn
The output is the destination, where the alpha is reduced by that of the source. This mode is the inverse of CompositionMode_SourceIn.
QPainter.CompositionMode_SourceOut
The output is the source, where the alpha is reduced by the inverse of destination.
QPainter.CompositionMode_DestinationOut
The output is the destination, where the alpha is reduced by the inverse of the source. This mode is the inverse of CompositionMode_SourceOut.
QPainter.CompositionMode_SourceAtop
The source pixel is blended on top of the destination, with the alpha of the source pixel reduced by the alpha of the destination pixel.
QPainter.CompositionMode_DestinationAtop
The destination pixel is blended on top of the source, with the alpha of the destination pixel is reduced by the alpha of the destination pixel. This mode is the inverse of CompositionMode_SourceAtop.
QPainter.CompositionMode_Xor
The source, whose alpha is reduced with the inverse of the destination alpha, is merged with the destination, whose alpha is reduced by the inverse of the source alpha. CompositionMode_Xor is not the same as the bitwise Xor.
QPainter.CompositionMode_Plus
Both the alpha and color of the source and destination pixels are added together.
QPainter.CompositionMode_Multiply
The output is the source color multiplied by the destination. Multiplying a color with white leaves the color unchanged, while multiplying a color with black produces black.
QPainter.CompositionMode_Screen
The source and destination colors are inverted and then multiplied. Screening a color with white produces white, whereas screening a color with black leaves the color unchanged.
QPainter.CompositionMode_Overlay
Multiplies or screens the colors depending on the destination color. The destination color is mixed with the source color to reflect the lightness or darkness of the destination.
QPainter.CompositionMode_Darken
The darker of the source and destination colors is selected.
QPainter.CompositionMode_Lighten
The lighter of the source and destination colors is selected.
QPainter.CompositionMode_ColorDodge
The destination color is brightened to reflect the source color. A black source color leaves the destination color unchanged.
QPainter.CompositionMode_ColorBurn
The destination color is darkened to reflect the source color. A white source color leaves the destination color unchanged.
QPainter.CompositionMode_HardLight
Multiplies or screens the colors depending on the source color. A light source color will lighten the destination color, whereas a dark source color will darken the destination color.
QPainter.CompositionMode_SoftLight
Darkens or lightens the colors depending on the source color. Similar to CompositionMode_HardLight.
QPainter.CompositionMode_Difference
Subtracts the darker of the colors from the lighter. Painting with white inverts the destination color, whereas painting with black leaves the destination color unchanged.
QPainter.CompositionMode_Exclusion
Similar to CompositionMode_Difference, but with a lower contrast. Painting with white inverts the destination color, whereas painting with black leaves the destination color unchanged.
QPainter.RasterOp_SourceOrDestination
Does a bitwise OR operation on the source and destination pixels (src OR dst).
QPainter.RasterOp_SourceAndDestination
Does a bitwise AND operation on the source and destination pixels (src AND dst).
QPainter.RasterOp_SourceXorDestination
Does a bitwise XOR operation on the source and destination pixels (src XOR dst).
QPainter.RasterOp_NotSourceAndNotDestination
Does a bitwise NOR operation on the source and destination pixels ((NOT src) AND (NOT dst)).
QPainter.RasterOp_NotSourceOrNotDestination
Does a bitwise NAND operation on the source and destination pixels ((NOT src) OR (NOT dst)).
QPainter.RasterOp_NotSourceXorDestination
Does a bitwise operation where the source pixels are inverted and then XOR’ed with the destination ((NOT src) XOR dst).
QPainter.RasterOp_NotSource
Does a bitwise operation where the source pixels are inverted (NOT src).
QPainter.RasterOp_NotSourceAndDestination
Does a bitwise operation where the source is inverted and then AND’ed with the destination ((NOT src) AND dst).
QPainter.RasterOp_SourceAndNotDestination
Does a bitwise operation where the source is AND’ed with the inverted destination pixels (src AND (NOT dst)).
QPainter.RasterOp_NotSourceOrDestination
Does a bitwise operation where the source is inverted and then OR’ed with the destination ((NOT src) OR dst).
QPainter.RasterOp_ClearDestination
The pixels in the destination are cleared (set to 0) independent of the source.
QPainter.RasterOp_SetDestination
The pixels in the destination are set (set to 1) independent of the source.
QPainter.RasterOp_NotDestination
Does a bitwise operation where the destination pixels are inverted (NOT dst).
QPainter.RasterOp_SourceOrNotDestination
Does a bitwise operation where the source is OR’ed with the inverted destination pixels (src OR (NOT dst)).
See also
compositionMode()setCompositionMode()Composition ModesImage Composition Example
- __init__()¶
Constructs a painter.
- __init__(device)
- Parameters:
device –
QPaintDevice
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Constructs a painter that begins painting the paint
deviceimmediately.This constructor is convenient for short-lived painters, e.g. in a QWidget::paintEvent() and should be used only once. The constructor calls
begin()for you and theQPainterdestructor automatically callsend().Here’s an example using
begin()andend():def paintEvent(self, arg__0): p = QPainter() p.begin(self) p.drawLine(drawingCode) # drawing code p.end()
The same example using this constructor:
def paintEvent(self, arg__0): p = QPainter(self) p.drawLine(drawingCode) # drawing code
Since the constructor cannot provide feedback when the initialization of the painter failed you should rather use
begin()andend()to paint on external devices, e.g. printers.- __exit__(arg__1, arg__2, arg__3)¶
- Parameters:
arg__1 – object
arg__2 – object
arg__3 – object
Returns the current background brush.
See also
setBackground()SettingsReturns the current background mode.
See also
setBackgroundMode()Settings- begin(device)¶
- Parameters:
device –
QPaintDevice- Return type:
bool
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Begins painting the paint
deviceand returnstrueif successful; otherwise returnsfalse.Notice that all painter settings (
setPen(),setBrush()etc.) are reset to default values when begin() is called.The errors that can occur are serious problems, such as these:
painter.begin(0) # impossible - paint device cannot be 0 image = QPixmap(0, 0) painter.begin(image) # impossible - image.isNull() == true painter.begin(myWidget) painter2.begin(myWidget) # impossible - only one painter at a time
Note that most of the time, you can use one of the constructors instead of begin(), and that
end()is automatically done at destruction.Warning
A paint device can only be painted by one painter at a time.
Warning
Painting on a
QImagewith the formatFormat_Indexed8is not supported.See also
end()QPainter()- beginNativePainting()¶
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Flushes the painting pipeline and prepares for the user issuing commands directly to the underlying graphics context. Must be followed by a call to
endNativePainting().Note that only the states the underlying paint engine changes will be reset to their respective default states. The states we reset may change from release to release. The following states are currently reset in the OpenGL 2 engine:
blending is disabled
the depth, stencil and scissor tests are disabled
the active texture unit is reset to 0
the depth mask, depth function and the clear depth are reset to their default values
the stencil mask, stencil operation and stencil function are reset to their default values
the current color is reset to solid white
If, for example, the OpenGL polygon mode is changed by the user inside a beginNativePaint()/
endNativePainting()block, it will not be reset to the default state byendNativePainting(). Here is an example that shows intermixing of painter commands and raw OpenGL commands:painter = QPainter(self) painter.fillRect(0, 0, 128, 128, Qt.GlobalColor.green) painter.beginNativePainting() glEnable(GL_SCISSOR_TEST) glScissor(0, 0, 64, 64) glClearColor(1, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glDisable(GL_SCISSOR_TEST) painter.endNativePainting()
See also
Returns the bounding rectangle of the
textas it will appear when drawn inside the givenrectanglewith the specifiedflagsusing the currently setfont().- boundingRect(rect, text[, o=QTextOption()])
- Parameters:
rect –
QRectFtext – str
o –
QTextOption
- Return type:
Instead of specifying flags as a bitwise OR of the Qt::AlignmentFlag and Qt::TextFlag, this overloaded function takes an
optionargument. TheQTextOptionclass provides a description of general rich text properties.See also
- boundingRect(rect, flags, text)
Returns the bounding rectangle of the
textas it will appear when drawn inside the givenrectanglewith the specifiedflagsusing the currently setfont(); i.e the function tells you where thedrawText()function will draw when given the same arguments.If the
textdoes not fit within the givenrectangleusing the specifiedflags, the function returns the required rectangle.The
flagsargument is a bitwise OR of the following flags:Qt::AlignLeft
Qt::AlignRight
Qt::AlignHCenter
Qt::AlignTop
Qt::AlignBottom
Qt::AlignVCenter
Qt::AlignCenter
Qt::TextSingleLine
Qt::TextExpandTabs
Qt::TextShowMnemonic
Qt::TextWordWrap
Qt::TextIncludeTrailingSpaces
If several of the horizontal or several of the vertical alignment flags are set, the resulting alignment is undefined.
See also
drawText()TextFlag- boundingRect(x, y, w, h, flags, text)
- Parameters:
x – int
y – int
w – int
h – int
flags – int
text – str
- Return type:
Returns the bounding rectangle of the given
textas it will appear when drawn inside the rectangle beginning at the point (x,y) with widthwand heighth.Returns the painter’s current brush.
See also
setBrush()SettingsReturns the currently set brush origin.
See also
setBrushOrigin()SettingsReturns the bounding rectangle of the current clip if there is a clip; otherwise returns an empty rectangle. Note that the clip region is given in logical coordinates.
The bounding rectangle is not guaranteed to be tight.
See also
- clipPath()¶
- Return type:
Returns the current clip path in logical coordinates.
Warning
QPainterdoes not store the combined clip explicitly as this is handled by the underlyingQPaintEngine, so the path is recreated on demand and transformed to the current logical coordinate system. This is potentially an expensive operation.See also
Returns the currently set clip region. Note that the clip region is given in logical coordinates.
Warning
QPainterdoes not store the combined clip explicitly as this is handled by the underlyingQPaintEngine, so the path is recreated on demand and transformed to the current logical coordinate system. This is potentially an expensive operation.See also
- combinedTransform()¶
- Return type:
Returns the transformation matrix combining the current window/viewport and world transformation.
See also
- compositionMode()¶
- Return type:
Returns the current composition mode.
See also
- device()¶
- Return type:
Returns the paint device on which this painter is currently painting, or
Noneif the painter is not active.See also
- deviceTransform()¶
- Return type:
Returns the matrix that transforms from logical coordinates to device coordinates of the platform dependent paint device.
This function is only needed when using platform painting commands on the platform dependent handle (Qt::HANDLE), and the platform does not do transformations nativly.
The
PaintEngineFeatureenum can be queried to determine whether the platform performs the transformations or not.See also
Draws the arc defined by the given
rectangle,startAngleandspanAngle.- drawArc(rect, a, alen)
- Parameters:
rect –
QRectFa – int
alen – int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the arc defined by the given
rectangle,startAngleandspanAngle.The
startAngleandspanAnglemust be specified in 1/16th of a degree, i.e. a full circle equals 5760 (16 * 360). Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.
rectangle = QRectF(10.0, 20.0, 80.0, 60.0) startAngle = 30 * 16 spanAngle = 120 * 16 painter = QPainter(self) painter.drawArc(rectangle, startAngle, spanAngle)
See also
- drawArc(x, y, w, h, a, alen)
- Parameters:
x – int
y – int
w – int
h – int
a – int
alen – int
Draws the arc defined by the rectangle beginning at (
x,y) with the specifiedwidthandheight, and the givenstartAngleandspanAngle.Draws the chord defined by the given
rectangle,startAngleandspanAngle.- drawChord(rect, a, alen)
- Parameters:
rect –
QRectFa – int
alen – int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the chord defined by the given
rectangle,startAngleandspanAngle. The chord is filled with the currentbrush().The startAngle and spanAngle must be specified in 1/16th of a degree, i.e. a full circle equals 5760 (16 * 360). Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.

rectangle = QRectF(10.0, 20.0, 80.0, 60.0) startAngle = 30 * 16 spanAngle = 120 * 16 painter = QPainter(self) painter.drawChord(rect, startAngle, spanAngle)
See also
- drawChord(x, y, w, h, a, alen)
- Parameters:
x – int
y – int
w – int
h – int
a – int
alen – int
Draws the chord defined by the rectangle beginning at (
x,y) with the specifiedwidthandheight, and the givenstartAngleandspanAngle.- drawConvexPolygon(points)¶
- Parameters:
points – .list of QPoint
- drawConvexPolygon(points)
- Parameters:
points – .list of QPointF
- drawConvexPolygon(polygon)
- Parameters:
polygon –
QPolygon
Draws the convex polygon defined by
polygonusing the current pen and brush.- drawConvexPolygon(polygon)
- Parameters:
polygon –
QPolygonF
Draws the convex polygon defined by
polygonusing the current pen and brush.Draws the ellipse defined by the given
rectangle.- drawEllipse(r)
- Parameters:
r –
QRectF
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the ellipse defined by the given
rectangle.A filled ellipse has a size of
rectangle.size(). A stroked ellipse has a size ofrectangle.size() plus the pen width.
rectangle = QRectF(10.0, 20.0, 80.0, 60.0) painter = QPainter(self) painter.drawEllipse(rectangle)
See also
- drawEllipse(center, rx, ry)
- Parameters:
center –
QPointrx – int
ry – int
Draws the ellipse positioned at
centerwith radiirxandry.- drawEllipse(center, rx, ry)
- Parameters:
center –
QPointFrx – float
ry – float
Draws the ellipse positioned at
centerwith radiirxandry.- drawEllipse(x, y, w, h)
- Parameters:
x – int
y – int
w – int
h – int
Draws the ellipse defined by the rectangle beginning at (
x,y) with the givenwidthandheight.Draws the glyphs represented by
glyphsatposition. Thepositiongives the edge of the baseline for the string of glyphs. The glyphs will be retrieved from the font selected onglyphsand at offsets given by the positions inglyphs.See also
Draws the given
imageat the givenpoint.Draws the given
imageat the givenpoint.Draws the given
imageinto the givenrectangle.Note
The image is scaled to fit the rectangle, if both the image and rectangle size disagree.
Draws the given
imageinto the givenrectangle.Note
The image is scaled to fit the rectangle, if both the image and rectangle size disagree.
- drawImage(p, image, sr[, flags=Qt.AutoColor])
- Parameters:
p –
QPointimage –
QImagesr –
QRectflags – Combination of
ImageConversionFlag
Draws the rectangular portion
sourceof the givenimagewith its origin at the givenpoint.- drawImage(p, image, sr[, flags=Qt.AutoColor])
- Parameters:
p –
QPointFimage –
QImagesr –
QRectFflags – Combination of
ImageConversionFlag
Draws the rectangular portion
sourceof the givenimagewith its origin at the givenpoint.- drawImage(targetRect, image, sourceRect[, flags=Qt.AutoColor])
- Parameters:
targetRect –
QRectimage –
QImagesourceRect –
QRectflags – Combination of
ImageConversionFlag
Draws the rectangular portion
sourceof the givenimageinto thetargetrectangle in the paint device.Note
The image is scaled to fit the rectangle, if both the image and rectangle size disagree.
- drawImage(targetRect, image, sourceRect[, flags=Qt.AutoColor])
- Parameters:
targetRect –
QRectFimage –
QImagesourceRect –
QRectFflags – Combination of
ImageConversionFlag
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the rectangular portion
sourceof the givenimageinto thetargetrectangle in the paint device.Note
The image is scaled to fit the rectangle, if both the image and rectangle size disagree.
Note
See
Drawing High Resolution Versions of Pixmaps and Imageson how this is affected bydevicePixelRatio().If the image needs to be modified to fit in a lower-resolution result (e.g. converting from 32-bit to 8-bit), use the
flagsto specify how you would prefer this to happen.target = QRectF(10.0, 20.0, 80.0, 60.0) source = QRectF(0.0, 0.0, 70.0, 40.0) image = QImage(":/images/myImage.png") painter = QPainter(self) painter.drawImage(target, image, source)
See also
drawPixmap()devicePixelRatio()- drawImage(x, y, image[, sx=0[, sy=0[, sw=-1[, sh=-1[, flags=Qt.AutoColor]]]]])
- Parameters:
x – int
y – int
image –
QImagesx – int
sy – int
sw – int
sh – int
flags – Combination of
ImageConversionFlag
Draws an image at (
x,y) by copying a part ofimageinto the paint device.(
x,y) specifies the top-left point in the paint device that is to be drawn onto. (sx,sy) specifies the top-left point inimagethat is to be drawn. The default is (0, 0).(
sw,sh) specifies the size of the image that is to be drawn. The default, (0, 0) (and negative) means all the way to the bottom-right of the image.Draws a line defined by
line.- drawLine(line)
- Parameters:
line –
QLineF
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws a line defined by
line.
line = QLineF(10.0, 80.0, 90.0, 20.0) painter = QPainter(self) painter.drawLine(line)
See also
Draws a line from
p1top2.Draws a line from
p1top2.- drawLine(x1, y1, x2, y2)
- Parameters:
x1 – int
y1 – int
x2 – int
y2 – int
Draws a line from (
x1,y1) to (x2,y2).- drawLines(lines)¶
- Parameters:
lines – .list of QLine
Draws the set of lines defined by the list
linesusing the current pen and brush.- drawLines(lines)
- Parameters:
lines – .list of QLineF
Draws the set of lines defined by the list
linesusing the current pen and brush.- drawLines(pointPairs)
- Parameters:
pointPairs – .list of QPoint
Draws a line for each pair of points in the vector
pointPairsusing the current pen.- drawLines(pointPairs)
- Parameters:
pointPairs – .list of QPointF
Draws a line for each pair of points in the vector
pointPairsusing the current pen. If there is an odd number of points in the array, the last point will be ignored.- drawLines(lines, lineCount)
- Parameters:
lines –
QLinelineCount – int
Draws the first
lineCountlines in the arraylinesusing the current pen.- drawLines(lines, lineCount)
- Parameters:
lines –
QLineFlineCount – int
Draws the first
lineCountlines in the arraylinesusing the current pen.See also
- drawLines(pointPairs, lineCount)
- Parameters:
pointPairs –
QPointlineCount – int
Draws the first
lineCountlines in the arraypointPairsusing the current pen.- drawLines(pointPairs, lineCount)
- Parameters:
pointPairs –
QPointFlineCount – int
Draws the first
lineCountlines in the arraypointPairsusing the current pen. The lines are specified as pairs of points so the number of entries inpointPairsmust be at leastlineCount* 2.- drawPath(path)¶
- Parameters:
path –
QPainterPath
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the given painter
pathusing the current pen for outline and the current brush for filling.
path = QPainterPath() path.moveTo(20, 80) path.lineTo(20, 30) path.cubicTo(80, 0, 50, 50, 80, 80) painter = QPainter(self) painter.drawPath(path)
See also
the Painter Paths examplethe Vector Deformation exampleReplays the given
pictureat the givenpoint.Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Replays the given
pictureat the givenpoint.The
QPictureclass is a paint device that records and replaysQPaintercommands. A picture serializes the painter commands to an IO device in a platform-independent format. Everything that can be painted on a widget or pixmap can also be stored in a picture.This function does exactly the same as
play()when called withpoint= QPointF(0, 0).Note
The state of the painter is preserved by this function.
picture = QPicture() point = QPointF(10.0, 20.0) picture.load("drawing.pic") painter = QPainter(self) painter.drawPicture(0, 0, picture)
See also
- drawPicture(x, y, picture)
- Parameters:
x – int
y – int
picture –
QPicture
Draws the given
pictureat point (x,y).Draws a pie defined by the given
rectangle,startAngleand andspanAngle.- drawPie(rect, a, alen)
- Parameters:
rect –
QRectFa – int
alen – int
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws a pie defined by the given
rectangle,startAngleandspanAngle.The pie is filled with the current
brush().The startAngle and spanAngle must be specified in 1/16th of a degree, i.e. a full circle equals 5760 (16 * 360). Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o’clock position.

rectangle = QRectF(10.0, 20.0, 80.0, 60.0) startAngle = 30 * 16 spanAngle = 120 * 16 painter = QPainter(self) painter.drawPie(rectangle, startAngle, spanAngle)
See also
- drawPie(x, y, w, h, a, alen)
- Parameters:
x – int
y – int
w – int
h – int
a – int
alen – int
Draws the pie defined by the rectangle beginning at (
x,y) with the specifiedwidthandheight, and the givenstartAngleandspanAngle.Draws the given
pixmapwith its origin at the givenpoint.Draws the given
pixmapwith its origin at the givenpoint.Draws the given
pixmapinto the givenrectangle.Note
The pixmap is scaled to fit the rectangle, if both the pixmap and rectangle size disagree.
Draws the rectangular portion
sourceof the givenpixmapwith its origin at the givenpoint.Draws the rectangular portion
sourceof the givenpixmapwith its origin at the givenpoint.- drawPixmap(targetRect, pixmap, sourceRect)
Draws the rectangular portion
sourceof the givenpixmapinto the giventargetin the paint device.Note
The pixmap is scaled to fit the rectangle, if both the pixmap and rectangle size disagree.
- drawPixmap(targetRect, pixmap, sourceRect)
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the rectangular portion
sourceof the givenpixmapinto the giventargetin the paint device.Note
The pixmap is scaled to fit the rectangle, if both the pixmap and rectangle size disagree.
Note
See
Drawing High Resolution Versions of Pixmaps and Imageson how this is affected bydevicePixelRatio().target = QRectF(10.0, 20.0, 80.0, 60.0) source = QRectF(0.0, 0.0, 70.0, 40.0) pixmap = QPixmap(":myPixmap.png") painter = QPainter(self) painter.drawPixmap(target, pixmap, source)
If
pixmapis aQBitmapit is drawn with the bits that are “set” using the pens color. IfbackgroundModeis Qt::OpaqueMode, the “unset” bits are drawn using the color of the background brush; ifbackgroundModeis Qt::TransparentMode, the “unset” bits are transparent. Drawing bitmaps with gradient or texture colors is not supported.See also
drawImage()devicePixelRatio()- drawPixmap(x, y, pm)
- Parameters:
x – int
y – int
pm –
QPixmap
Draws the given
pixmapat position (x,y).- drawPixmap(x, y, w, h, pm)
- Parameters:
x – int
y – int
w – int
h – int
pm –
QPixmap
Draws the
pixmapinto the rectangle at position (x,y) with the givenwidthandheight.- drawPixmap(x, y, pm, sx, sy, sw, sh)
- Parameters:
x – int
y – int
pm –
QPixmapsx – int
sy – int
sw – int
sh – int
Draws a pixmap at (
x,y) by copying a part of the givenpixmapinto the paint device.(
x,y) specifies the top-left point in the paint device that is to be drawn onto. (sx,sy) specifies the top-left point inpixmapthat is to be drawn. The default is (0, 0).(
sw,sh) specifies the size of the pixmap that is to be drawn. The default, (0, 0) (and negative) means all the way to the bottom-right of the pixmap.- drawPixmap(x, y, w, h, pm, sx, sy, sw, sh)
- Parameters:
x – int
y – int
w – int
h – int
pm –
QPixmapsx – int
sy – int
sw – int
sh – int
Draws the rectangular portion with the origin (
sx,sy), widthswand heightsh, of the givenpixmap, at the point (x,y), with a width ofwand a height ofh. If sw or sh are equal to zero the width/height of the pixmap is used and adjusted by the offset sx/sy;- drawPixmapFragments(fragments, fragmentCount, pixmap[, hints=QPainter.PixmapFragmentHints()])¶
- Parameters:
fragments –
PixmapFragmentfragmentCount – int
pixmap –
QPixmaphints – Combination of
PixmapFragmentHint
This function is used to draw
pixmap, or a sub-rectangle ofpixmap, at multiple positions with different scale, rotation and opacity.fragmentsis an array offragmentCountelements specifying the parameters used to draw each pixmap fragment. Thehintsparameter can be used to pass in drawing hints.This function is potentially faster than multiple calls to
drawPixmap(), since the backend can optimize state changes.See also
PixmapFragmentPixmapFragmentHintDraws a single point at the given
positionusing the current pen’s color.- drawPoint(pt)
- Parameters:
pt –
QPointF
Draws a single point at the given
positionusing the current pen’s color.See also
- drawPoint(x, y)
- Parameters:
x – int
y – int
Draws a single point at position (
x,y).- drawPoints(points)¶
- Parameters:
points – .list of QPoint
- drawPoints(points)
- Parameters:
points – .list of QPointF
- drawPoints(points)
- Parameters:
points –
QPolygon
Draws the points in the vector
points.- drawPoints(points)
- Parameters:
points –
QPolygonF
Draws the points in the vector
points.- drawPoints(points, pointCount)
- Parameters:
points –
QPointFpointCount – int
Draws the first
pointCountpoints in the arraypointsusing the current pen’s color.See also
- drawPointsNp(x, y)¶
- Parameters:
x –
PyArrayObjecty –
PyArrayObject
Draws the points specified by two one-dimensional, equally sized numpy arrays representing the x, y values, respectively.
- drawPolygon(points, fill_rule)
- Parameters:
points – .list of QPointF
fill_rule –
FillRule
Draws the polygon defined by the given
pointsusing the fill rulefillRule.Draws the polygon defined by the given
pointsusing the fill rulefillRule.- drawPolyline(points)¶
- Parameters:
points – .list of QPoint
- drawPolyline(points)
- Parameters:
points – .list of QPointF
- drawPolyline(polygon)
- Parameters:
polygon –
QPolygon
Draws the polyline defined by the given
pointsusing the current pen.- drawPolyline(polyline)
- Parameters:
polyline –
QPolygonF
Draws the polyline defined by the given
pointsusing the current pen.Draws the current
rectanglewith the current pen and brush.- drawRect(rect)
- Parameters:
rect –
QRectF
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the current
rectanglewith the current pen and brush.A filled rectangle has a size of
rectangle.size(). A stroked rectangle has a size ofrectangle.size() plus the pen width.
rectangle = QRectF(10.0, 20.0, 80.0, 60.0) painter = QPainter(self) painter.drawRect(rectangle)
See also
- drawRect(x1, y1, w, h)
- Parameters:
x1 – int
y1 – int
w – int
h – int
Draws a rectangle with upper left corner at (
x,y) and with the givenwidthandheight.- drawRects(rectangles)¶
- Parameters:
rectangles – .list of QRect
Draws the given
rectanglesusing the current pen and brush.- drawRects(rectangles)
- Parameters:
rectangles – .list of QRectF
Draws the given
rectanglesusing the current pen and brush.- drawRects(rects, rectCount)
- Parameters:
rects –
QRectrectCount – int
Draws the first
rectCountof the givenrectanglesusing the current pen and brush.- drawRects(rects, rectCount)
- Parameters:
rects –
QRectFrectCount – int
Draws the first
rectCountof the givenrectanglesusing the current pen and brush.See also
- drawRoundedRect(rect, xRadius, yRadius[, mode=Qt.AbsoluteSize])¶
Draws the given rectangle
rectwith rounded corners.- drawRoundedRect(rect, xRadius, yRadius[, mode=Qt.AbsoluteSize])
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the given rectangle
rectwith rounded corners.The
xRadiusandyRadiusarguments specify the radii of the ellipses defining the corners of the rounded rectangle. Whenmodeis Qt::RelativeSize,xRadiusandyRadiusare specified in percentage of half the rectangle’s width and height respectively, and should be in the range 0.0 to 100.0.A filled rectangle has a size of rect.size(). A stroked rectangle has a size of rect.size() plus the pen width.

rectangle = QRectF(10.0, 20.0, 80.0, 60.0) painter = QPainter(self) painter.drawRoundedRect(rectangle, 20.0, 15.0)
See also
- drawRoundedRect(x, y, w, h, xRadius, yRadius[, mode=Qt.AbsoluteSize])
- Parameters:
x – int
y – int
w – int
h – int
xRadius – float
yRadius – float
mode –
SizeMode
Draws the given rectangle
x,y,w,hwith rounded corners.- drawStaticText(topLeftPosition, staticText)¶
- Parameters:
topLeftPosition –
QPointstaticText –
QStaticText
Draws the
staticTextat thetopLeftPosition.Note
The y-position is used as the top of the font.
- drawStaticText(topLeftPosition, staticText)
- Parameters:
topLeftPosition –
QPointFstaticText –
QStaticText
Draws the given
staticTextat the giventopLeftPosition.The text will be drawn using the font and the transformation set on the painter. If the font and/or transformation set on the painter are different from the ones used to initialize the layout of the
QStaticText, then the layout will have to be recalculated. Useprepare()to initializestaticTextwith the font and transformation with which it will later be drawn.If
topLeftPositionis not the same as whenstaticTextwas initialized, or when it was last drawn, then there will be a slight overhead when translating the text to its new position.Note
If the painter’s transformation is not affine, then
staticTextwill be drawn using regular calls todrawText(), losing any potential for performance improvement.- drawStaticText(left, top, staticText)
- Parameters:
left – int
top – int
staticText –
QStaticText
Draws the
staticTextat coordinatesleftandtop.Note
The y-position is used as the top of the font.
Draws the given
textwith the currently defined text direction, beginning at the givenposition.By default,
QPainterdraws text anti-aliased.- drawText(p, s)
- Parameters:
p –
QPointFs – str
Draws the given
textwith the currently defined text direction, beginning at the givenposition.This function does not handle the newline character (\n), as it cannot break text into multiple lines, and it cannot display the newline character. Use the QPainter::drawText() overload that takes a rectangle instead if you want to draw multiple lines of text with the newline character, or if you want the text to be wrapped.
By default,
QPainterdraws text anti-aliased.- drawText(r, text[, o=QTextOption()])
- Parameters:
r –
QRectFtext – str
o –
QTextOption
Draws the given
textin therectanglespecified using theoptionto control its positioning, direction, and orientation. The options given inoptionoverride those set on theQPainterobject itself.By default,
QPainterdraws text anti-aliased.- drawText(x, y, s)
- Parameters:
x – int
y – int
s – str
Draws the given
textat position (x,y), using the painter’s currently defined text direction.By default,
QPainterdraws text anti-aliased.The function returns the bounding rectangle enclosing the whole text.
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the given
textwithin the providedrectangleaccording to the specifiedflags.The
boundingRect(if not null) is set to the what the bounding rectangle should be in order to enclose the whole text. For example, in the following image, the dotted line representsboundingRectas calculated by the function, and the dashed line representsrectangle:
painter = QPainter(self) font = painter.font() font.setPixelSize(48) painter.setFont(font) rectangle = QRect(0, 0, 100, 50) boundingRect = painter.drawText(rectangle, 0, "Hello") pen = painter.pen() pen.setStyle(Qt.DotLine) painter.setPen(pen) painter.drawRect(boundingRect.adjusted(0, 0, -pen.width(), -pen.width())) pen.setStyle(Qt.DashLine) painter.setPen(pen) painter.drawRect(rectangle.adjusted(0, 0, -pen.width(), -pen.width()))
By default,
QPainterdraws text anti-aliased.The function returns the bounding rectangle enclosing the whole text.
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the given
textwithin the providedrectangle. Therectanglealong with alignmentflagsdefines the anchors for thetext.
painter = QPainter(self) painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, tr("Qt\nProject"))
The
boundingRect(if not null) is set to what the bounding rectangle should be in order to enclose the whole text. For example, in the following image, the dotted line representsboundingRectas calculated by the function, and the dashed line representsrectangle:
painter = QPainter(self) font = painter.font() font.setPixelSize(48) painter.setFont(font) rectangle = QRect(0, 0, 100, 50) boundingRect = painter.drawText(rectangle, 0, "Hello") pen = painter.pen() pen.setStyle(Qt.DotLine) painter.setPen(pen) painter.drawRect(boundingRect.adjusted(0, 0, -pen.width(), -pen.width())) pen.setStyle(Qt.DashLine) painter.setPen(pen) painter.drawRect(rectangle.adjusted(0, 0, -pen.width(), -pen.width()))
The
flagsargument is a bitwise OR of the following flags:Qt::AlignLeft
Qt::AlignRight
Qt::AlignHCenter
Qt::AlignJustify
Qt::AlignTop
Qt::AlignBottom
Qt::AlignVCenter
Qt::AlignCenter
Qt::TextDontClip
Qt::TextSingleLine
Qt::TextExpandTabs
Qt::TextShowMnemonic
Qt::TextWordWrap
Qt::TextIncludeTrailingSpaces
By default,
QPainterdraws text anti-aliased.Note
The y-coordinate of
rectangleis used as the top of the font.See also
- drawText(x, y, w, h, flags, text)
- Parameters:
x – int
y – int
w – int
h – int
flags – int
text – str
The function returns the bounding rectangle enclosing the whole text.
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Draws the given
textwithin the rectangle with origin (x,y),widthandheight.The
boundingRect(if not null) is set to the what the bounding rectangle should be in order to enclose the whole text. For example, in the following image, the dotted line representsboundingRectas calculated by the function, and the dashed line represents the rectangle defined byx,y,widthandheight:
painter = QPainter(self) font = painter.font() font.setPixelSize(48) painter.setFont(font) rectangle = QRect(0, 0, 100, 50) boundingRect = painter.drawText(rectangle, 0, "Hello") pen = painter.pen() pen.setStyle(Qt.DotLine) painter.setPen(pen) painter.drawRect(boundingRect.adjusted(0, 0, -pen.width(), -pen.width())) pen.setStyle(Qt.DashLine) painter.setPen(pen) painter.drawRect(rectangle.adjusted(0, 0, -pen.width(), -pen.width()))
The
flagsargument is a bitwise OR of the following flags:Qt::AlignLeft
Qt::AlignRight
Qt::AlignHCenter
Qt::AlignJustify
Qt::AlignTop
Qt::AlignBottom
Qt::AlignVCenter
Qt::AlignCenter
Qt::TextSingleLine
Qt::TextExpandTabs
Qt::TextShowMnemonic
Qt::TextWordWrap
By default,
QPainterdraws text anti-aliased.- drawTextItem(x, y, ti)
- Parameters:
x – int
y – int
ti –
QTextItem
- drawTiledPixmap(rectangle, pixmap[, position=QPoint()])¶
Draws a tiled
pixmap, inside the givenrectanglewith its origin at the givenposition.- drawTiledPixmap(rect, pm[, offset=QPointF()])
Draws a tiled
pixmap, inside the givenrectanglewith its origin at the givenposition.Calling drawTiledPixmap() is similar to calling
drawPixmap()several times to fill (tile) an area with a pixmap, but is potentially much more efficient depending on the underlying window system.drawTiledPixmap() will produce the same visual tiling pattern on high-dpi displays (with devicePixelRatio > 1), compared to normal- dpi displays. Set the devicePixelRatio on the
pixmapto control the tile size. For example, setting it to 2 halves the tile width and height (on both 1x and 2x displays), and produces high-resolution output on 2x displays.The
positionoffset is always in the painter coordinate system, indepentent of display devicePixelRatio.See also
- drawTiledPixmap(x, y, w, h, pixmap[, sx=0[, sy=0]])
- Parameters:
x – int
y – int
w – int
h – int
pixmap –
QPixmapsx – int
sy – int
Draws a tiled
pixmapin the specified rectangle.(
x,y) specifies the top-left point in the paint device that is to be drawn onto; with the givenwidthandheight. (sx,sy) specifies the top-left point in thepixmapthat is to be drawn; this defaults to (0, 0).- end()¶
- Return type:
bool
Ends painting. Any resources used while painting are released. You don’t normally need to call this since it is called by the destructor.
Returns
trueif the painter is no longer active; otherwise returnsfalse.See also
- endNativePainting()¶
Restores the painter after manually issuing native painting commands. Lets the painter restore any native state that it relies on before calling any other painter commands.
See also
Erases the area inside the given
rectangle.- eraseRect(rectangle)
- Parameters:
rectangle –
QRectF
Warning
This section contains snippets that were automatically translated from C++ to Python and may contain errors.
Erases the area inside the given
rectangle. Equivalent to callingfillRect(rectangle, background())
See also
- eraseRect(x, y, w, h)
- Parameters:
x – int
y – int
w – int
h – int
Erases the area inside the rectangle beginning at (
x,y) with the givenwidthandheight.- fillPath(path, brush)¶
- Parameters:
path –
QPainterPathbrush –
QBrush
Fills the given
pathusing the givenbrush. The outline is not drawn.Alternatively, you can specify a
QColorinstead of aQBrush; theQBrushconstructor (taking aQColorargument) will automatically create a solid pattern brush.See also
Fills the given
rectanglewith the specifiedbrush.Fills the given
rectanglewith thecolorspecified.Fills the given
rectanglewith the specified gradientpreset.- fillRect(r, style)
- Parameters:
r –
QRectstyle –
BrushStyle
Fills the given
rectanglewith the brushstylespecified.- fillRect(r, c)
- Parameters:
r –
QRectc –
GlobalColor
Fills the given
rectanglewith the specifiedcolor.Fills the given
rectanglewith thebrushspecified.Alternatively, you can specify a
QColorinstead of aQBrush; theQBrushconstructor (taking aQColorargument) will automatically create a solid pattern brush.See also
Fills the given
rectanglewith thecolorspecified.Fills the given
rectanglewith the specified gradientpreset.- fillRect(r, style)
- Parameters:
r –
QRectFstyle –
BrushStyle
Fills the given
rectanglewith the brushstylespecified.- fillRect(r, c)
- Parameters:
r –
QRectFc –
GlobalColor
Fills the given
rectanglewith the specifiedcolor.- fillRect(x, y, w, h, preset)
- Parameters:
x – int
y – int
w – int
h – int
preset –
Preset
Fills the rectangle beginning at (
x,y) with the givenwidthandheight, using the given gradientpreset.- fillRect(x, y, w, h, style)
- Parameters:
x – int
y – int
w – int
h – int
style –
BrushStyle
Fills the rectangle beginning at (
x,y) with the givenwidthandheight, using the brushstylespecified.- fillRect(x, y, w, h, c)
- Parameters:
x – int
y – int
w – int
h – int
c –
GlobalColor
Fills the rectangle beginning at (
x,y) with the givenwidthandheight, using the givencolor.- fillRect(x, y, w, h, brush)
- Parameters:
x – int
y – int
w – int
h – int
brush –
QBrush
Fills the rectangle beginning at (
x,y) with the givenwidthandheight, using the givenbrush.- fillRect(x, y, w, h, color)
- Parameters:
x – int
y – int
w – int
h – int
color –
QColor
Fills the rectangle beginning at (
x,y) with the givenwidthandheight, using the givencolor.Returns the currently set font used for drawing text.
See also
setFont()drawText()SettingsReturns the font info for the painter if the painter is active. Otherwise, the return value is undefined.
See also
font()isActive()Settings- fontMetrics()¶
- Return type:
Returns the font metrics for the painter if the painter is active. Otherwise, the return value is undefined.
See also
font()isActive()Settings- hasClipping()¶
- Return type:
bool
Returns
trueif clipping has been set; otherwise returnsfalse.See also
setClipping()Clipping- isActive()¶
- Return type:
bool
Returns
trueifbegin()has been called andend()has not yet been called; otherwise returnsfalse.See also
- layoutDirection()¶
- Return type:
Returns the layout direction used by the painter when drawing text.
See also
- opacity()¶
- Return type:
float
Returns the opacity of the painter. The default value is 1.
See also
- paintEngine()¶
- Return type:
Returns the paint engine that the painter is currently operating on if the painter is active; otherwise 0.
See also
Returns the painter’s current pen.
See also
setPen()Settings- renderHints()¶
- Return type:
Combination of
RenderHint
Returns a flag that specifies the rendering hints that are set for this painter.
See also
setRenderHints()testRenderHint()Rendering Quality- resetTransform()¶
Resets any transformations that were made using
translate(),scale(),shear(),rotate(),setWorldTransform(),setViewport()andsetWindow().See also
Coordinate Transformations- restore()¶
Restores the current painter state (pops a saved state off the stack).
See also
- rotate(a)¶
- Parameters:
a – float
Rotates the coordinate system clockwise. The given
angleparameter is in degrees.See also
setWorldTransform()Coordinate Transformations- save()¶
Saves the current painter state (pushes the state onto a stack). A save() must be followed by a corresponding
restore(); theend()function unwinds the stack.See also
- scale(sx, sy)¶
- Parameters:
sx – float
sy – float
Scales the coordinate system by (
sx,sy).See also
setWorldTransform()Coordinate TransformationsSets the background brush of the painter to the given
brush.The background brush is the brush that is filled in when drawing opaque text, stippled lines and bitmaps. The background brush has no effect in transparent background mode (which is the default).
See also
background()setBackgroundMode()SettingsSets the background mode of the painter to the given
modeQt::TransparentMode (the default) draws stippled lines and text without setting the background pixels. Qt::OpaqueMode fills these space with the current background color.
Note that in order to draw a bitmap or pixmap transparently, you must use
setMask().See also
backgroundMode()setBackground()SettingsSets the painter’s brush to a solid brush with the specified
color.- setBrush(style)
- Parameters:
style –
BrushStyle
Sets the painter’s brush to black color and the specified
style.- setBrush(color)
- Parameters:
color –
GlobalColor
Sets the painter’s brush to a solid brush with the specified
color.- setBrush(brush)
- Parameters:
brush –
QBrush
Sets the painter’s brush to the given
brush.The painter’s brush defines how shapes are filled.
See also
brush()SettingsSets the brush’s origin to the given
position.- setBrushOrigin(position)
- Parameters:
position –
QPointF
Sets the brush origin to
position.The brush origin specifies the (0, 0) coordinate of the painter’s brush.
Note that while the
brushOrigin()was necessary to adopt the parent’s background for a widget in Qt 3, this is no longer the case since the Qt 4 painter doesn’t paint the background unless you explicitly tell it to do so by setting the widget’s autoFillBackground property to true.See also
brushOrigin()Settings- setBrushOrigin(x, y)
- Parameters:
x – int
y – int
Sets the brush’s origin to point (
x,y).- setClipPath(path[, op=Qt.ReplaceClip])¶
- Parameters:
path –
QPainterPathop –
ClipOperation
Enables clipping, and sets the clip path for the painter to the given
path, with the clipoperation.Note that the clip path is specified in logical (painter) coordinates.
See also
clipPath()clipRegion()Clipping- setClipRect(rectangle[, op=Qt.ReplaceClip])¶
- Parameters:
rectangle –
QRectop –
ClipOperation
Enables clipping, and sets the clip region to the given
rectangleusing the given clipoperation.- setClipRect(rectangle[, op=Qt.ReplaceClip])
- Parameters:
rectangle –
QRectFop –
ClipOperation
Enables clipping, and sets the clip region to the given
rectangleusing the given clipoperation. The default operation is to replace the current clip rectangle.Note that the clip rectangle is specified in logical (painter) coordinates.
See also
clipRegion()setClipping()Clipping- setClipRect(x, y, w, h[, op=Qt.ReplaceClip])
- Parameters:
x – int
y – int
w – int
h – int
op –
ClipOperation
Enables clipping, and sets the clip region to the rectangle beginning at (
x,y) with the givenwidthandheight.- setClipRegion(region[, op=Qt.ReplaceClip])¶
- Parameters:
region –
QRegionop –
ClipOperation
Sets the clip region to the given
regionusing the specified clipoperation. The default clip operation is to replace the current clip region.Note that the clip region is given in logical coordinates.
See also
clipRegion()setClipRect()Clipping- setClipping(enable)¶
- Parameters:
enable – bool
Enables clipping if
enableis true, or disables clipping ifenableis false.See also
hasClipping()Clipping- setCompositionMode(mode)¶
- Parameters:
mode –
CompositionMode
Sets the composition mode to the given
mode.Warning
Only a
QPainteroperating on aQImagefully supports all composition modes. The RasterOp modes are supported for X11 as described incompositionMode().See also
Sets the painter’s font to the given
font.This font is used by subsequent
drawText()functions. The text color is the same as the pen color.If you set a font that isn’t available, Qt finds a close match.
font()will return what you set using setFont() andfontInfo()returns the font actually being used (which may be the same).See also
font()drawText()Settings- setLayoutDirection(direction)¶
- Parameters:
direction –
LayoutDirection
Sets the layout direction used by the painter when drawing text, to the specified
direction.The default is Qt::LayoutDirectionAuto, which will implicitly determine the direction from the text drawn.
See also
- setOpacity(opacity)¶
- Parameters:
opacity – float
Sets the opacity of the painter to
opacity. The value should be in the range 0.0 to 1.0, where 0.0 is fully transparent and 1.0 is fully opaque.The opacity set on the painter applies to each drawing operation separately. Filling a shape and drawing its outline are treated as separate drawing operations.
See also
Sets the painter’s pen to have the given
style, width 1 and black color.- setPen(color)
- Parameters:
color –
QColor
Sets the painter’s pen to have style Qt::SolidLine, width 1 and the specified
color.- setPen(pen)
- Parameters:
pen –
QPen
Sets the painter’s pen to be the given
pen.The
pendefines how to draw lines and outlines, and it also defines the text color.See also
pen()Settings- setRenderHint(hint[, on=true])¶
- Parameters:
hint –
RenderHinton – bool
Sets the given render
hinton the painter ifonis true; otherwise clears the render hint.See also
setRenderHints()renderHints()Rendering Quality- setRenderHints(hints[, on=true])¶
- Parameters:
hints – Combination of
RenderHinton – bool
Sets the given render
hintson the painter ifonis true; otherwise clears the render hints.See also
setRenderHint()renderHints()Rendering Quality- setTransform(transform[, combine=false])¶
- Parameters:
transform –
QTransformcombine – bool
Sets the world transformation matrix. If
combineis true, the specifiedtransformis combined with the current matrix; otherwise it replaces the current matrix.See also
- setViewTransformEnabled(enable)¶
- Parameters:
enable – bool
Enables view transformations if
enableis true, or disables view transformations ifenableis false.Sets the painter’s viewport rectangle to the given
rectangle, and enables view transformations.The viewport rectangle is part of the view transformation. The viewport specifies the device coordinate system. Its sister, the
window(), specifies the logical coordinate system.The default viewport rectangle is the same as the device’s rectangle.
- setViewport(x, y, w, h)
- Parameters:
x – int
y – int
w – int
h – int
Sets the painter’s viewport rectangle to be the rectangle beginning at (
x,y) with the givenwidthandheight.Sets the painter’s window to the given
rectangle, and enables view transformations.The window rectangle is part of the view transformation. The window specifies the logical coordinate system. Its sister, the
viewport(), specifies the device coordinate system.The default window rectangle is the same as the device’s rectangle.
- setWindow(x, y, w, h)
- Parameters:
x – int
y – int
w – int
h – int
Sets the painter’s window to the rectangle beginning at (
x,y) and the givenwidthandheight.- setWorldMatrixEnabled(enabled)¶
- Parameters:
enabled – bool
Enables transformations if
enableis true, or disables transformations ifenableis false. The world transformation matrix is not changed.See also
worldMatrixEnabled()worldTransform()Coordinate Transformations- setWorldTransform(matrix[, combine=false])¶
- Parameters:
matrix –
QTransformcombine – bool
Sets the world transformation matrix. If
combineis true, the specifiedmatrixis combined with the current matrix; otherwise it replaces the current matrix.See also
- shear(sh, sv)¶
- Parameters:
sh – float
sv – float
Shears the coordinate system by (
sh,sv).See also
setWorldTransform()Coordinate Transformations- strokePath(path, pen)¶
- Parameters:
path –
QPainterPathpen –
QPen
Draws the outline (strokes) the path
pathwith the pen specified bypenSee also
fillPath()Drawing- testRenderHint(hint)¶
- Parameters:
hint –
RenderHint- Return type:
bool
Returns
trueifhintis set; otherwise returnsfalse.See also
- transform()¶
- Return type:
Alias for
worldTransform(). Returns the world transformation matrix.See also
Translates the coordinate system by the given
offset.- translate(offset)
- Parameters:
offset –
QPointF
Translates the coordinate system by the given
offset; i.e. the givenoffsetis added to points.See also
setWorldTransform()Coordinate Transformations- translate(dx, dy)
- Parameters:
dx – float
dy – float
Translates the coordinate system by the vector (
dx,dy).- viewTransformEnabled()¶
- Return type:
bool
Returns
trueif view transformation is enabled; otherwise returns false.Returns the viewport rectangle.
See also
Returns the window rectangle.
See also
- worldMatrixEnabled()¶
- Return type:
bool
Returns
trueif world transformation is enabled; otherwise returns false.- worldTransform()¶
- Return type:
Returns the world transformation matrix.
See also
- class PixmapFragment¶
This class is used in conjunction with the
drawPixmapFragments()function to specify how a pixmap, or sub-rect of a pixmap, is drawn.Details
The
sourceLeft,sourceTop,widthandheightvariables are used as a source rectangle within the pixmap passed into thedrawPixmapFragments()function. The variablesx,y,widthandheightare used to calculate the target rectangle that is drawn.xandydenotes the center of the target rectangle. Thewidthandheightin the target rectangle is scaled by thescaleXandscaleYvalues. The resulting target rectangle is then rotatedrotationdegrees around thex,ycenter point.See also
Synopsis¶
Static functions¶
def
create()
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
- PySide6.QtGui.QPainter.PixmapFragment.x¶
- PySide6.QtGui.QPainter.PixmapFragment.y¶
- PySide6.QtGui.QPainter.PixmapFragment.sourceLeft¶
- PySide6.QtGui.QPainter.PixmapFragment.sourceTop¶
- PySide6.QtGui.QPainter.PixmapFragment.width¶
- PySide6.QtGui.QPainter.PixmapFragment.height¶
- PySide6.QtGui.QPainter.PixmapFragment.scaleX¶
- PySide6.QtGui.QPainter.PixmapFragment.scaleY¶
- PySide6.QtGui.QPainter.PixmapFragment.rotation¶
- PySide6.QtGui.QPainter.PixmapFragment.opacity¶
- static create(pos, sourceRect[, scaleX=1[, scaleY=1[, rotation=0[, opacity=1]]]])¶
- Parameters:
- Return type:
This is a convenience function that returns a
PixmapFragmentthat is initialized with thepos,sourceRect,scaleX,scaleY,rotation,opacityparameters.



