我已经继承了子类QGraphicsRectItem
,并且没有收到任何鼠标事件。我已经看到其他类似的问题,比如说我需要启用鼠标跟踪,但是setMouseTracking
它在QWidget中,而QGraphicsItem似乎不是QWidget。
我已经实现paint
,并且可以正常工作。在我的子类QGraphicsView中,我得到了鼠标事件。
文档似乎认为我应该只重写mousePressEvent函数(例如),并且应该开始获取事件。是否将mousePressEvent转发给QGraphicsView的超类似乎没有什么区别。
在子类QGraphicsView中,如果希望覆盖鼠标事件方法向下传播到项目,则需要调用它们的默认实现。例如:
CustomView::mousePressEvent(QMouseEvent *event)
{
// handle the event as you like
QGraphicsView::mousePressEvent(event); // then call default implementation
}
如果要接受悬停事件,则需要致电QGraphicsItem::setAcceptHoverEvents(true);
。否则,您无需启用任何特定的鼠标跟踪。
编辑:这是一个完整的工作示例:
#include <QtGui>
class CustomView : public QGraphicsView
{
protected:
void mousePressEvent(QMouseEvent *event)
{
qDebug() << "Custom view clicked.";
QGraphicsView::mousePressEvent(event);
}
};
class CustomItem : public QGraphicsRectItem
{
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << "Custom item clicked.";
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CustomItem item;
item.setRect(20, 20, 60, 60);
QGraphicsScene scene(0, 0, 100, 100);
scene.addItem(&item);
CustomView view;
view.setScene(&scene);
view.show();
return a.exec();
}
如问题中所述,我尝试过。我在QGraphicsItem中的mousepress事件上有一个断点,无论我是否这样做都不会调用它
QGraphicsView::mousePressEvent(event);
@Almo您是否重写了子类QGraphicsScene中的任何鼠标事件?
在我的QGraphicsView子类中,我创建一个QGraphicsScene,并使用它调用setScene。我还没有将QGraphicsScene子类化。
@Almo有关工作示例,请参见编辑。我的猜测是您
QGraphicsItem::boundingRect()
没有返回正确的矩形,或者如果您已重新实现QGraphicsItem::shape()
,那是不正确的。啊
QGraphicsSceneMouseEvent
。我一直在寻找QMouseEvent
一个参数,因为QGraphicsView
覆盖使用那些参数。我没注意到它们的区别QGraphicsItem
。您的示例指出了这一点。我很尴尬。:)