2

I'm creating a series of buttons using a for loop and I want them all to trigger the same method when clicked, but in the method I need to check which button was clicked. With the code below, and when clicking any button, the method always believes that "Button 4" was clicked, even if another button was clicked.

How can I change my code to get the "printer" method to recognize the individual buttons?

import sys
from PySide import QtGui, QtCore


class MyTest( QtGui.QWidget ):
    def __init__(self):
        super(MyTest, self).__init__()
        self.initUI()


    def initUI(self):  
        hbox = QtGui.QHBoxLayout()
        self.setLayout(hbox)
        self.setWindowTitle('Buttons test')
        self.show()

        buttons = {}
        for n in range(0, 5):
            buttons[n] = QtGui.QPushButton()
            buttons[n].setText('Button ' + str(n))
            hbox.addWidget(buttons[n])
            buttons[n].released.connect( lambda : self.printer( object_name=buttons[n].text() ) )


    def printer(self, object_name):
        print object_name


def main():
    app = QtGui.QApplication(sys.argv)
    ex = MyTest()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

I'm doing this with PySide, but I assume it would be the same solution for PyQt.

fredrik
  • 9,631
  • 16
  • 72
  • 132

1 Answers1

2

You don't need to use lambda for this. Simply connect the event then use sender() to get the object that called it within the function.

Connect button event:

buttons[n].released.connect(self.printer)

Printer function:

def printer(self):
    print self.sender().text() 

I tried this on PyQt but I don't currently have a PySide installation to test this on but it should work.

Shadow9043
  • 2,140
  • 1
  • 15
  • 13