[PyQt] Keyboard shortcuts not working

Mark Summerfield mark at qtrac.eu
Fri Apr 11 07:45:46 BST 2008


On 2008-04-10, 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
> work:

One thing about QAction's: they only come into effect when the action
has been added to a menu or a toolbar or both.

If you want a shortcut with no menu or toolbar option you might try
something like this (untested, just off the top of my head):

    QShortcut(QKeySequence("Ctrl+D"), self, self.down)

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



-- 
Mark Summerfield, Qtrac Ltd., www.qtrac.eu



More information about the PyQt mailing list