QAction shortcut doesnt always work

MBU picture MBU · Feb 16, 2012 · Viewed 11.3k times · Source

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...

Answer

David Faure picture David Faure · Feb 17, 2012

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.