简体   繁体   English

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

[英]How to install and use an Event Filter written in Qt C++ in a QML application

I have a situation where I need to add keyboard shortcuts to an application that is mainly comprised of a QtQuick user interface. 我有一种情况需要将键盘快捷键添加到主要由QtQuick用户界面组成的应用程序中。 The version of Qt Quick is unfortunately locked to Qt5.3 and Shortcuts (the way we need them) were only introduced in Qt5.5 and Qt5.7 respectively. 不幸的是,Qt Quick的版本被锁定到Qt5.3,而快捷方式(我们需要它们的方式)分别仅在Qt5.5和Qt5.7中引入。

So, as a solution, I wrote an event filter that functions similarly to QShortcut (can't use QShortcut, hence the event filter). 因此,作为一个解决方案,我编写了一个事件过滤器,其功能类似于QShortcut(不能使用QShortcut,因此事件过滤器)。

Does anybody know how to install and use this eventfilter in QML? 有人知道如何在QML中安装和使用这个eventfilter吗?

One way would be to expose a singleton type to QML: 一种方法是将单例类型公开给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"

main.qml : 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)
}

If you have several different listeners, you could also do it declaratively by adding an object property to ShortcutListener that it would install an event filter on when set. 如果你有几个不同的监听器,你也可以通过向ShortcutListener添加一个object属性来声明性地执行它,它将在设置时安装事件过滤器。

For more info, see Integrating QML and C++ . 有关更多信息,请参阅集成QML和C ++

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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