在paintEvent函数外实现(即,不使用paintEvent函数):
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class myMainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.image = QPixmap(1000, 1000)
self.image.fill(Qt.transparent)# 填充透明色
self.setWindowTitle("简单的画板")
self.pos_xy = []
self.pen = QPen(Qt.black, 2, Qt.SolidLine)
self.painton = True
self.imageLabel = QLabel()
self.setCentralWidget(self.imageLabel)
self.imageLabel.setPixmap(self.image)
def mouseMoveEvent(self, event):
pos_tmp = (event.pos().x(), event.pos().y())
self.pos_xy.append(pos_tmp)
painter = QPainter(self.image)
painter.setPen(self.pen)
if len(self.pos_xy) > 1:
point_start = self.pos_xy[0]
for pos_tmp in self.pos_xy:
painter.drawLine(point_start[0], point_start[1], pos_tmp[0], pos_tmp[1])
point_start = pos_tmp
self.imageLabel.setPixmap(self.image)
def mouseReleaseEvent(self, event):
self.pos_xy = []
app = QApplication(sys.argv)
form = myMainWindow()
form.setMinimumSize(1000, 1000)
form.show()
app.exec_()
使用paintEvent函数实现:
class myMainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("简单的画板")
self.image = QPixmap(1000, 1000)
self.image.fill(Qt.transparent) # 填充透明色
self.painton = True
#self.setMouseTracking(True)#默认状态(False):鼠标按下移动mouseMoveEvent才能捕捉到
self.pos_xy = []
self.pen = QPen(Qt.black, 2, Qt.SolidLine)
self.imageLabel = QLabel()
self.setCentralWidget(self.imageLabel)
self.imageLabel.setPixmap(self.image)
#self.imageLabel.setMouseTracking(True)
def paintEvent(self,event):
painter = QPainter(self.image)
#painter.begin(self)
painter.setPen(self.pen)
if len(self.pos_xy) > 1:
point_start = self.pos_xy[0]
for pos_tmp in self.pos_xy:
point_end = pos_tmp
if point_end == (-1, -1):
point_start = (-1, -1)
continue
if point_start == (-1, -1):
point_start = point_end
continue
painter.drawLine(point_start[0], point_start[1], point_end[0], point_end[1])
point_start = point_end
#painter.end()
self.imageLabel.setPixmap(self.image)
def mouseMoveEvent(self, event):
if self.painton:
pos_tmp = (event.pos().x(), event.pos().y())
self.pos_xy.append(pos_tmp)
self.update()
def mouseReleaseEvent(self, event):
pos_test = (-1, -1)#用(-1,-1)作为一笔的断点
self.pos_xy.append(pos_test)
self.update()
方法一:Qpainter实例是局部的,画完一笔就释放了。占用内存小。但是无法撤回。
方法二:painterEvent() ,update()函数,会发生重绘事件。占用内存大,但是对上面代码稍稍加几个记录历史路径的变量可以实现画板的撤回功能。