温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to use QtPainter after starting the UI and later when a button is pressed?

python - 在启动UI之后以及以后按下按钮时如何使用QtPainter?

发布于 2020-03-27 10:44:41

我正在编写一个模拟GUI,在其中打开窗口时,QtPainter会立即绘制一个Pixmap。我使用了不同的按钮,这些按钮应该导致在像素图上绘画(线条和其他几何形式)

我试过编写将QtPainter对象作为参数并使用button.clicked.connect()调用函数的函数,但是图形从不出现在屏幕上。由于我是PyQt的新手,所以我不确定它的工作方式,但是我想我只能通过调用paintEvent()函数来绘画,但是如果我在paintEvent()中编写所有几何形式,我如何确保它们仅出现当按下按钮时?

查看更多

查看更多

提问者
frfritz
被浏览
9
Heike 2019-07-04 02:15

To draw directly onto a widget you can override it's paintEvent. The thing to remember when doing so is that paintEvent fires every time the Widget deems it necessary to redraw itself e.g. when it has been resized or moved. This means that when implementing your own version of paintEvent you need to draw all the shapes you want drawn on your widget. Note that paintEvent is rarely called directly. If you want the widget to redraw itself, you should call update() which will schedule a paintEvent for you.

这是一个简单的示例,其中在单击按钮时将任意矩形添加到画布。矩形存储在Canvas对象的数组中在中Canvas.paintEvent,我们创建的实例,QPainter并使用此对象绘制数组中的所有矩形。

from PyQt5 import QtWidgets, QtGui, QtCore
from random import randrange

class Canvas(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.rectangles = []

    def add_rectangle(self, rect, color):
        self.rectangles.append((rect, color))
        self.update()

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        brush = QtGui.QBrush(QtCore.Qt.white)
        painter.setBrush(brush)
        painter.drawRect(event.rect())

        pen = QtGui.QPen()
        pen.setWidth(3)
        for rect, color in self.rectangles:
            pen.setColor(color)
            painter.setPen(pen)
            brush.setColor(color)
            painter.setBrush(brush)
            painter.drawRect(rect)

class MyWindow(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.canvas = Canvas(self)
        self.button = QtWidgets.QPushButton('Add rectangle')
        self.button.clicked.connect(self.add_rectangle)

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.canvas)
        self.layout.addWidget(self.button)
        self.resize(500,500)

    def add_rectangle(self):
        w = self.canvas.width()
        h = self.canvas.height()
        x0, y0 = randrange(w), randrange(h)
        x1, y1 = randrange(w), randrange(h)

        shape = QtCore.QRect(min(x0,x1), min(y0,y1), abs(x0-x1), abs(y0-y1))
        color = QtGui.QColor.fromRgb(*(randrange(256) for i in range(3)), 180)
        self.canvas.add_rectangle(shape, color)


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    window = MyWindow()
    window.show()
    app.exec()

发布
问题

分享
好友

手机
浏览

扫码手机浏览