override在qt_为什么QEvent :: ShortcutOverride事件发生?

当一个QMainWindow安装了事件过滤器,并在打开并关闭一个QDialog后,键盘箭头键不再响应,因为主窗口只接收到ShortcutOverride事件而非KeyPress事件。解决方法是在QMainWindow中使用setFocus()来恢复焦点。ShortcutOverride事件在每次按键时都会触发,因为它用于在不确定按键是否会作为快捷键时提供取消快捷键处理的机会。
摘要由CSDN通过智能技术生成

I have a QMainWindow with an event filter installed.

After I open and close a QDialog the keyboard arrow keys don't respond since QMainWindow receives only ShortcutOverride events instead of KeyPress events.

When I changed the QMainWindow's event filter to handle ShortcutOverride events I got a strange behavior since in my program each key press event is preceded by two shortcut override events (why??).

This doesn't work - events are handled more than once:

bool eventFilter(QObject *, QEvent *event) {

if(type == QEvent::KeyPress || type == QEvent::ShortcutOverride) {

QKeyEvent *keyEvent = static_cast(event);

switch(keyEvent->key()) {

case Qt::Key_Up:

case Qt::Key_Down:

case Qt::Key_Left:

case Qt::Key_Right:

// Do something here

break;

default:

break;

}

return true;

}

return false;

}

Why is this happening? Where do those ShortcutOverride events come from?

Edit:

As it turns out, QMainwindow loses focus when the QDialog is opened and never gains it back when the QDialog is closed.

I used setFocus() in the eventFilter of QMainwindow and it seems to do the trick.

解决方案

Lost focus is exactly the reason for not getting any keyboard events after a dialog opens up. The solution you suggested is probably the best fix for this issue.

As for ShortcutOverride events, they come for every keypress because any key or combination of keys can be registered as a shortcut. This event gives you an option to cancel shortcut handling, if needed. It has to be processed at the earliest possible moment when the engine doesn't know yet if the pressed key is going to be used as a shortcut or not. Thus the event is generated for all key presses "just in case". You may read more here: https://wiki.qt.io/ShortcutOverride

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值