Create pyqt5 pushbuttons with click event using lo

2019-08-20 05:38发布

问题:

How Can I Create PushButtons With connect using loop

list = ['apple','orange','banana','carrot']
for i,s in enumerate(list)
    list[i] = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
    list[i].setText(s[0])
    list[i].clicked.connect(lambda:getbuttontext(list[i].text()))

and Here Is getbuttontext function:

def getbuttontext(n):
    print(n)

My Problem Is That When I Click On Any button the Function print "carrot" How To Fix It Please...

回答1:

The solution is simple, define the input parameters of the lambda function:

fruits = ['apple','orange','banana','carrot']
for i,s in enumerate(fruits)
    btn = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
    btn.setText(s[0])
    btn.clicked.connect(lambda checked, text=s : getbuttontext(text))

Note: I put checked because it is the parameter that passes the clicked signal by default.