问题
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?
回答1:
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);
}
回答2:
Is your item located under a QGraphicsItemGroup
?
I had this exact same issue until I found this quote:
"A QGraphicsItemGroup
is a special type of compound item that treats itself and all its children as one item (i.e., all events and geometries for all children are merged together)."
(Look here: http://qt-project.org/doc/qt-4.8/qgraphicsitemgroup.html)
What this means is that QGraphicsItemGroup
calls setHandlesChildEvents(true)
.
I fixed my issue by calling parentItem->setHandlesChildEvents(false)
on any (and all) groups located above my item to capture hover events. Poof! The events began showing up in the virtual callbacks you mention.
来源:https://stackoverflow.com/questions/12428045/using-hover-events