GraphicsItem使用一些透明部分绘制图像

2024-07-04 07:51:55 发布

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

我想通过鼠标事件透明图像。我尝试在图像上使用矩形,但它在异或模式下填充黑色,在异或模式下保留红色矩形

我的目标是用鼠标擦除一些像素,然后将多个图像混合在一起

有人能帮我吗

img

使用下面的代码,我得到this ,但为什么黑色而不是带条纹的透明背景

import sys

from PyQt5.QtCore import QRectF, Qt, QPoint, QPointF, QRect
from PyQt5.QtGui import QPen, QBrush, QPixmap, QPainter, QImage, QPainterPath, QColor, QBitmap
from PyQt5.QtWidgets import QApplication, QWidget, QGraphicsView, QGraphicsScene, QFrame, QGraphicsPixmapItem, \
    QGraphicsItem, QStyleOptionGraphicsItem, QGraphicsSceneMouseEvent, QGraphicsRectItem


class CutImg(QGraphicsItem):
    def __init__(self, qPixmap):
        super(CutImg, self).__init__()
        self.qPixmap = qPixmap

    def boundingRect(self):
        return QRectF(self.qPixmap.rect())

    def paint(self, qPainter, qStyleOptionGraphicsItem, widget=None):
        qPainter.drawPixmap(QPointF(), self.qPixmap)
        qPainter.setCompositionMode(QPainter.CompositionMode_Xor)
        qPainter.fillRect(QRectF(QPointF(30, 50), QPointF(100, 150)), QBrush(Qt.red))



class CutScene(QGraphicsScene):
    def __init__(self):
        super(CutScene, self).__init__()
        self.cuttedImg = None

    def setPixmap(self, qPixmap):
        self.mainImg = CutImg(qPixmap)
        self.addItem(self.mainImg)
        self.cuttedImg = qPixmap


class MainCutWindow(QGraphicsView):
    def __init__(self):
        super(MainCutWindow, self).__init__()
        self.scene = CutScene()
        self.setScene(self.scene)
        self.boardmargin = 100

    def setPixmap(self, qPixmap):
        self.scene = CutScene()
        self.setScene(self.scene)
        self.setFixedSize(qPixmap.width() + self.boardmargin * 2, qPixmap.height() + self.boardmargin * 2)
        self.scene.setPixmap(qPixmap)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainCutWindow()
    window.setPixmap(QPixmap('images/cat.jpg'))
    window.show()
    app.exec_()

Tags: from图像importselfinitdefscenepyqt5

热门问题