Should I use KeyPressEvent or QAction to implement keystrokes?

In Qt, either the implementation of keyPressEvent or the creation of a QAction and assigning a keyboard shortcut to it allows me to act based on the keyboard.

Which of these methods is usually preferable?

+3
source share
3 answers

You must use QAction whenever the same event that is triggered using a sequence of keys can be triggered using other methods, for example, from a menu, toolbar, or other buttons. That way, you can use the same action for multiple widgets that should do the same trick.

Excerpt from QAction doc :

QAction , .

, . , , , .

+5

keyPressEvent. QAction, - ". keyPressedEvent. , . keyPressEvent , . , , " " keyPressEvent. (, Shift Ctrl). IMHO , keyPressEvent, , , , , , .

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 );
    }
}
+2

, .

, , , , , QAction. , .

(, ), .

+1
source

Source: https://habr.com/ru/post/1787849/


All Articles