Search code examples
c++qtqt-events

Using Hover Events


I am having trouble capturing the hover enter and hover leave events in a QGraphicsRectItem.

I have subclassed this object, and reimplemented the hover enter and hover leave handlers... or at least I think I have. I also set accepts hover event to true in the constructor.

The event is never fired, however. Breakpoints inside the handlers are never hit.

Here is the class:

#include "qhgraphicsrectitem.h"

QhGraphicsRectItem::QhGraphicsRectItem(QGraphicsRectItem *parent) :
    QGraphicsRectItem(parent)
{
    setAcceptHoverEvents(true);
    setAcceptsHoverEvents(true);
}

void QhGraphicsRectItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
    oldBrush = brush();
    setBrush(QBrush(QColor((oldBrush.color().red() + (0.5 * (255-oldBrush.color().red()))),(oldBrush.color().green() + (0.5 * (255-oldBrush.color().green()))),(oldBrush.color().blue() + (0.5 * (255-oldBrush.color().blue()))))));
}

void QhGraphicsRectItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
    setBrush(oldBrush);
}

What is it that I am doing wrong?


Solution

  • Did you mark your hoverEnterEvent and hoverLeaveEvent as virtual? If you didn't, the events could be triggering but the QGraphicsItem is handling the event instead.

    class QhGraphicsRectItem : public QGraphicsItem
    {
        ...
        virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
        virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
    }