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

时间:2018-03-21 12:06:31

标签: c++ qt mouseevent collision qgraphicsitem

在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);
  }
}

1 个答案:

答案 0 :(得分:0)

感谢SteakOverflow在正确的方向上找到了一点。

Aiiright,这是你要做的事情:

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();
    }
  }
}