¿Puedo utilizar Pyside clicked.connect para conectar una función que tiene un parámetro?

I want to have a function in main class which has parameters not only self.

class Ui_Form(object):
    def clearTextEdit(self, x):
            self.plainTextEdit.setPlainText(" ")
            print("Script in Textbox is Cleaned!",)

x will be my additional parameter and I want clearTextEdit to be called by click.

self.pushButton_3.clicked.connect(self.clearTextEdit(x))

it does not allow me to write x as parameter in clicked. Can you help me!

preguntado el 24 de mayo de 14 a las 16:05

1 Respuestas

Solución

This is a perfect place to use a lambda:

self.pushButton_3.clicked.connect(lambda: self.clearTextEdit(x))

Recuerda, connect expects a function of no arguments, so we have to wrap up the function call in another function.

Explicación

Your original statement

self.pushButton_3.clicked.connect(self.clearTextEdit(x))  # Incorrect

Fue en realidad llamar self.clearTextEdit(x) when you made the call to connect, and then you got an error because clearTextEdit doesn't return a function of no arguments, which is what connect querido.

Lambda?

Instead, by passing lambda: self.clearTextEdit(x), damos connect a function of no arguments, which when called, will call self.clearTextEdit(x). The code above is equivalent to

def callback():
    return self.clearTextEdit(x)
self.pushButton_3.clicked.connect(callback)

But with a lambda, we don't have to name "callback", we just pass it in directly.

If you want to know more about lambda functions, you can check out esta pregunta para más detalles.


On an unrelated note, I notice that you don't use x en cualquier lugar de clearTextEdit. Is it necessary for clearTextEdit to take an argument in the first place?

contestado el 23 de mayo de 17 a las 13:05

thank you Istvan, you made my code more readable and less complex:) Let me ask you one more questıon: what if I have another function and I want to add that function as a parameter in my original function. such as: def myFunct(): return x and self.pushButton_3.clicked.connect(lambda:self.clearTextEdit(clearTextEdit(myFunct))) is it allowed in pyside?? Thanks in advance - mesutali

By the way, I just needed an example so that I could do in my project. writing whole script would be garbage I guess. I would thank u a lot. my duty is done :) - mesutali

@mesutali Yes, that can be done in the same way as passing any other argument. Your example would look something like self.pushButton_3.clicked.connect(lambda: self.clearTextEdit(myFunct)) (you had an extra clearTextEdit) - Lirio Chung

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.