[PyQt] Keyboard shortcuts not working

Ulrich Berning ulrich.berning at denviso.de
Fri Apr 11 08:06:41 BST 2008

Karlo Lozovina wrote:

>Hi guys!
>I'm trying to add keyboard shortcuts to my application, but I'm stuck
>at the beginning. Here is a simple application that I can't get to
>import sys
>from PyQt4.Qt import Qt
>from PyQt4.QtCore import QObject, SIGNAL
>from PyQt4.QtGui import QWidget, QApplication, QMainWindow, QAction,
>QIcon, QKeySequence
>class MainWindow(QMainWindow):
>    def __init__(self, parent):
>        QMainWindow.__init__(self, parent)
>        self.centralwidget = QWidget(self)
>        self.action = QAction(QIcon(), "Down", self)
>        self.action.setShortcut("Ctrl+D")
>        self.action.setShortcutContext(Qt.ApplicationShortcut)
>        QObject.connect(self.action, SIGNAL("triggered()"), self.down)
>    def down(self):
>        print 'DOWN!!!'
>def main():
>    app = QApplication(sys.argv)
>    mw = MainWindow(None)
>    mw.show()
>    sys.exit(app.exec_())
>if __name__ == '__main__':
>    main()
>I've tried using different shortcut context: WindowShortcut,
>WidgetShortcut, ApplicationShortcut, but it still doesn't work.
>Any help greately appreciated.
 From the docs:
"Actions are added to widgets using QWidget::addAction(). Note that an 
action must be added to a widget before it can be used; this is also 
true when the shortcut should be global (i.e., Qt::ApplicationShortcut 
as Qt::ShortcutContext)."

Add the line
and it works.


More information about the PyQt mailing list