0

Based on this answer, I try to get the name of the QPushButton when the button is clicked. I don't have an error but when I try to print the name, I get nothing.

Here my code:

def add_btn(self):
    for i in range(0, 10):
        for j in range(1):
            self.btn = QPushButton("btn_%i" % i)
            self.btn_area.addWidget(self.btn,i,j)
            self.btn.clicked.connect(lambda: self.dostuff(self.btn))

def dostuff(self, btn):
    self.btn = btn
    name_btn_clicked = self.btn.objectName()
    print("Name: ",name_btn_clicked)

The result (empty string):

Name:
H. Dave
  • 549
  • 3
  • 9
  • 26
  • If you have not added an objectName as you expect to recover it? change `self.btn` to `btn` and add: `btn.setObjectName("btn_%i" % i)` – eyllanesc Aug 21 '18 at 23:26
  • @eyllanesc: Thank you for your answer. Now I got the name of the object but whatever the button clicked, it only returns the name of the last button added. – H. Dave Aug 21 '18 at 23:37
  • Have you read the other link that marks you as a duplicate? https://stackoverflow.com/questions/35819538/using-lambda-expression-to-connect-slots-in-pyqt – eyllanesc Aug 21 '18 at 23:38
  • Yes, and I managed to pass the number associated to the pushbutton (i.e. 0 if I click the first button, 1 for the second button,etc.) but I can't figure out how to use that information to get for example `self.btn_0.setText('something')` – H. Dave Aug 22 '18 at 00:24
  • 1
    You have not understood the solution and have only applied, the answers do not apply to apply, in your case you just have to replace: `btn.clicked.connect(lambda checked, btn=btn: self.dostuff(btn))` – eyllanesc Aug 22 '18 at 00:26
  • Thank you. It works but you are right, I need to investigate further with the concept linked to `lambda` and how to use it properly. – H. Dave Aug 22 '18 at 00:38

0 Answers0