忽略在QGraphicsObject上的鼠标拖动

2024-09-30 18:24:32 发布

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

我在一个继承自QGraphicsObject的类中放入了一个简单的QRectF。我希望此矩形区域通过鼠标拖动事件。i、 现在,我已经点击并拖动移动矩形。但是,我需要将该事件发送到后台,在那里我需要选择多个项目(默认情况下这是可能的)。为mouseevents设置属性WA_TransparentForMouseEvents似乎非常适合,但据我所知,这仅适用于QWidget

class GraphicsItem(QtWidgets.QGraphicsObject):
    def __init__(self):
        self._box = QtCore.QRectF(0, 0, 100, 100)

    def mouseMoveEvent(self, event):
        if (self._box.contains(event.pos()):
            # set event transparency here

这可能吗? 谢谢


Tags: 项目selfboxevent区域属性def事件
1条回答
网友
1楼 · 发布于 2024-09-30 18:24:32

您可以为项目定义^{}。我不知道你的GraphicsItem看起来像什么,但这里有一个通用的例子。另一项可以从self._box区域内选择

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

class GraphicsItem(QGraphicsObject):
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._box = QRectF(0, 0, 100, 100)
        self.setFlags(self.ItemIsSelectable | self.ItemIsMovable)

    def boundingRect(self):
        return QRectF(-100, -50, 300, 200)

    def shape(self):
        area = QPainterPath()
        area.addRect(self.boundingRect())
        box = QPainterPath()
        box.addRect(self._box)
        return area - box

    def paint(self, painter, *args):
        painter.setBrush(QColor(0, 255, 0, 180))
        painter.drawPath(self.shape())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    scene = QGraphicsScene(-200, -150, 500, 400)
    rect = scene.addRect(30, 30, 30, 30, Qt.black, Qt.red)
    rect.setFlags(rect.ItemIsSelectable | rect.ItemIsMovable)
    scene.addItem(GraphicsItem())

    view = QGraphicsView(scene)
    view.show()
    sys.exit(app.exec_())

或者,如果您特别想重新实现鼠标事件处理程序:

def mousePressEvent(self, event):
    event.ignore() if event.pos() in self._box else super().mousePressEvent(event)

相关问题 更多 >