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.