Last active
September 23, 2022 07:23
-
-
Save mitchcurtis/0d95a6d2f016fe6fc9434ded60b6a07d to your computer and use it in GitHub Desktop.
Qt Quick KeyListener [eventFilter, event filter]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QGuiApplication> | |
#include <QQmlApplicationEngine> | |
#include <QDebug> | |
#include <QKeyEvent> | |
class KeyListener : public QObject | |
{ | |
Q_OBJECT | |
public: | |
KeyListener() {} | |
bool eventFilter(QObject *watched, QEvent *event) { | |
if (event->type() == QEvent::KeyPress) { | |
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); | |
qDebug() << "text" << keyEvent->text() << "key" << keyEvent->key() << "modifiers" << keyEvent->modifiers(); | |
} | |
QObject::eventFilter(watched, event); | |
return false; | |
} | |
}; | |
int main(int argc, char *argv[]) | |
{ | |
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) | |
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); | |
#endif | |
QGuiApplication app(argc, argv); | |
QQmlApplicationEngine engine; | |
const QUrl url(QStringLiteral("qrc:/main.qml")); | |
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, | |
&app, [url](QObject *obj, const QUrl &objUrl) { | |
if (!obj && url == objUrl) | |
QCoreApplication::exit(-1); | |
}, Qt::QueuedConnection); | |
engine.load(url); | |
if (engine.rootObjects().isEmpty()) { | |
qWarning() << "No root objects!"; | |
return 1; | |
} | |
KeyListener keyListener; | |
engine.rootObjects().first()->installEventFilter(&keyListener); | |
return app.exec(); | |
} | |
#include "main.moc" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import QtQuick 2.15 | |
import QtQuick.Controls 2.15 | |
ApplicationWindow { | |
objectName: "window" | |
width: 800 | |
height: 800 | |
visible: true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment