如何使用QPainter+QPixmap实现鼠标绘图?

2021-06-14 23:51:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用鼠标画图。你知道吗

当我运行代码并尝试绘制时,在画布上看不到任何结果。怎么了?你知道吗

下面的代码只包含类画布代码,不包括UI和我的项目中的其他东西。你知道吗

from PyQt5 import uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Canvas(QLabel):
    def __init__(self, parent=None):
        super().__init__(parent)
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.white)
        self.setAutoFillBackground(True)
        self.setPalette(p)        
        self.setPixmap(QPixmap())
        self.pen = QPen()
        self.last = None
        self.painter = QPainter(self.pixmap())
        self.painter.begin(self)        

    def paintEvent(self, event):
        pass

    def mouseMoveEvent(self, event):
        if self.last:
            self.painter.setPen(self.pen)
            self.painter.drawLine(self.last, event.pos())

            self.last = event.pos()
            self.update()

    def mousePressEvent(self, event):
        self.last = event.pos()

    def mouseReleaseEvent(self, event):
        self.last = None