[英]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.