1

我有一种情况,我想将 QML 事件传递给初始事件处理程序中间的另一个 QML 项目。例如

Item {
   id: item1

   Keys.onPressed: {
      // Pre-process...

      passEventToObject(event, item2);

      // Post-process based on results of event passing...
   }
}

TextInput {
   id: item2
   // Expect key press event to be handled by text input
}

我能做些什么来实现passEventToObject

笔记:

  • 我无权在Keys.onPressed里面修改item2,它是 QML 内置的(TextInput)。
  • 事件传递必须发生在中间item1.Keys.onPressed
4

3 回答 3

3

您可以简单地在您的第一个对象信号处理程序中调用另一个对象的信号:

Item {
   id: item1
   Keys.onPressed: {
      // Pre-process...
      item2.Keys.pressed(event);
      // Post-process based on results of event passing...
   }
}

Item {
   id: item2
   Keys.onPressed: {
      // Some other stuff happens here
   }
}
于 2014-11-14T10:53:50.127 回答
2

One method to move events between Items is to create a C++ plugin and use QCoreApplication::sendEvent. Unfortunately, Qt doesn't map directly from the QML KeyEvent and the C++ QKeyEvent, so the interface to the plugin will need to expose the internals of the event:

bool EventRelay::relayKeyPressEvent(
   int key,
   Qt::KeyboardModifiers modifiers,
   const QString& text,
   bool autoRepeat,
   ushort count) const
{
   QKeyEvent event(QKeyEvent::KeyPress, key, modifiers, text, autoRepeat, count);
   return relayEventToObject(&event, mpTargetObject);
}

To use it:

EventRelay { id: relay }

Item {
   id: item1
   Keys.onPressed: {
      // Pre-process...

      relay.relayEventToObject(event, item2);

      // Post-process...
   }
}

TextInput {
   id: item2
}
于 2014-11-13T17:15:06.400 回答
1

我认为您可以在此处找到的“信号到信号连接”部分可能会很有用。基本上,每个信号都有一个connect可以用来创建信号链的方法。

如果您有兴趣转发关键事件(如您的示例),请考虑以下forwardTo属性:

此属性提供了一种将来自输入法的按键、按键释放和键盘输入转发到其他项目的方法。当您希望一个项目处理某些键(例如向上和向下箭头键)而另一个项目处理其他键(例如向左和向右箭头键)时,这可能很有用。一旦已转发键的项目接受该事件,它将不再转发到列表中稍后的项目。

该文档提供了一个很好的简单示例。

于 2014-11-13T17:10:43.483 回答