tags:

views:

511

answers:

2

I need to be able to know what item I've clicked in a dynamically generated menu system. I only want to know what I've clicked on, even if it's simply a string representation.

def populateShotInfoMenus(self):
    self.menuFilms = QMenu()
    films = self.getList()

    for film in films:
        menuItem_Film = self.menuFilms.addAction(film)
        self.connect(menuItem_Film, SIGNAL('triggered()'), self.onFilmSet)
        self.menuFilms.addAction(menuItem_Film)

def onFilmRightClick(self, value):
    self.menuFilms.exec_(self.group1_inputFilm.mapToGlobal(value))

def onFilmSet(self, value):
    print 'Menu Clicked ', value
+3  A: 

Instead of using onFilmSet directly as the receiver of your connection, use a lambda function so you can pass additional parameters:

receiver = lambda film=film: self.onFilmSet(self, film)
self.connect(menuItem_Film, SIGNAL('triggered()'), receiver)
Aaron Digulla
exactly what i was looking for, ahhh sweet lambda!
mleep
+1  A: 

Take a look at the Qt's property system. You can dynamically add a property containing a string or anything you desire, which defines the action. Then you can use sender() method in the slot to obtain the QObject calling the slot. Then, query the property you set and do whatever you want accordingly.

But, this is not the best method to do this. Using sender() is not advised because it violates the object oriented principle of modularity.

The best method would be using QSignalMapper class. This class maps signals from different objects to the same slot with different arguments.

I haven't used PyQt therefore i cannot give you exact syntax or an example, but it shouldn't be hard to find with a little research.

erelender
I agree that this seems like the place to use a signal mapper.
Caleb Huitt - cjhuitt