这是PyQt6教程。本教程适合初学者和中级程序员。阅读本教程后,您将能够编写非平凡的PyQt6应用程序。

代码示例可在本站下载:教程源代码

目录

  • 引言
  • 日期和时间
  • 第一个工程
  • 菜单与工具栏
  • 布局管理
  • 事件和信号
  • 对话框
  • 控件
  • 拖放
  • 绘画

绘画

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

QPainter

QPainter在控件和其他绘画设备上执行低级绘画。它可以画从简单的线条到复杂的形状。

paintEvent 方法

绘画是在paintEvent方法中完成的。绘制代码放置在QPainter对象的开始和结束方法之间。它在小部件和其他绘画设备上执行低级绘画。

PyQt6 绘制文本

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

#!/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()

在我们的例子中,我们用Cylliric绘制了一些文本。文本垂直和水平对齐。

def paintEvent(self, event):
...

绘画是在绘画活动中完成的。

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

QPainter类负责所有低级绘画。所有的绘画方法都介于开始和结束方法之间。实际的绘画被委托给drawText方法。

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

在这里,我们定义了用于绘制文本的笔和字体。

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

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

PyQt6 绘制点


点是可以绘制的最简单的图形对象。这是窗户上的一个小地方。

#!/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()

每次调整窗口大小时,都会生成一个绘制事件。我们用size方法得到窗口的当前大小。我们使用窗口的大小将点分布在窗口的整个客户端区域。

qp.drawPoint(x, y)

我们用drawPoint方法画点。

PyQt6 颜色

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

#!/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值。第三个和第四个参数是矩形的宽度和高度。该方法使用当前笔和画笔绘制矩形。

PyQt6 QPen

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

#!/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像素间距等。

PyQt6 QBrush

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

#!/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)

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

Bézier 曲线


贝塞尔曲线是一条三次曲线。PyQt6中的贝塞尔曲线可以用QPainterPath创建。画家路径是由许多图形构建块组成的对象,如矩形、椭圆、直线和曲线。

#!/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路径创建贝塞尔曲线。曲线是使用cubicTo方法创建的,该方法有三个点:起点、控制点和终点。

qp.drawPath(path)

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

在PyQt6教程的这一部分中,我们做了一些基本的绘画。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