Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use KeyPressEvent or QAction to implement keypresses?

In Qt, either implementing keyPressEvent or creating a QAction and assigning it a key combination allow me to act based on the keyboard.

Which of these methods is generally preferred?

like image 930
Patrick Avatar asked Dec 06 '25 08:12

Patrick


2 Answers

You should use QAction whenever the same event that is triggered by the key sequence you want may be triggered through other ways like from a menu, toolbar or other buttons. This way you can use the same action on several widgets that should do the same trick.

Excerpt from QAction doc:

The QAction class provides an abstract user interface action that can be inserted into widgets.

In applications many common commands can be invoked via menus, toolbar buttons, and keyboard shortcuts. Since the user expects each command to be performed in the same way, regardless of the user interface used, it is useful to represent each command as an action.

like image 56
Shinnok Avatar answered Dec 08 '25 03:12

Shinnok


I'd prefer to overwrite the keyPressEvent. I don't like the idea of a QAction "lying around somewhere". Just overwrite the keyPressedEvent. I usually do it with a switch-case in which I check the pressed key. Just don't forget to call the keyPressEvent of the base class if you don't want to disable the standard behaviour of a key. Additionally you can check if a "modifier" is pressed while a keyPressEvent occurs. (e.g. Shift or Ctrl). IMHO for general purposes overwriting the keyPressEvent is better than creating invisible, secret actions, unless you want your application to contain all those actions visible for the user.

void my_widget::keyPressEvent( QKeyEvent* p_event )
{
    bool ctrl_pressed = false;

    if( p_event->modifiers() == Qt::ControlModifier )
    {
        ctrl_pressed = true;
    }

    switch( p_event->key() )
    {
    case Qt::Key_F:
        focus_view();
        break;

    case Qt::Key_I:
        if( ctrl_pressed )
        {
            toggle_interface();
        }
        else
        {
            QWidget::keyPressEvent( p_event );
        }
        break;

    case Qt::Key_Return:    // return key
    case Qt::Key_Enter:     // numpad enter key
        update_something();
        break;

    default:
        QSpinBox::keyPressEvent( p_event );
    }
}
like image 36
Exa Avatar answered Dec 08 '25 03:12

Exa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!