Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Set the setDefault(true) key to spacebar - eventFilter()?



  • Hi,

    i need to change the key which is set for the setDefault(true) behaviour of an QPushButton. On my system (ubuntu Linux 19.04) with Qt 5.12.3 it is the ENTER key. But i need to have the SPACEBAR for it. I cannot find a function like setDefaultKey(Qt::Key_Space) so i guessed i have to do it via eventFilter().

    Unfortunately it seems to be impossible to fetch a Qt::Key_Space keypress Event e.g. if a spinbox in the same dialog have focus.

    This is the dialog:
    alt text

    This is the eventFilter() code:

    bool MetronomDialogImpl::eventFilter(QObject *object, QEvent *event)
    {
        qDebug() << event->type();
        if (event->type() == QEvent::KeyPress ) {
            QKeyEvent *ke = static_cast<QKeyEvent *>(event);
            qDebug() << ke->key();
            if (ke->key() == Qt::Key_Space) {
                qDebug() << "Space";
                pushButton_play->click();
                return true;
             }
         }
    
        return QDialog::eventFilter(object, event);
    }
    

    If any childwidget like QSlider of QSpinbox have focus i currently cannot grab the keypress event.

    What can i do to fetch the spacebar press event globally for the QDialog?



  • Hi @fhammer,
    You can try QPushButton::setShortcut or QAction:

        pushButton_play->setShortcut(QKeySequence(Qt::Key_Space));
    

    or

        QAction *playAction = new QAction(this);
        playAction->setShortcut(QKeySequence(Qt::Key_Space));
        addAction(playAction);
    
        connect(playAction, &QAction::triggered, pushButton_play, &QPushButton::click);
    

    But you may still have a problem when one of the QSpinboxs is focused, because they handle the space key press first (and it's a very normal behavior, think of it as a lineedit !). So I recommend, if you want a one key shortcut, using a different key (e.g Qt::Key_F5) , if you insist to be the space key, then try combining it with a modifier (Qt::SHIFT, Qt::CTRL, Qt::ALT, or Qt::META).



  • Hi SamurayH,

    thanks for the hint with setShortcut(QKeySequence(Qt::Key_Space));
    That helped a lot. Concerning the spinboxes you also were right. I need to build a MyMetronomeSpinbox class give it the pushButton_play object and filter the spacebar there via:

    void MyMetronomeSpinBox::keyPressEvent(QKeyEvent *event) {
        if (event->key() == Qt::Key_Space) {
            myPlayButton->click();
            QSpinBox::keyPressEvent(event);
        } else {
            QSpinBox::keyPressEvent(event);
        }
    }
    

    Now it works like a charme ;-)
    Thanks you!


Log in to reply