在Qt5的QQuickItem上捕获mouseMoveEvent

时间:2015-05-17 00:01:49

标签: c++ qt qml qt5

我正在关注previous question的回复。但我被U_U困住了。

我正在开发一个Qt5应用程序,我希望在鼠标悬停QQuickItem项目时捕获mouseMoveEvent事件。但我不知道如何使其发挥作用。

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

的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不是,为什么?我认为解决方案必须是微不足道的,但我看不出我的错误。

1 个答案:

答案 0 :(得分:4)

感谢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"
    }
}