15
votes

I have a Qaction on a menu item for deleting selected items in one of my views. Here is how i create the action:

deleteAct = new QAction( tr("Delete Selected"), this);
deleteAct->setShortcut(QKeySequence::Delete);
connect(deleteAct, SIGNAL(triggered()), this, SLOT(deleteSelected()));  

I setup a keyboard shortcut (Delete Key) which should trigger the delectAct action. It works most of the time but at some points it stops working... Does anyone know why the shortcut would stop working?

Note: the action still works if i trigger it from the menu item. Its just the shortcut that doesn't...

5
I observed the same problem for QtAction instances added with the QtCreator designer; the action is set up as specified, except that shortcuts don't work. Even though it was added with the designer, a manual call to addAction() was still required (as given in the selected answer). - John Doggett

5 Answers

27
votes

You need to add the action to a widget, since it's the widget that will be listening for key events. Assuming "this" is a mainwindow, simply do

addAction(deleteAct);

Note that you can add the same action to multiple widgets (that's the whole point of the separated action concept). So it's fine to add it to the mainwindow and to a menu.

7
votes

Try changing the shortcut context of the action, for example:

deleteAct->setShortcutContext(Qt::ApplicationShortcut);
1
votes

The shortcut works depending on the focus of the application views.
I wanted to have shortcuts working on buttons.
In my application I changed the shortcut context of the action,
added the action to the widget
and finally to the subviews of the application.
Then the necessary signals and slots of widget an action must be connected.

const QAbstractButton*button  = dynamic_cast<QAbstractButton*>(widget);

action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
widget->addAction(action);
ui->textBrowser->addAction(action);
ui->treeSource->addAction(action);

if (button)
{
    if (button->isCheckable())
    {
        action->setCheckable(true);
        if (button->isChecked()) action->setChecked(true);
        connect(action, SIGNAL(triggered(bool)), button, SLOT(setChecked(bool)));
        connect(button, SIGNAL(clicked(bool)), action, SLOT(setChecked(bool)));
    }
    else
    {
        connect(action, SIGNAL(triggered()), button, SLOT(click()));
    }
}
0
votes

Without seeing the complete code, I'd hazard a guess that somewhere it gets enabled/disabled. Make sure that the shortcut is getting hit in the constructor and not 'disabled' somewhere else because of a setting perhaps.

0
votes

You can use http://doc.qt.io/qt-5/qaction.html#shortcutVisibleInContextMenu-prop property since QT 5.10 for this:

deleteAct->setShortcutVisibleInContextMenu(true);