问题
I have a qml Window with an Item which has
Keys.onPressed {
}
And I have a c++ class which has
protected:
void keyPressEvent(QKeyEvent *event);
What needs to go inside the Keys.onPressed? I have tried
myclass.keyPressEvent(event)
and I have tried a public Q_INVOKABLE function (handleKeyPress) in my c++ class with parameter (QKeyEvent * event) from which I wanted to call the keyPressEvent.
At runtime the former gives
"TypeError: Property 'keyPressEvent' of object myclass is not a function"
The latter
"Error: Unknown method parameter type: QKeyEvent*".
(I have then found out that qml can only handle pointers to QObject, and QKeyEvent doesn't inherit from QObject but that doesn't help me in finding a solution.)
So what is the correct way to get the keyPressEvent called from qml? Or if this is the wrong approach altogether, what is the correct one if my class needs the information QKeyEvent can give me like which key was pressed etc.?
回答1:
KeyEvent
is not a QKeyEvent *
, but a class that inherits from QObject
and encapsulates a QKeyEvent
, so QKeyEvent
can not be accessed, but you could access the q-properties as shown below:
C++
protected:
Q_INVOKABLE void someMethod(QObject *event){
qDebug()<< "key" << event->property("key").toInt();
qDebug()<< "text" << event->property("text").toString();
qDebug()<< "modifiers" << event->property("modifiers").toInt();
qDebug()<< "isAutoRepeat" << event->property("isAutoRepeat").toBool();
qDebug()<< "count" << event->property("count").toInt();
qDebug()<< "nativeScanCode" << event->property("nativeScanCode").value<quint32>();
qDebug()<< "accepted" << event->property("accepted").toBool();
}
QML:
Keys.onPressed: myclass_obj.someMethod(event)
But that is not recommended. Your class should not know the event directly, but the best thing is that you handle the logic in QML and that the function:
Keys.onPressed: {
if(event.key === Qt.Key_A){
myclass_obj.foo_A()
}
else if(event.key === Qt.Key_B){
myclass_obj.foo_B()
}
}
Or if you want to know only the key could be as follows
C++
Q_INVOKABLE void someMethod(int key){
qDebug()<< key;
}
QML
Keys.onPressed: myclass_obj.someMethod(event.key)
来源:https://stackoverflow.com/questions/51491711/how-to-call-qt-keypresseventqkeyevent-event-from-qml-keys-onpressed