使用悬停事件

Using Hover Events

本文关键字:事件 悬停      更新时间:2023-10-16

我在捕获QGraphicsRectItem中的悬停进入和悬停离开事件时遇到问题。

我已经子类化了这个对象,并重新实现了悬停输入和悬停离开处理程序......或者至少我认为我有。我还在构造函数中将接受悬停事件设置为 true。

但是,该事件永远不会触发。永远不会命中处理程序内的断点。

这是类:

#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);
}

我做错了什么?

您是否将

hoverEnterEventhoverLeaveEvent标记为虚拟? 如果不这样做,事件可能会触发,但QGraphicsItem正在处理事件。

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

您的物品是否位于QGraphicsItemGroup下?

在我找到这句话之前,我遇到了完全相同的问题:

"QGraphicsItemGroup是一种特殊类型的复合项目,它将自身及其所有子项视为一个项目(即,所有子项的所有事件和几何图形都合并在一起)。

(看这里: http://qt-project.org/doc/qt-4.8/qgraphicsitemgroup.html)

这意味着QGraphicsItemGroup调用setHandlesChildEvents(true)

通过在项目上方的任何(和所有)组上调用parentItem->setHandlesChildEvents(false)来捕获悬停事件,从而解决了我的问题。 噗! 事件开始显示在您提到的虚拟回调中。