在Qt5的QQuickItem 上捕获mouseMoveEvent

catch mouseMoveEvent on Qt5's QQuickItem

本文关键字:mouseMoveEvent QQuickItem Qt5      更新时间:2023-10-16

我遵循我上一个问题的回答。但是我被卡住了。

我正在开发一个Qt5应用程序,我想在鼠标悬停在QQuickItem项目时捕获mouseMoveEvent事件。但我不知道如何让它工作。

我已经隔离了有问题的代码(使用此代码):

main.cpp :

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQuick>
class MyItem : public QQuickItem
{
public:
    MyItem()
    {
        setAcceptHoverEvents(true);
        setAcceptedMouseButtons(Qt::AllButtons);
        setFlag(ItemAcceptsInputMethod, true);
    }
    void mousePressEvent(QMouseEvent* event)
    {
        QQuickItem::mousePressEvent(event);
        qDebug() << event->pos();
    }
    void mouseMoveEvent(QMouseEvent* event)
    {
        QQuickItem::mouseMoveEvent(event);
        qDebug() << event->pos();
    }
};
int main(int argc, char** argv)
{
    QGuiApplication app(argc, argv);
    QQuickView* view = new QQuickView;
    qmlRegisterType<MyItem>("Test", 1, 0, "MyItem");
    view->setSource(QUrl(QStringLiteral("qrc:/main.qml")));
    view->show();
    return app.exec();
}

main.qml :

import QtQuick 2.4
import QtQuick.Controls 1.3
import Test 1.0
Rectangle {
    width: 400
    height: 400
    visible: true
    MyItem {
        anchors.fill: parent
    }
    Button {
        x: 100
        y: 100
        text: "Button"
    }
}

在这个示例代码中,mousePressEvent被捕获,但mouseMoveEvent没有,为什么?

感谢Jeremy Friesner的评论,我得到了工作代码:

main.cpp:

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtQuick>
class MyItem : public QQuickItem
{
public:
    MyItem()
    {
        setAcceptHoverEvents(true);
        setAcceptedMouseButtons(Qt::AllButtons);
        setFlag(ItemAcceptsInputMethod, true);
    }
    void mousePressEvent(QMouseEvent* event)
    {
        QQuickItem::mousePressEvent(event);
        qDebug() << event->pos();
    }
    //This is function to override:
    void hoverMoveEvent(QHoverEvent* event) {
        QQuickItem::hoverMoveEvent(event);
        qDebug() << event->pos();
    }
};
int main(int argc, char** argv)
{
    QGuiApplication app(argc, argv);
    QQuickView* view = new QQuickView;
    qmlRegisterType<MyItem>("Test", 1, 0, "MyItem");
    view->setSource(QUrl(QStringLiteral("qrc:/main.qml")));
    view->show();
    return app.exec();
}

main.qml:

import QtQuick 2.4
import QtQuick.Controls 1.3
import Test 1.0
Rectangle {
    width: 400
    height: 400
    visible: true
    MyItem {
        anchors.fill: parent
    }
    Button {
        x: 100
        y: 100
        text: "Button"
    }
}