mardi 28 juin 2016

How do I avoid this case of Late Binding when connecting multiple button signals in PyQt4?

I want to connect multiple buttons to the same method but each with a different argument to that method. In this case the argument is the index of the button in a list of all buttons.

from PyQt4 import QtGui, QtCore
import sys
class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        #We declare each button
        self.pushButton_01 = QtGui.QPushButton(self)
        self.pushButton_02 = QtGui.QPushButton(self)
        self.pushButton_03 = QtGui.QPushButton(self)
        self.pushButton_04 = QtGui.QPushButton(self)
        self.pushButton_05 = QtGui.QPushButton(self)
        self.pushButton_06 = QtGui.QPushButton(self)
        #We combine the buttons in a list
        list_of_buttons = [self.pushButton_01,self.pushButton_02,self.pushButton_03,self.pushButton_04,self.pushButton_05,self.pushButton_06]
        layout = QtGui.QVBoxLayout(self)
        #We add each button to the layout
        for button in list_of_buttons:
            layout.addWidget(button)
        #This is supposed to connect each button in a way that in prints out its index in the list above
        for button in list_of_buttons:
            button.clicked.connect(lambda: self.handle(list_of_buttons.index(button)))


    def handle(self,x):
        print x

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

I expect the output to be an integer from 0 to 5 when I click each button but instead each button outputs the last index 5.

Edit

I tried the following

button.clicked.connect(lambda button = button: self.handle(list_of_buttons.index(button)))

But whenever I click a button I get

ValueError: False is not in list

So I tried changing the second loop to

for i in range(0,6):
        list_of_buttons[i].clicked.connect(lambda i=i: self.handle(i))

But even though the previous error no longer appears, it outputs False Whenever I click a button.

Aucun commentaire:

Enregistrer un commentaire