Sahil Gupta Sahil Gupta - 3 months ago 14
Python Question

Pass the QAction object which calls triggered.connect() as a parameter in the function that is triggered after i click on QAction

i am creating list of QAction objects using for loop like this:

class some_class:
self.tabs = []

for self.i in range(0,10):
self.tabs[self.i] = QtGui.QAction("New", self)
self.tabs[self.i].triggered.connect(self.some_function)

def some_function(self):
print self.i


whenever i click on any of the tabs created, it triggers only tabs[9] and print "9" only.

So how to pass the QAction object itself in the some_function which triggered some_function()

Answer

Cache the index as a default argument:

for index in range(0, 10):
    action = QtGui.QAction("New", self)
    action.triggered.connect(
        lambda checked, index=index: self.some_function(index))
    self.tabs.append(action)

...

def some_function(self, index):
    action = self.tabs[index]
    print(action.text())