How to pass arguments to functions by the click of button in PyQt? How to pass arguments to functions by the click of button in PyQt? python python

How to pass arguments to functions by the click of button in PyQt?


You can simply write

name = "user"button.clicked.connect(lambda: calluser(name))


I tried an efficient way of doing it and it worked out well for me. You can use the code:

from functools import partialdef calluser(name):    print namedef Qbutton():    button = QtGui.QPushButton("button",widget)    name = "user"    button.setGeometry(100,100, 60, 35)    button.clicked.connect(partial(calluser,name))


Usually GUIs are built using classes. By using bound methods as callbacks (see self.calluser below) you can "pass" information to the callback through self's attributes (e.g. self.name):

For example, using slightly modified code from this tutorial:

import sysimport PyQt4.QtCore as QtCoreimport PyQt4.QtGui as QtGuiclass QButton(QtGui.QWidget):    def __init__(self, parent=None):        QtGui.QWidget.__init__(self, parent)        self.button = QtGui.QPushButton('Button', self)        self.name='me'        self.button.clicked.connect(self.calluser)    def calluser(self):        print(self.name)def demo_QButton():    app = QtGui.QApplication(sys.argv)    tb = QButton()    tb.show()    app.exec_()if __name__=='__main__':    demo_QButton()

Since the callback per se is always called with no additional arguments, when you need to pass distinct additional information to many callbacks, you need to make different callbacks for each button.

Since that can be laborious (if done manually), use a function factory instead. See below for an example. The function factory is a closure. It can be passed additional arguments, which the inner function can access when called:

class ButtonBlock(QtGui.QWidget):    def __init__(self, *args):        super(QtGui.QWidget, self).__init__()        grid = QtGui.QGridLayout()        names = ('One', 'Two', 'Three', 'Four', 'Five',                 'Six', 'Seven', 'Eight', 'Nine', 'Ten')        for i, name in enumerate(names):            button = QtGui.QPushButton(name, self)            button.clicked.connect(self.make_calluser(name))            row, col = divmod(i, 5)            grid.addWidget(button, row, col)        self.setLayout(grid)    def make_calluser(self, name):        def calluser():            print(name)        return calluserapp = QtGui.QApplication(sys.argv)tb = ButtonBlock()tb.show()app.exec_()