PDA

View Full Version : Keyboard shortcut event not received



D Cell
14th December 2010, 22:39
I have a custom subclass of QGraphicsScene that executes a context menu. The context menu works, but I can't seem to receive any keyboard shortcuts for it. Here's a simplified example of my code.

MyScene::MyScene(QObject *parent) :
QGraphicsScene(parent)
{
m_contextMenu = new QMenu();
QAction *action = m_contextMenu->addAction(tr("Duplicate"), this);
action->setShortcut(tr("Ctrl+D"));
connect(action, SIGNAL(triggered(), this, SLOT(duplicateSelectedItem()));
}

The duplicateSelectedItem() slot never gets called. How do I ensure the keyboard shortcut events get propagated to this action? I got the impression this would happen when the QGraphicsView gets focus, but clearly it can't figure out that the actions I've created in the scene are in focus. If it makes any difference, I'm testing this on OSX. Thanks.

wysota
15th December 2010, 00:19
Look that the menu is in no way tied to the graphics view so pressing keys when the view has focus will not lead towards the appropriate actions. In your situation it is best to build the context menu differently. Instead of creating a custom QMenu object and adding actions to it, use the Qt::ActionsContextMenu context menu policy and use addAction() to add the actions directly to the view widget. Then all the shortcuts will be active the whole time the widget has focus and in addition if you right click the view, a context menu made of actions you added to the widget will be created for you. If you don't really want the context menu, just the shortcuts then don't set the context menu policy to ActionsContextMenu and only add the actions to the widget.

D Cell
15th December 2010, 09:45
Thanks. I got your suggestion to work. I also had to set

action->setShortcutContext(Qt::WidgetShortcut);since I have more than one instance of the view. Otherwise I got an error about an ambiguous shortcut.

For future reference, is it not possible then to receive keyboard shortcuts on anything except widgets? Is calling QWidget::addAction(...) the only way to setup the keyboard shortcuts to propagate correctly?

wysota
15th December 2010, 09:52
For future reference, is it not possible then to receive keyboard shortcuts on anything except widgets? Is calling QWidget::addAction(...) the only way to setup the keyboard shortcuts to propagate correctly?
The action has to be tied to something that is currently visible. It is possible to hack a global shortcut support by catching shortcuts in the application object and triggering appropriate actions manually but it's not available out of the box.