ZetCode

PyQt6 绘图

最后修改于 2023 年 1 月 10 日

PyQt6 绘图系统能够渲染矢量图形、图像和基于轮廓字体的文本。当我们需要更改或增强现有部件,或者从头开始创建自定义部件时,应用程序中就需要绘图。为了进行绘图,我们使用 PyQt6 工具包提供的绘图 API。

QPainter

QPainter 在部件和其他绘图设备上执行低级绘图。它可以绘制从简单的线条到复杂的形状的所有内容。

paintEvent 方法

绘图在 paintEvent 方法中完成。绘图代码位于 QPainter 对象的 beginend 方法之间。它在部件和其他绘图设备上执行低级绘图。

PyQt6 绘制文本

我们首先在窗口的客户端区域上绘制一些 Unicode 文本。

draw_text.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

In this example, we draw text in Russian Cylliric.

Author: Jan Bodnar
Website: zetcode.com
"""

import sys
from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter, QColor, QFont
from PyQt6.QtCore import Qt


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.text = "Лев Николаевич Толстой\nАнна Каренина"

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Drawing text')
        self.show()


    def paintEvent(self, event):

        qp = QPainter()
        qp.begin(self)
        self.drawText(event, qp)
        qp.end()


    def drawText(self, event, qp):

        qp.setPen(QColor(168, 34, 3))
        qp.setFont(QFont('Decorative', 10))
        qp.drawText(event.rect(), Qt.Alignment.AlignCenter, self.text)


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

在我们的示例中,我们在西里尔字母中绘制了一些文本。文本是垂直和水平对齐的。

def paintEvent(self, event):
...

绘图在 paint event 中完成。

qp = QPainter()
qp.begin(self)
self.drawText(event, qp)
qp.end()

QPainter 类负责所有低级绘图。所有绘图方法都位于 beginend 方法之间。实际的绘图委托给 drawText 方法。

qp.setPen(QColor(168, 34, 3))
qp.setFont(QFont('Decorative', 10))

在这里,我们定义一个画笔和字体,用于绘制文本。

qp.drawText(event.rect(), Qt.Alignment.AlignCenter, self.text)

drawText 方法在窗口上绘制文本。 paint event 的 rect 方法返回需要更新的矩形。使用 Qt.Alignment.AlignCenter,我们在两个维度上对齐文本。

Drawing text
图:绘制文本

PyQt6 绘制点

一个点是可以绘制的最简单的图形对象。它在窗口上是一个小点。

draw_points.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

In the example, we draw randomly 1000 red points
on the window.

Author: Jan Bodnar
Website: zetcode.com
"""

from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter
from PyQt6.QtCore import Qt
import sys, random


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.setMinimumSize(50, 50)
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Points')
        self.show()


    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawPoints(qp)
        qp.end()


    def drawPoints(self, qp):

        qp.setPen(Qt.GlobalColor.red)
        size = self.size()

        for i in range(1000):

            x = random.randint(1, size.width() - 1)
            y = random.randint(1, size.height() - 1)
            qp.drawPoint(x, y)


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

在我们的示例中,我们在窗口的客户端区域上随机绘制 1000 个红点。

qp.setPen(Qt.GlobalColor.red)

我们将画笔设置为红色。我们使用预定义的 Qt.GlobalColor.red 颜色常量。

size = self.size()

每次我们调整窗口大小时,都会生成一个 paint event。我们使用 size 方法获取窗口的当前大小。我们使用窗口的大小将点分布在窗口的整个客户端区域上。

qp.drawPoint(x, y)

我们使用 drawPoint 方法绘制点。

Points
图:点

PyQt6 颜色

颜色是一个对象,表示红色、绿色和蓝色 (RGB) 强度值的组合。有效的 RGB 值在 0 到 255 范围内。我们可以通过各种方式定义颜色。最常见的是 RGB 十进制值或十六进制值。我们也可以使用 RGBA 值,它代表红色、绿色、蓝色和 Alpha。在这里,我们添加了一些关于透明度的额外信息。 Alpha 值为 255 定义完全不透明,0 定义完全透明,例如颜色不可见。

colours.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

