忽略鼠标拖动到QGraphicsObject上



我有一个简单的QRectF,我已经把从QGraphicsObject继承的类。我想让这个矩形的区域通过鼠标拖动事件。也就是说,现在,我有点击和拖动移动矩形,然而,我需要的事件发送到后台,我需要选择多个项目(这是可能的默认)。设置属性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

这可能吗?谢谢。

您可以为项目定义QGraphicsItem.shape()。我不知道你的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)

最新更新