虽然您不会使用
boundingRect()
要检测碰撞,必须返回
QRect
这是覆盖
shape
,为此,我们可以使用
boundingRect()
方法
QPainterPath
,此外,无需覆盖形状
QGraphicsRectItem
。
class RectItem(QGraphicsRectItem):
def __init__(self, *args):
super().__init__(*args)
self.setFlag(QGraphicsItem.ItemIsMovable)
self.setPen(QPen(Qt.cyan))
class CurveItem(QGraphicsItem):
def __init__(self):
super().__init__()
self.path = self._setupPath()
def paint(self, painter, styles, widget=None):
painter.drawPath(self.path)
def boundingRect(self):
return self.path.boundingRect()
def shape(self):
return self.path
def _setupPath(self):
path = QPainterPath()
path.moveTo(0, 0)
path.cubicTo(99, 0, 50, 50, 99, 99)
path.cubicTo(0, 99, 50, 50, 0, 0)
return path
class Scene(QGraphicsScene):
def __init__(self):
super().__init__()
self.curve_item = CurveItem()
self.rect_item = RectItem(-50, -50, 25, 25)
self.addItem(self.curve_item)
self.addItem(self.rect_item)
def mouseMoveEvent(self, e):
print(self.collidingItems(self.rect_item, mode=Qt.IntersectsItemShape))
super().mouseMoveEvent(e)