1

I want to create multiple buttons by a for loop. Pressing on the buttons call same function but transfer a different parameters.

def someFunction(self):
      buttons = [None] * 8
      for i in range(8):
            buttons[i] = QPushButton(self)
            buttons[i].clicked.connect(self.function(i))

def function(self, i):
        print(i)

I expect the output of buttons[i] to be i but the output always 7

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Guy
  • 21
  • 1
  • 3

1 Answers1

1

Try it:

from PyQt5.QtWidgets import *

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.layout = QVBoxLayout(self) 
        self.someFunction()

    def someFunction(self):
#        buttons = [None] * 8
        for i in range(8):
            button = QPushButton("Button {}".format(i), self)
            button.clicked.connect(lambda ch, i=i: self.function(i))      # < ---
            self.layout.addWidget(button)

    def function(self, i):
        print(i)

if __name__ == '__main__':        
    app = QApplication([])
    mainapp = MainWindow()
    mainapp.show()
    app.exec_()

enter image description here

S. Nick
  • 12,879
  • 8
  • 25
  • 33