I have a QML LineEdit like:
TextField
{
id: testEdit
text: "0"
Keys.onPressed:
{
console.log("Press = " + event.key)
console.log("Current text is " + text)
}
Keys.onReleased:
{
console.log("Release = " + event.key)
console.log("Current text is " + text)
}
}
I want to change its text property by simulating key events . So I have C++ object (eventHandler) exposed to QML generating key events:
void normalKeyPress(QQuickItem *receiver, QString keys)
{
receiver->forceActiveFocus();
QKeySequence keysSeq = QKeySequence(keys);
for (auto idx = 0; idx < keysSeq.count(); ++idx)
{
auto keyCode = keysSeq[idx];
auto keyEvent = new QKeyEvent(QEvent::KeyPress, keyCode, Qt::NoModifier);
auto keyEventSent = QApplication::sendEvent(receiver, keyEvent);
keyEvent = new QKeyEvent(QEvent::KeyRelease, keyCode, Qt::NoModifier);
keyEventSent = QApplication::sendEvent(receiver, keyEvent);
}
}
Now in QML, when I do:
testEdit.forceActiveFocus()
eventHandler.normalKeyPress(testEdit, "4")
eventHandler.normalKeyPress(testEdit, "Enter")
I get the following output:
qml: Press = 52
qml: Current text is 0
qml: Release = 52
qml: Current text is 0
qml: Press = 16777221
qml: Current text is 0
qml: Release = 16777221
qml: Current text is 0
So key events are correctly received by the QML LineEdit.
But why text property is not updated accordingly?
UPDATE #1: if I use a TextInput
instead of a TextField
, then it works as expected.
Well, looking at your code, I think the solution in adding setProperty()
method to your reciever
. So your code will be:
void normalKeyPress(QQuickItem *receiver, QString keys)
{
receiver->forceActiveFocus();
receiver->setProperty("text", keys);
<...>
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.