tags:

views:

253

answers:

1

Hi everyone,

I'm trying to develop an application with a very modular approach to commands and thought it would be nice, sind I'm using pyqt, to use QAction's to bind shortcuts to the commands.
However, it seems that actions shortcuts only works when the action is visible in a menu or toolbar. Does anyone know a way to get this action to work without it being visible?
Below some example code that shows what I'm trying.
Thanks,

André

from PyQt4 import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class TesteMW(QMainWindow):
    def __init__(self, *args):
        QMainWindow.__init__(self, *args)
        self.create_action()

    def create_action(self):
        self.na = QAction(self)
        self.na.setText('Teste')
        self.na.setShortcut('Ctrl+W')
        self.connect(self.na, SIGNAL('triggered()'), self.action_callback)
        # uncomment the next line for the action to work
        # self.menuBar().addMenu("Teste").addAction(self.na)

    def action_callback(self):
        print 'action called!'


app = QApplication(sys.argv)
mw = TesteMW()
mw.show()

app.exec_()
+4  A: 

You need to add your action to a widget before it will be processed. From the QT documentation for QAction:

Actions are added to widgets using QWidget::addAction() or QGraphicsWidget::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).

This does not mean that they will be visible as a menu item or whatever - just that they will be processes as part of the widgets event loop.

Thomi