2

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...

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Derar
  • 97
  • 14

2 Answers2

2

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 1
    @Derar Check my current answer, you should not use list to store strings and buttons. also list is a reserved word – eyllanesc Dec 12 '17 at 14:31
  • TypeError: () missing 1 required positional argument: 'checked' , also without checked, it just gave false value – greendino Oct 27 '21 at 19:45
  • 1
    @FoggyMindedGreenhorn Sure you are using PySide2, try `btn.clicked.connect(lambda *args, text=s : getbuttontext(text))` OR `btn.clicked[bool].connect(lambda checked, text=s : getbuttontext(text))`, See https://stackoverflow.com/questions/65185005/error-lambda-missing-1-required-positional-argument-when-using-with-qpushbutton/65185119#65185119 – eyllanesc Oct 27 '21 at 19:53
  • thanks, it works! yes, I use PySide2, sorry, I thought they have the same behavior on this matter, didn't think that far tbh @eyllanesc – greendino Oct 27 '21 at 19:59
  • @eyllanesc, why do you need enumerate? – Scott Mar 17 '22 at 06:45
1

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()))
Omar rai
  • 29
  • 5