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

4
  • Please edit your question and add a real question. It's not clear what you are asking... Commented Dec 12, 2017 at 13:10
  • What is your question? What does PHP have to do with your question? Commented Dec 12, 2017 at 13:41
  • Give Me A Function That Print The Text Of Each button inside the loop Commented Dec 12, 2017 at 13:52
  • @Derar What buttons, and what loop? Also show what you have tried to solve it, read the SO rules: How to Ask Commented Dec 12, 2017 at 14:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@Derar Check my current answer, you should not use list to store strings and buttons. also list is a reserved word
TypeError: <lambda>() missing 1 required positional argument: 'checked' , also without checked, it just gave false value
@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 stackoverflow.com/questions/65185005/…
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
@eyllanesc, why do you need enumerate?
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()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.