Intercepting Tab key press to manage focus switching manually

被刻印的时光 ゝ 提交于 2020-01-20 04:18:55

问题


I want to intercept Tab key press in my main window to prevent Qt from switching focus. Here's what I've tried so far:

bool CMainWindow::event(QEvent * e)
{
    if (e && e->type() == QEvent::KeyPress)
    {
        QKeyEvent * keyEvent = dynamic_cast<QKeyEvent*>(e);
        if (keyEvent && keyEvent->key() == Qt::Key_Tab)
            return true;
    }
    return QMainWindow::event(e);
}

This doesn't work, event isn't called when I press Tab. How to achieve what I want?


回答1:


The most elegant way I found to avoid focus change is to reimplement in your class derived from QWidget the method bool focusNextPrevChild(bool next) and simply return FALSE. In case you want to allow it, return TRUE.

Like other keys you get now also the key Qt::Key_Tab in keyPressEvent(QKeyEvent* event)




回答2:


Reimplementing virtual bool QApplication::notify(QObject * receiver, QEvent * e) and pasting the code from my question there works.




回答3:


You can achieve by using setFocusPolicy( Qt::NoFocus) property of QWidget. You can set Focus policy on widget which doesn't require tab focus. I think the reason why event handler is not calling, because Tab is managed by Qt framework internally. Please see QWidget::setTabOrder API, which is static.




回答4:


You'll need to install an event filter on your main window in order to receive the events. You can use installEventFilter method for this. Another option is to override the keyPressEvent method to handle the key presses.



来源:https://stackoverflow.com/questions/18160051/intercepting-tab-key-press-to-manage-focus-switching-manually

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!