简体   繁体   中英

QQuickView: handling mouse events in C++

I render my 3d model under qml controls using QQuickView::beforeRendering event. I want to do my mouse events handling in C++ if user clicks outside any of qml controls/ How can I found out in QQuickView::mousePressEvent that mouse is pressed outside qml controls?

I think it's easier to do it with a custom QQuickItem , because doing it with a custom QQuickView apparently means that you get the events before they reach any of the items.

Here's an example:

#include <QtQuick>

class MyItem : public QQuickItem
{
public:
    MyItem() {
        setAcceptedMouseButtons(Qt::AllButtons);
    }

    void mousePressEvent(QMouseEvent *event) {
        QQuickItem::mousePressEvent(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::fromLocalFile("main.qml"));
    view->show();

    return app.exec();
}

Put the custom item at the bottom of the scene and it will get all of the unhandled mouse events:

import QtQuick 2.3
import QtQuick.Controls 1.0
import Test 1.0

Rectangle {
    width: 400
    height: 400
    visible: true

    MyItem {
        anchors.fill: parent
    }

    Button {
        x: 100
        y: 100
        text: "Button"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM