[PyQt] question about QMenu `triggered' event

Tony Willis twillis449 at gmail.com
Thu Dec 17 06:22:01 GMT 2009


According to the Qt QMenu documentation, a QMenu should be capable 
of generating its own 'triggered' event when any action that 
has been added to the menu generates such an event. However, while 
I can successfully connect 'triggered' events from individual actions 
in a menu to separate callbacks, I can't seem to get a QMenu 
to produce a global 'triggered' event. The appended script 
illustrates the problem. Can someone tell me what I'm doing wrong? 

(I realize that individual callbacks are the proper way to go, but 
I'm porting a large application from Qt3 to Qt4 and don't want to 
have to split up the current code into about a hundred new callbacks!) 

Thanks 

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

class mepViewer(QDialog):

    def __init__(self, parent=None):
        super(mepViewer, self).__init__(parent)
        self.setWindowTitle('mepViewer.py')

        # The status bar gives status and progress.
        # (do this one first, so we can send messages)
        self._statusBar = QStatusBar()
        self._statusBar.showMessage('This is the status bar')

        # The menu-bar:
        self._menuBar = QMenuBar()
        self._menuBar.addMenu(self.make_file_menu())


        # Make the overall vertical layout:
        vlayout = QVBoxLayout()
        vlayout.addWidget(self._menuBar)
        self.setLayout(vlayout)

        return None

    def make_file_menu(self):
        """
        Make the file menu on the main menubar.
        """
        menu = QMenu('&File', self)
# the next line works
        self.connect(menu, SIGNAL('aboutToShow()'), self.about_to_show)

# the following line doesn't seem to work 
        self.connect(menu, SIGNAL('triggered()'), self.was_triggered)

        action = QAction('&New', self)
        action.setToolTip('Open a new .mep file')
        menu.addAction(action)
        self.connect(action, SIGNAL('triggered()'), self.new_mepTable_dialog)

# the following also doesn't seem to do anything
        self.connect(menu, SIGNAL('triggered(QAction)'), self.was_triggered)

        action = QAction('&Simulated', self)
        action.setToolTip('Simulated .mep table')
        menu.addAction(action)
        self.connect(action, SIGNAL('triggered()'), self.read_mepfile)

        return menu

    #----------------------------------------------------------------

    def was_triggered(self):
        print 'caught triggered event'

    def about_to_show(self):
        print 'in about_to_show'

    def new_mepTable_dialog(self):
        print 'in new_mepTable'

    def read_mepfile (self, mepname=None):
        print 'in read_mepfile'

if __name__ == '__main__':

   app = QApplication(sys.argv)
   mv = mepViewer()
   mv.show()
   app.exec_()




More information about the PyQt mailing list