Search code examples
qtqmlqevent

Pass Events Between QML Objects


I have a situation where I would like to pass a QML event to another QML item in the middle of the initial event handler. e.g.

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
}

What can I do to acheive passEventToObject?

Notes:

  • I don't have access to modify Keys.onPressed inside item2, it's a QML built-in (TextInput).
  • The event passing must happen in the middle of item1.Keys.onPressed

Solution

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