QGraphicsPixmapItem如何设置鼠标碰撞框? [QT/C++]

How to Set Mouse Collision Box for QGraphicsPixmapItem? [QT/C++]

mousePressEventmouseReleaseEventmouseMoveEvent 等 QGraphicsPixmapItem 中重新实现任何鼠标事件函数时,图形项使用像素完美碰撞。例如,要触发 mousePressEvent,单击时鼠标必须恰好位于像素图中可见像素的顶部。

另一方面,我希望碰撞是基于像素图的宽度和高度的通用框:[0, 0, width, height]

如何实现?

(一些示例代码导致人们似乎喜欢那样):

class MyGraphicsItem: public QGraphicsPixmapItem {
public:
  MyGraphicsItem(): QGraphicsPixmapItem() {}

protected:
  void mousePressEvent(QGraphicsSceneMouseEvent* event) {
    // do stuff. Will be called when clicked exactly on the image
    QGraphicsPixmapItem::mousePressEvent(event);
  }
}

感谢 SteakOverflow 指出了正确的方向。

好吧,这是你要做的:

class MyGraphicsItem: public QGraphicsPixmapItem {
public:
  MyGraphicsItem(): QGraphicsPixmapItem() {
    // Change shape mode in constructor
    setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
  }

protected:
  void mousePressEvent(QGraphicsSceneMouseEvent* event) {
    // do stuff. Will be called when clicked exactly on the image
    QGraphicsPixmapItem::mousePressEvent(event);
  }
}

或者,您可以这样做:

class MyGraphicsItem: public QGraphicsPixmapItem {
public:
  MyGraphicsItem(): QGraphicsPixmapItem() {}

protected:
  void mousePressEvent(QGraphicsSceneMouseEvent* event) {
    // do stuff. Will be called when clicked exactly on the image
    QGraphicsPixmapItem::mousePressEvent(event);
  }

  // ::shape defines collision. 
  // This will make it a rect based on general dimensions of the pixmap
  QPainterPath shape() const {
    if(!pixmap().isNull()) {
        QPainterPath path;
        path.addRect(0, 0, pixmap().width(), pixmap().height());
        return path;
    } else {
        return QGraphicsPixmapItem::shape();
    }
  }
}