Qt5乱用图层 - QPaintDevice:无法破坏正在绘制的设备

时间:2016-10-05 06:26:26

标签: python qt pyqt5 qgraphicsscene qpainter

我试图为多层图片重新实施the scribble demo app。我正在努力在场景中绘制像素图,因为画家抱怨早期被摧毁。

  

QPaintDevice:无法销毁正在绘制的绘图设备

你可以帮我修改我的代码,这样你就可以用红笔在roilayer像素图上绘图,并且这个图层开始透明。

#!/usr/bin/python3

import sys
import os
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsPixmapItem
from PyQt5.QtGui import QPixmap, QImage, QPainter, QPen
from PyQt5.QtCore import Qt, QRect


class Main(QGraphicsView):

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Scribble with layers")
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        self.image = QImage('sample/test.bmp')
        self.imlayer = QGraphicsPixmapItem(QPixmap.fromImage(self.image))
        self.roilayer = QGraphicsPixmapItem(QPixmap(self.image.size()))
        self.addlayer(self.imlayer)
        self.addlayer(self.roilayer)
        self.drawing = False
        self.lastPoint = None
        self.pencolour = Qt.red
        self.penwidth = 2
        self.show()

    def addlayer(self, layer):
        self.scene.addItem(layer)
        self.updateviewer()

    def updateviewer(self):
        self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)

    def mousePressEvent(self, event):
        # print(event.modifiers())
        if event.button() == Qt.LeftButton:
            self.lastPoint = event.pos()
            self.drawing = True

    def mouseMoveEvent(self, event):
        if (event.buttons() & Qt.LeftButton) and self.drawing:
            self.drawlineto(event.pos())

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton and self.drawing:
            self.drawlineto(event.pos())
            self.drawing = False

    def drawlineto(self, position):
        pixmap = self.roilayer.pixmap()
        painter = QPainter(pixmap)
        painter.setPen(QPen(self.pencolour, self.penwidth, Qt.SolidLine,
                Qt.RoundCap, Qt.RoundJoin))
        painter.drawLine(self.lastPoint, position)
        self.imlayer.setPixmap(pixmap)
        self.modified = True

        rad = self.penwidth / 2 + 2
        self.update(QRect(self.lastPoint, position).normalized().adjusted(-rad, -rad, +rad, +rad))
        self.lastPoint = position


if __name__ == '__main__':
    app = QApplication([])
    main = Main()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。解决方案是对这部分代码执行以下操作:

    def drawlineto(self, position):
        pixmap = self.roilayer.pixmap()
        painter = QPainter()
        painter.begin(pixmap)
        painter.setPen(QPen(self.pencolour, self.penwidth, Qt.SolidLine,
            Qt.RoundCap, Qt.RoundJoin))
        painter.drawLine(self.lastPoint, position)
        painter.end()
        self.imlayer.setPixmap(pixmap)
        self.modified = True