Reputation: 107
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...
Upvotes: 2
Views: 2027
Reputation: 15
lambda doesnt store the value of button ,instead you can use another method
from functools import partial
for i in range(10):
btn[i].clicked.connect(patial(getbuttontext,btn[i].text()))
Upvotes: 1
Reputation: 243955
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.
Upvotes: 2