简体   繁体   English

在所有情况下将keyPressEvent分配给顶级QWidget

[英]Propogate keyPressEvent to top level QWidget in all cases

I am working on an application where I want a certain keystroke (lets say the Tab key for this example) to always be handled by a particular QWidget . 我正在开发一个应用程序,在该应用程序中,总是希望通过特定的QWidget处理特定的击键(在本例中为Tab键)。 Lets say I have a hierarchy like this: 可以说我有一个这样的层次结构:

QWidget (top level window)
  ¬ QWidget X (the widget that should handle all Tab presses)
  ¬ QWidget (inner widget)
    ¬ ...
      ¬ ...
        ¬ QLineEdit (very deep into the hierarchy)

The QLineEdit currently has focus, and you can enter text into it. QLineEdit当前具有焦点,您可以在其中输入文本。 When the user presses Tab , I want it to be handled by QWidget X (near the very top of the hierarchy), to perform some action. 当用户按下Tab ,我希望它由QWidget X (在层次结构的最顶部)处理,以执行一些操作。 How can I make sure a particular QWidget intercepts every single Tab key press if anything in the current window has focus? 如果当前窗口中有焦点,我如何确保特定的QWidget会拦截每一次Tab键按下?

Installing an event filter on every child QWidget is impractical, as the application is vast and liable to change. 在每个子QWidget上安装事件过滤器都是不切实际的,因为该应用程序庞大且易于更改。

Instead of having your QWidget override keyPressEvent , you can use QShortcut : 您可以使用QShortcut代替QWidget覆盖keyPressEvent

QShortcut *Shortcut = new QShortcut(this);
Shortcut->setKey(Qt::Key_Tab);
connect(Shortcut, SIGNAL(activated()), this, SLOT(TabPressed()));

And then in the TabPressed() slot, perform the action. 然后在TabPressed()插槽中,执行操作。 This works regardless of any another QWidget having focus. 无论其他任何QWidget具有焦点,此方法都有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM