PDA

View Full Version : Can't get keyboard shortcuts to work



aquavitae
19th January 2012, 10:08
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?


class Widget(QtGui.QWidget):
def __init__(self):
super().__init__()
self.act = QtGui.QAction('test', self)
self.act.setShortcut(QtGui.QKeySequence(QtGui.QKey Sequence.Copy))
self.act.setShortcutContext(Qt.WidgetWithChildrenS hortcut)
self.addAction(self.act)
self.act.triggered.connect(self.slot)

def slot(self):
print('triggered')

aquavitae
21st January 2012, 07:11
Can anyone help?

Lykurg
21st January 2012, 08:15
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.

aquavitae
21st January 2012, 12:06
Thanks for the reply, but that's not it. I tried it with other widgets and explicitly setting focus (and using hasFocus() to confirm).

blueSpirit
21st January 2012, 16:37
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):

QAction* pAction = new QAction( "text4ESC", this );
// 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 );

aquavitae
22nd January 2012, 20:07
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!