This example draws three rectangles in three
different colours.

Author: Jan Bodnar
Website: zetcode.com
"""

from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter, QColor
import sys


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.setGeometry(300, 300, 350, 100)
        self.setWindowTitle('Colours')
        self.show()


    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawRectangles(qp)
        qp.end()


    def drawRectangles(self, qp):

        col = QColor(0, 0, 0)
        col.setNamedColor('#d4d4d4')
        qp.setPen(col)

        qp.setBrush(QColor(200, 0, 0))
        qp.drawRect(10, 15, 90, 60)

        qp.setBrush(QColor(255, 80, 0, 160))
        qp.drawRect(130, 15, 90, 60)

        qp.setBrush(QColor(25, 0, 90, 200))
        qp.drawRect(250, 15, 90, 60)


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

在我们的示例中,我们绘制了三个彩色矩形。

color = QColor(0, 0, 0)
color.setNamedColor('#d4d4d4')

在这里,我们使用十六进制表示法定义颜色。

qp.setBrush(QColor(200, 0, 0))
qp.drawRect(10, 15, 90, 60)

在这里,我们定义一个画刷并绘制一个矩形。一个*画刷*是一个基本的图形对象,用于绘制形状的背景。 drawRect 方法接受四个参数。前两个是轴上的 x 和 y 值。第三个和第四个参数是矩形的宽度和高度。该方法使用当前画笔和画刷绘制矩形。

Colours
图:颜色

PyQt6 QPen

QPen 是一个基本的图形对象。它用于绘制线条、曲线和矩形、椭圆、多边形或其他形状的轮廓。

pens.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

In this example we draw 6 lines using
different pen styles.

Author: Jan Bodnar
Website: zetcode.com
"""

from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter, QPen
from PyQt6.QtCore import Qt
import sys


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.setGeometry(300, 300, 280, 270)
        self.setWindowTitle('Pen styles')
        self.show()


    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()


    def drawLines(self, qp):

        pen = QPen(Qt.GlobalColor.black, 2, Qt.PenStyle.SolidLine)

        qp.setPen(pen)
        qp.drawLine(20, 40, 250, 40)

        pen.setStyle(Qt.PenStyle.DashLine)
        qp.setPen(pen)
        qp.drawLine(20, 80, 250, 80)

        pen.setStyle(Qt.PenStyle.DashDotLine)
        qp.setPen(pen)
        qp.drawLine(20, 120, 250, 120)

        pen.setStyle(Qt.PenStyle.DotLine)
        qp.setPen(pen)
        qp.drawLine(20, 160, 250, 160)

        pen.setStyle(Qt.PenStyle.DashDotDotLine)
        qp.setPen(pen)
        qp.drawLine(20, 200, 250, 200)

        pen.setStyle(Qt.PenStyle.CustomDashLine)
        pen.setDashPattern([1, 4, 5, 4])
        qp.setPen(pen)
        qp.drawLine(20, 240, 250, 240)


def main():
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

在我们的示例中,我们绘制了六条线。线条以六种不同的画笔样式绘制。有五种预定义的画笔样式。我们还可以创建自定义画笔样式。最后一条线是使用自定义画笔样式绘制的。

pen = QPen(Qt.GlobalColor.black, 2, Qt.PenStyle.SolidLine)

我们创建一个 QPen 对象。颜色是黑色。宽度设置为 2 像素,以便我们可以看到画笔样式之间的差异。 Qt.SolidLine 是预定义的画笔样式之一。

pen.setStyle(Qt.PenStyle.CustomDashLine)
pen.setDashPattern([1, 4, 5, 4])
qp.setPen(pen)

在这里,我们定义一个自定义画笔样式。我们设置 Qt.PenStyle.CustomDashLine 画笔样式并调用 setDashPattern 方法。数字列表定义了一个样式。必须有偶数个数字。奇数定义一个短划线,偶数定义一个空格。数字越大,空格或短划线越大。我们的模式是 1 像素短划线,4 像素空格,5 像素短划线,4 像素空格等。

Pen styles
图:画笔样式

PyQt6 QBrush

