QQuickView: handling mouse events in C++

2019-07-20 20:48发布

问题:

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?

回答1:

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