As I already pointed out in this answer: KeyEvent
is not a QKeyEvent
but a QObject that exposes some properties but not all. A workaround is to create a QObject that installs an event filter to the item and exposes that property:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickItem>
class KeyHelper: public QObject{
Q_OBJECT
Q_PROPERTY(QQuickItem* target READ target WRITE setTarget NOTIFY targetChanged)
public:
using QObject::QObject;
QQuickItem* target() const {
return m_target;
}
void setTarget(QQuickItem* item){
if(m_target)
m_target->removeEventFilter(this);
m_target = item;
if(m_target)
m_target->installEventFilter(this);
Q_EMIT targetChanged(m_target);
}
bool eventFilter(QObject *watched, QEvent *event){
if(watched == m_target && event->type() == QEvent::KeyPress){
if(QKeyEvent *ke = static_cast<QKeyEvent *>(event))
Q_EMIT nativeVirtualKeyChanged(ke->nativeVirtualKey());
}
return QObject::eventFilter(watched, event);
}
signals:
void nativeVirtualKeyChanged(quint32 nativeVirtualKey);
void targetChanged(QQuickItem* item);
private:
QPointer<QQuickItem> m_target;
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<KeyHelper>("qt.keyhelper", 1, 0, "KeyHelper");
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);
return app.exec();
}
#include "main.moc"
import QtQuick 2.12
import QtQuick.Window 2.12
import qt.keyhelper 1.0
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Item {
id: item
focus: true
anchors.fill: parent
}
KeyHelper{
target: item
onNativeVirtualKeyChanged: console.log(nativeVirtualKey)
}
}