0

I know lambda is use when calling anonymous functions like:

double = lambda x: x * 2

However, I don't quite understand why do I have to use lambda when binding a function to a QAction object in the following scenario:

class UiMainWindow(object):
    def setupUi(self, mainwindows):

        mainwindows.setObjectName("MainWindow")
       
        self.menubar = QtWidgets.QMenuBar(mainwindows)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 484, 21))
        self.menubar.setObjectName("menubar")

        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")

        mainwindows.setMenuBar(self.menubar)

        self.actionOpen = QtWidgets.QAction(mainwindows)
        self.actionOpen.triggered.connect(lambda:self.test())

        self.menuFile.addAction(self.actionOpen)

        self.menubar.addAction(self.menuFile.menuAction())
        self.retranslateUi(mainwindows)
        QtCore.QMetaObject.connectSlotsByName(mainwindows)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.actionOpen.setText(_translate("MainWindow", "Open..."))


    def test(self):
        win32api.MessageBox(0, 'hello', 'title')
quamrana
  • 37,849
  • 12
  • 53
  • 71
HussainBiedouh
  • 99
  • 2
  • 11
  • What makes you think that you have to use a `lambda`? – quamrana Jun 21 '20 at 09:40
  • Without lambda the function fires automatically as soon as the code runs, without even clicking the binded item. – HussainBiedouh Jun 21 '20 at 09:52
  • Well, what happens in the following two lines of your code? Aren't they also trying to link an event from QT to some of your methods? – quamrana Jun 21 '20 at 09:55
  • No. I know how to make things work but what i mean is that i don't understand why do i have to use lambda to make things work in this situation as the function is explicitly defined and lambda documentations says it is for anonymous functions. – HussainBiedouh Jun 21 '20 at 10:13

0 Answers0