[ACCEPTED]-QAction shortcut doesnt always work-action
You need to add the action to a widget, since 6 it's the widget that will be listening for 5 key events. Assuming "this" is a mainwindow, simply 4 do
addAction(deleteAct);
Note that you can add the same action 3 to multiple widgets (that's the whole point 2 of the separated action concept). So it's 1 fine to add it to the mainwindow and to a menu.
Try changing the shortcut context of the action, for example:
deleteAct->setShortcutContext(Qt::ApplicationShortcut);
0
The shortcut works depending on the focus 7 of the application views.
I wanted to have 6 shortcuts working on buttons.
In my application 5 I changed the shortcut context of the action,
added 4 the action to the widget
and finally to 3 the subviews of the application.
Then the 2 necessary signals and slots of widget an 1 action must be connected.
const QAbstractButton*button = dynamic_cast(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()));
}
}
Without seeing the complete code, I'd hazard 4 a guess that somewhere it gets enabled/disabled. Make 3 sure that the shortcut is getting hit in 2 the constructor and not 'disabled' somewhere 1 else because of a setting perhaps.
You can use http://doc.qt.io/qt-5/qaction.html#shortcutVisibleInContextMenu-prop property since QT 5.10 for 1 this:
deleteAct->setShortcutVisibleInContextMenu(true);
You're right, the button is enabled or disabled 4 somewhere else. Unfortunately the action 3 has to be enabled or disabled too. The button 2 owns the action, so this is possible with 1 a little extra code.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.