4

我使用 QQuickView::beforeRendering 事件在 qml 控件下渲染我的 3d 模型。如果用户在任何 qml 控件之外单击,我想在 C++ 中处理我的鼠标事件/我如何在 QQuickView::mousePressEvent 中发现鼠标在 qml 控件之外被按下?

4

1 回答 1

5

我认为使用 custom 更容易QQuickItem,因为使用 customQQuickView显然意味着您可以在事件到达任何项目之前获得事件。

这是一个例子:

#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();
}

将自定义项放在场景底部,它将获取所有未处理的鼠标事件:

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"
    }
}
于 2015-04-13T16:35:20.047 回答