我正在从事一个基本上是Paint的项目。我实现了打开文件功能,因此当我打开文件时,它会加载到QPixmap中。
问题是:当我尝试绘制成功加载的QPixmap时,我的应用程序崩溃了(没有错误或什么,它只是关闭了自己)。我将提供用于绘制和打开文件的代码。我认为在这种情况下,其余部分(UI等)不是必需的。
绘图:
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.myPixmap = QPixmap(600, 600)
self.painter = QPainter(self.myPixmap)
self.pen = QPen()
self.painter.setPen(self.pen)
self.painter.fillRect(0, 0, 600, 600, Qt.white)
self.setPixmap(self.myPixmap)
self.last = None
def mouseMoveEvent(self, event):
if self.last:
self.painter.setPen(self.pen)
self.painter.drawLine(self.last, event.pos())
self.last = event.pos()
self.setPixmap(self.myPixmap)
self.update()
def mousePressEvent(self, event):
self.last = event.pos()
def mouseReleaseEvent(self, event):
self.last = None
打开文件:
def openFile(self):
openFile_file = QFileDialog.getOpenFileName(None, 'Open File:', '', 'Images (*.png *.bmp *.jpg)')
openFile_ok = self.canvas.myPixmap.load(openFile_file[0])
self.canvas.setPixmap(self.canvas.myPixmap)
self.canvas.update()
print('open', openFile_ok)
答案 0 :(得分:1)
两个主要问题是:1)没有结束在施工中完成的绘画,以及2)在加载新图像后未重置画家。
import sys
from PyQt5.QtGui import QPixmap, QPainter, QPen
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QFileDialog
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.myPixmap = QPixmap(600, 600)
self.painter = QPainter(self.myPixmap)
self.pen = QPen()
self.painter.setPen(self.pen)
self.painter.fillRect(0, 0, 600, 600, Qt.white)
self.painter.end() # Need to end the painting here
self.setPixmap(self.myPixmap)
self.last = None
self.image_loaded = False
def mouseMoveEvent(self, event):
if self.last:
self.painter.setPen(self.pen)
self.painter.drawLine(self.last, event.pos())
self.last = event.pos()
self.setPixmap(self.myPixmap)
self.update()
def mousePressEvent(self, event):
if not self.image_loaded:
self.openFile()
self.image_loaded = True
self.last = event.pos()
def mouseReleaseEvent(self, event):
self.last = None
def openFile(self):
openFile_file = QFileDialog.getOpenFileName(None, 'Open File:', '', 'Images (*.png *.bmp *.jpg)')
openFile_ok = self.myPixmap.load(openFile_file[0])
self.setPixmap(self.myPixmap)
self.painter = QPainter(self.myPixmap) # Need to reset the painter...there may be another method without creating a new painter
self.painter.setPen(self.pen)
self.update()
print('open', openFile_ok)
app = QApplication(sys.argv)
label = Canvas()
label.show()
sys.exit(app.exec_())