Can't get keyboard shortcuts to work
Using PyQt4, I can't get keyboard shortcuts to work with the Qt.WidgetShortcut or Qt.WidgetWithChildrenShortcut contexts (nothing happens when I press the shortcut). I'm pretty sure its something simple I'm missing, but I just can't figure out what. Here is a sample class showing the steps I'm using. Can anyone point out what I'm missing?
Code:
def __init__(self):
super().__init__()
self.
act = QtGui.
QAction('test', self
) self.act.setShortcutContext(Qt.WidgetWithChildrenShortcut)
self.addAction(self.act)
self.act.triggered.connect(self.slot)
def slot(self):
print('triggered')
Re: Can't get keyboard shortcuts to work
Re: Can't get keyboard shortcuts to work
I don't know PyQt but mustn't have the widget the focus that the shortcut is working? And a QWidget normally don't get the focus.
Re: Can't get keyboard shortcuts to work
Thanks for the reply, but that's not it. I tried it with other widgets and explicitly setting focus (and using hasFocus() to confirm).
Re: Can't get keyboard shortcuts to work
I don't know PyQt either, but you can try this (it's C++ but you should be able to read it) - and if it's working you can alter the code line by line (and post a reply, what the reason was):
Code:
// Use a common key
pAction->setShortcut( Qt::Key_Escape );
// If using the Qt::WindowShortcut, you don't have to take care of the focus - just any element of the window must be focused
pAction->setShortcutContext( Qt::WindowShortcut );
connect( pAction, SIGNAL(triggered()),
this, SLOT(SL_DoSomething()) );
addAction( pAction );
setContextMenuPolicy( Qt::ActionsContextMenu );
Re: Can't get keyboard shortcuts to work
Thanks for the example code, but I've just discovered the problem. In my simplified example, the focus was indeed the problem, but in my actual code (which I tested more extensively) I forgot to call widget.addAction()! The way I'm dealing with them is through several modules and a lot of abstraction, and somehow that just slipped through the gap.
Thanks for the help though!