如何使用从C ++生成的键事件更改QML TextField文本属性

时间:2016-05-27 16:43:34

标签: c++ qt qml

我有一个QML LineEdit,如:

$stateProvider
.state('contacts', {
    abstract: true,
    url: '/:my_id/contacts',
    templateUrl: 'contacts.html'
})
.state('contacts.list', {
    url: 'list',
    // loaded into ui-view of parent's template
    templateUrl: 'contacts.list.html'
})
.state('contacts.detail', {
    url: 'detail',
    'dontUseParentTemplate': true, // something like that
    // loaded into ui-view of parent's template
    templateUrl: 'contacts.detail.html'
})

我想通过模拟关键事件来更改其文本属性 。所以我将C ++对象(eventHandler)暴露给生成关键事件的QML:

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)
  }
}

现在在QML中,当我这样做时:

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);
  }
}

我得到以下输出:

testEdit.forceActiveFocus()
eventHandler.normalKeyPress(testEdit, "4")
eventHandler.normalKeyPress(testEdit, "Enter")

因此QML LineEdit正确接收了关键事件。

但为什么text属性没有相应更新?

更新#1:如果我使用的是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 而不是TextInput,那么它会按预期工作。

1 个答案:

答案 0 :(得分:0)

好吧,看看你的代码,我认为在你的setProperty()中添加reciever方法的解决方案。所以你的代码将是:

void normalKeyPress(QQuickItem *receiver, QString keys)
{
  receiver->forceActiveFocus();
  receiver->setProperty("text", keys);

  <...>
}