0
def initUI(self):
    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)
    x=1
    for index, row in self.database.iterrows():
        button=QPushButton(row['Usernames'],self)
        button.move(10,40*x)
        print(row['Usernames'])
        button.clicked.connect(lambda:self.copy(row['Usernames']))
        button=QPushButton('password',self)
        button.move(200,40*x)
        button.clicked.connect(lambda:self.fetch_password(row['Usernames']))
        x+=1

In the above code I try to create a button for each row of dataframe. The problem is that each button click is doing what the click for last row 's button. I guess same instance of QPushButton gets linked to most recent row. Buttons are created with proper name but events occur as per last row only. How do I get around this problem?

  • Does this answer your question? [Creating lambda inside a loop](https://stackoverflow.com/questions/7546285/creating-lambda-inside-a-loop) – mugiseyebrows May 01 '21 at 19:12
  • @musicamante Both the above links provide same solution i.e. passing an extra argument with default values. I have done same with x with no different result. Do I need to change closure's returning value or extra argument(x)? – Harsh Prakash Agarwal May 01 '21 at 20:24
  • 1
    @HarshPrakashAgarwal I don't know what that `database` is, but you could pass a reference to the row in the lambda: `lambda _, row=row: self.copy(row['Usernames'])`. Note that the first argument (I used an underscore) is mandatory, as `clicked` always sends the checked state argument. Also, `self.width()` and `self.height()` are properties of QWidget and they should not be overwritten with custom values. Then, fixed geometries are discouraged, use [layout managers](https://doc.qt.io/qt-5/layout.html) instead. – musicamante May 01 '21 at 20:38
  • @musicamante Yes, passing row as argument along with underscore works. Could you point to why row works and x does not. database is a pandas dataframe with two columns. – Harsh Prakash Agarwal May 01 '21 at 20:47
  • @HarshPrakashAgarwal how did you use that "x" argument? – musicamante May 01 '21 at 23:23
  • @musicamante lambda _, x=x: self.copy(row['Usernames']) – Harsh Prakash Agarwal May 02 '21 at 05:04
  • And how would that be useful in any way?!? Don't just copy/paste code, *understand* what it does! You're not using the x in that function, you're just adding it to the arguments, what makes you think it would change anything? – musicamante May 02 '21 at 13:11

0 Answers0