Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting Tab key press to manage focus switching manually

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?

like image 373
Violet Giraffe Avatar asked Aug 10 '13 08:08

Violet Giraffe


3 Answers

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

like image 66
Violet Giraffe Avatar answered Oct 19 '22 03:10

Violet Giraffe


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)

like image 37
pi3 Avatar answered Oct 19 '22 03:10

pi3


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.

like image 45
Ashif Avatar answered Oct 19 '22 03:10

Ashif