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



当在QGraphicsPixmapItem中重新实现任何鼠标事件函数(如mousePressEventmouseReleaseEventmouseMoveEvent时,图形项使用像素完美碰撞。例如,对于要触发的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();
    }
  }
}

最新更新