没有按住鼠标按钮就不接收mouseMoveEvent

时间:2017-07-10 11:57:11

标签: c++ qml qt5 qtquick2

我正在尝试实现悬停功能,当我将鼠标悬停在我的项目上的特定区域时,我重新绘制该项目。

class TestItem : public QQuickItem
{
    Q_OBJECT

public:
    explicit TestItem(QQuickItem *parent = nullptr) : QQuickItem(parent)
    {
        setAcceptHoverEvents(true);
        setAcceptedMouseButtons(Qt::AllButtons);
    }

protected:
    // QQuickItem interface
    void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE
    {
        qDebug() << "mouseMoveEvent()" << event->buttons() << event->x() << event->y();
    }

    void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE
    {
        qDebug() << "mousePressEvent()" << event->buttons() << event->x() << event->y();
    }

    void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE
    {
        qDebug() << "mouseReleaseEvent()" << event->buttons() << event->x() << event->y();
    }
};

然而,当我将光标移动到我的项目上时,使用此类我终端上不会收到任何“mouseMoveEvent()”输出。它仅在按住任何鼠标按钮时有效。

如何在不强迫用户按住任何鼠标按钮的情况下实现此目的?

1 个答案:

答案 0 :(得分:2)

可以自己解决,问题是我正在听错事件。正确的事件应该是hoverMoveEvent()

使用以下类,我得到了正确的输出:

class TestItem : public QQuickItem
{
    Q_OBJECT

public:
    explicit TestItem(QQuickItem *parent = nullptr) : QQuickItem(parent)
    {
        setAcceptHoverEvents(true);
    }

protected:
    // QQuickItem interface
    void hoverEnterEvent(QHoverEvent *event) Q_DECL_OVERRIDE
    {
        qDebug() << "hoverEnterEvent()" << event->posF();
    }

    void hoverMoveEvent(QHoverEvent *event) Q_DECL_OVERRIDE
    {
        qDebug() << "hoverMoveEvent()" << event->posF();
    }

    void hoverLeaveEvent(QHoverEvent *event) Q_DECL_OVERRIDE
    {
        qDebug() << "hoverLeaveEvent()" << event->posF();
    }
};