QBrush 是一个基本的图形对象。它用于绘制图形形状的背景,例如矩形、椭圆或多边形。画刷可以是三种不同的类型:预定义的画刷、渐变或纹理图案。

brushes.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

This example draws nine rectangles in different
brush styles.

Author: Jan Bodnar
Website: zetcode.com
"""

from PyQt6.QtWidgets import QWidget, QApplication
from PyQt6.QtGui import QPainter, QBrush
from PyQt6.QtCore import Qt
import sys


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.setGeometry(300, 300, 355, 280)
        self.setWindowTitle('Brushes')
        self.show()


    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        self.drawBrushes(qp)
        qp.end()


    def drawBrushes(self, qp):

        brush = QBrush(Qt.BrushStyle.SolidPattern)
        qp.setBrush(brush)
        qp.drawRect(10, 15, 90, 60)

        brush.setStyle(Qt.BrushStyle.Dense1Pattern)
        qp.setBrush(brush)
        qp.drawRect(130, 15, 90, 60)

        brush.setStyle(Qt.BrushStyle.Dense2Pattern)
        qp.setBrush(brush)
        qp.drawRect(250, 15, 90, 60)

        brush.setStyle(Qt.BrushStyle.DiagCrossPattern)
        qp.setBrush(brush)
        qp.drawRect(10, 105, 90, 60)

        brush.setStyle(Qt.BrushStyle.Dense5Pattern)
        qp.setBrush(brush)
        qp.drawRect(130, 105, 90, 60)

        brush.setStyle(Qt.BrushStyle.Dense6Pattern)
        qp.setBrush(brush)
        qp.drawRect(250, 105, 90, 60)

        brush.setStyle(Qt.BrushStyle.HorPattern)
        qp.setBrush(brush)
        qp.drawRect(10, 195, 90, 60)

        brush.setStyle(Qt.BrushStyle.VerPattern)
        qp.setBrush(brush)
        qp.drawRect(130, 195, 90, 60)

        brush.setStyle(Qt.BrushStyle.BDiagPattern)
        qp.setBrush(brush)
        qp.drawRect(250, 195, 90, 60)


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

在我们的示例中,我们绘制了九个不同的矩形。

brush = QBrush(Qt.BrushStyle.SolidPattern)
qp.setBrush(brush)
qp.drawRect(10, 15, 90, 60)

我们定义一个画刷对象。我们将其设置为 painter 对象,并通过调用 drawRect 方法绘制矩形。

Brushes
图:画刷

贝塞尔曲线

贝塞尔曲线是一条三次线。 PyQt6 中的贝塞尔曲线可以使用 QPainterPath 创建。一个 painter path 是由许多图形构建块组成的,例如矩形、椭圆、线条和曲线。

bezier_curve.py
#!/usr/bin/python

"""
ZetCode PyQt6 tutorial

This program draws a Bézier curve with
QPainterPath.

Author: Jan Bodnar
Website: zetcode.com
"""

import sys

from PyQt6.QtGui import QPainter, QPainterPath
from PyQt6.QtWidgets import QWidget, QApplication


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.setGeometry(300, 300, 380, 250)
        self.setWindowTitle('Bézier curve')
        self.show()


    def paintEvent(self, e):

        qp = QPainter()
        qp.begin(self)
        qp.setRenderHint(QPainter.RenderHints.Antialiasing)
        self.drawBezierCurve(qp)
        qp.end()


    def drawBezierCurve(self, qp):
    
        path = QPainterPath()
        path.moveTo(30, 30)
        path.cubicTo(30, 30, 200, 350, 350, 30)

        qp.drawPath(path)


def main():

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec())


if __name__ == '__main__':
    main()

此示例绘制一个贝塞尔曲线。

path = QPainterPath()
path.moveTo(30, 30)
path.cubicTo(30, 30, 200, 350, 350, 30)

我们使用 QPainterPath path 创建一个贝塞尔曲线。曲线使用 cubicTo 方法创建,该方法接受三个点:起始点、控制点和结束点。

qp.drawPath(path)

最终路径使用 drawPath 方法绘制。

Bézier curve
图:贝塞尔曲线

在 PyQt6 教程的这一部分中,我们进行了一些基本的绘图。