当前位置: 首页 > 文档资料 > PyQt5 开发文档 >

绘图

优质
小牛编辑
114浏览
2023-12-01

PyQt5 绘图系统能渲染矢量图像、位图图像和轮廓字体文本。一般会使用在修改或者提高现有组件的功能,或者创建自己的组件。使用 PyQt5 的绘图 API 进行操作。

绘图由 paintEvent() 方法完成,绘图的代码要放在 QPainter 对象的 begin()end() 方法之间。是低级接口。

文本涂鸦

我们从画一些 Unicode 文本开始。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
In this example, we draw text in Russian Cylliric.

"""

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

class Example(QWidget):

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

        self.initUI()


    def initUI(self):      

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

        self.setGeometry(300, 300, 280, 170)
        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.AlignCenter, self.text)        


if __name__ == '__main__':

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

写了一些文本上下居中对齐的俄罗斯 Cylliric 语言的文字。

def paintEvent(self, event):
...

在绘画事件内完成绘画动作。

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

QPainter 是低级的绘画类。所有的绘画动作都在这个类的 begin()end() 方法之间完成,绘画动作都封装在 drawText() 内部了。

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

为文字绘画定义了笔和字体。

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

drawText() 方法在窗口里绘制文本,rect() 方法返回要更新的矩形区域。

程序展示:

drawing text

点的绘画

点是最简单的绘画了。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

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

"""

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

class Example(QWidget):

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

        self.initUI()


    def initUI(self):      

        self.setGeometry(300, 300, 300, 190)
        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.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)     


if __name__ == '__main__':

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

我们在窗口里随机的画出了 1000 个点。

qp.setPen(Qt.red)

设置笔的颜色为红色,使用的是预定义好的颜色。

size = self.size()

每次更改窗口大小,都会产生绘画事件,从 size() 方法里获得当前窗口的大小,然后把产生的点随机的分配到窗口的所有位置上。

qp.drawPoint(x, y)

drawPoint() 方法绘图。

程序展示:

points