如何在QML应用程序中安装和使用Qt C++编写的事件过滤器

Lou*_*kin 3 c++ qt qml qt-quick

我有一种情况需要将键盘快捷键添加到主要由QtQuick用户界面组成的应用程序中.不幸的是,Qt Quick的版本被锁定到Qt5.3,而快捷方式(我们需要它们的方式)分别仅在Qt5.5和Qt5.7中引入.

因此,作为一个解决方案,我编写了一个事件过滤器,其功能与QShortcut类似(不能使用QShortcut,因此事件过滤器).

有人知道如何在QML中安装和使用这个eventfilter吗?

Mit*_*tch 7

一种方法是将单例类型公开给QML:

#include <QtGui>
#include <QtQml>

class ShortcutListener : public QObject
{
    Q_OBJECT

public:
    ShortcutListener(QObject *parent = nullptr) :
        QObject(parent)
    {
    }

    Q_INVOKABLE void listenTo(QObject *object)
    {
        if (!object)
            return;

        object->installEventFilter(this);
    }

    bool eventFilter(QObject *object, QEvent *event) override
    {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
            qDebug() << "key" << keyEvent->key() << "pressed on" << object;
            return true;
        }
        return false;
    }
};

static QObject *shortcutListenerInstance(QQmlEngine *, QJSEngine *engine)
{
    return new ShortcutListener(engine);
}

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterSingletonType<ShortcutListener>("App", 1, 0, "ShortcutListener", shortcutListenerInstance);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

#include "main.moc"
Run Code Online (Sandbox Code Playgroud)

main.qml:

import QtQuick 2.5
import QtQuick.Window 2.2

import App 1.0

Window {
    id: window
    width: 640
    height: 480
    visible: true

    Component.onCompleted: ShortcutListener.listenTo(window)
}
Run Code Online (Sandbox Code Playgroud)

如果你有几个不同的监听器,你也可以通过添加一个object属性来声明性地执行它ShortcutListener,它将在设置时安装事件过滤器.

有关更多信息,请参阅集成QML和C++.