23

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?

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281

2 Answers2

38

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

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
  • 4
    I had this same problem and removing the `mouseMoveEvent` implementation from my `QGraphicsView` was also necessary to fix it. Now that I have it working I could probably add `mouseMoveEvent` back in as long as I figure out a way for it to not eat up the `QEvent`. – Cory Klein Mar 05 '13 at 22:42
  • Thank you so much! You just ended great suffering – Freedom_Ben Aug 18 '13 at 16:50
  • @CoryKlein did you find the way to use both mouseMoveEvent and hover events? – lena Feb 29 '16 at 13:11
  • @lena honestly I don't remember – Cory Klein Feb 29 '16 at 13:13
7

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.

Eustace
  • 313
  • 5
  • 12