QGraphicsItem doesn't receive mouse hover events

百般思念 提交于 2019-12-19 12:24:35

问题


I have a class derived from QGraphicsView, which contains QGraphicsItem-derived elements. I want these elements to change color whenever the mouse cursor hovers over them, so I implemented hoverEnterEvent (and hoverLeaveEvent):

void MyGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent* event)
{
    update (boundingRect());
}

However, this event handler code is never executed. I've explicitly enabled mouse tracking:

MyGraphicsView::MyGraphicsView(MainView *parent) :
    QGraphicsView(parent)
{
    setMouseTracking(true);
    viewport()->setMouseTracking(true);
    ...
}

Still, no luck. What am I doing wrong?


回答1:


Fixed it. I need to use setAcceptHoverEvents(true) in the constructor of my QGraphicsItem-derived class.




回答2:


In my case, hover events wouldn't work if I overrode mouseMoveEvent in my implementation of the QGraphicsView class. I fixed this by adding a call to

QGraphicsView::mouseMoveEvent(event);

which propagated the event to the parent, which in turn sent it out to all the scene items.



来源:https://stackoverflow.com/questions/2940392/qgraphicsitem-doesnt-receive-mouse-hover-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!