0

I have a main window with a toolbar. I also have a class that handles actions and a class that has all the actions. Here is my code:

import sys
from PyQt4 import QtGui, QtCore


buttonActions = ['actA', 'actB', 'actC']
img = '../../Images/logo.png'
tip = 'home'

class HandlerClass:

    def __init__(self):
        pass

    def loadAction(self, act, win):
        uiAct = ActionsClass()
        func = getattr(uiAct, act)
        func(win)

class ActionsClass:

    def __init__(self):
        pass

    def actA(self, win):
        print 'I am actA'

    def actB(self, win):
        print 'I am actB'

    def actC(self, win):
        print 'I am actC'


class TestWindow(object):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''

        self.app = QtGui.QApplication(sys.argv)
        self.thisWin = QtGui.QMainWindow()

        self.buildButtons()

        self.thisWin.show()
        sys.exit(self.app.exec_())

    def buildButtons(self):

        thisBar = self.thisWin.addToolBar('Basic')        

        for i in range(0, len(buttonActions)):
            toolAct = QtGui.QAction(buttonActions[i], self.thisWin)
            toolAct.triggered.connect(lambda: actHandler.loadAction(buttonActions[i], self.thisWin))
            thisBar.addAction(toolAct)

if __name__ == '__main__':

    actHandler = HandlerClass()

    TestWindow()

As you can see, the problem is that whatever button I press on toolbar, always the last Method from ActionClass is executed. It seems that lambda doesn't works well as it is.

Is there any solution?

ioaniatr
  • 277
  • 4
  • 15
  • Sorry I am not following fully but you might be able to return a [partial](https://www.learnpython.org/en/Partial_functions) – bison Aug 17 '18 at 21:01
  • The Pythonic way to iterate over array items is ```for item in my_array:``` – Ozzy Walsh Aug 17 '18 at 21:02
  • use `toolAct.triggered.connect(lambda i=i: actHandler.loadAction(buttonActions[i], self.thisWin))` – eyllanesc Aug 17 '18 at 21:05
  • If i put `lambda i=i:` then it is always executed the first method. – ioaniatr Aug 17 '18 at 21:16
  • As suggested by @eyllanesc I looked into [here](https://stackoverflow.com/questions/35819538/using-lambda-expression-to-connect-slots-in-pyqt). `state` was missing. If I put down `toolAct.triggered.connect(lambda state, i=i: actHandler.loadAction(buttonActions[i], self.thisWin))`, i don't know what state word really does, but it works. Thanks – ioaniatr Aug 17 '18 at 21:30

0 Answers0