QtQuick 按键事件传播

QtQuick key press event propagation

我有 Qt GUI 应用程序。 Main window 包含使用 window 容器放置在其上的 QtQuick 组件:

QQuickView * view = new QQuickView ();
QWidget * container = QWidget::createWindowContainer (view, this);

我想处理整个 window 下的所有按键事件。但是我遇到了一个问题,即当 QtQuick 组件获得焦点时我无法处理关键事件,即使我已经将 window 设置为它的父对象。

documentation 说这种行为是意料之中的:

QWidget *QWidget::createWindowContainer(QWindow *window, QWidget *parent = > Q_NULLPTR, Qt::WindowFlags flags = Qt::WindowFlags())
...
The window container has a number of known limitations:
...
Focus Handling; It is possible to let the window container instance have any focus policy and it will delegate focus to the window via a call to QWindow::requestActivate(). However, returning to the normal focus chain from the QWindow instance will be up to the QWindow instance implementation itself. For instance, when entering a Qt Quick based window with tab focus, it is quite likely that further tab presses will only cycle inside the QML application. Also, whether QWindow::requestActivate() actually gives the window focus, is platform dependent.

我的问题是:即使焦点被QtQuick组件获取,有没有办法在整个window下处理按键事件?

GitLab 提供了最小和完整的示例。

一个可能的(但丑陋的)解决方案是:

  1. 在 QML 中处理按键事件;
  2. 通过信号从 QML 通知 C++ 代码;
  3. 在 C++ 代码中生成按键事件;
  4. 在公共事件过滤器中处理本机事件和重新生成的事件。

示例位于 GitLab