user6565581
user6565581

Reputation:

How in PyQt connect button to a function with a specific parameter?

The idea is that when button is pressed, I need to start a function with the parameter that is that button's text.

# -*- coding: utf-8 -*-
import ftplib 
from PyQt4 import QtGui, QtCore
import sys
import socket

app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()

List = ['one', 'two', 'free']

layer = QtGui.QVBoxLayout()
window.setLayout(layer)

def btn_clicked(btn):
    print 'button with text <%s> clicked' %(btn)

for i in List:
    button = QtGui.QPushButton(i)
    layer.addWidget(button)
    QtCore.QObject.connect(button, QtCore.SIGNAL('clicked()'),  btn_clicked(button.text())) # <--- the problem is here 

window.show()
sys.exit(app.exec_())

Upvotes: 1

Views: 3125

Answers (2)

Achayan
Achayan

Reputation: 5885

I prefer partial over lambda and I think that will be easy to use.

from functools import partial
...
for i in List:
    button = QtGui.QPushButton(i)
    layer.addWidget(button)
    button.clicked.connect(partial(btn_clicked, str(button.text())))

Upvotes: 0

ekhumoro
ekhumoro

Reputation: 120568

Connect the buttons like this:

for i in List:
    button = QtGui.QPushButton(i)
    layer.addWidget(button)
    button.clicked.connect(lambda arg, text=i: myfunc(text))

Upvotes: 1

Related Questions