Can I utilize Pyside clicked.connect to connect a function which has a parameter
Asked Answered
M

1

6

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!

Marcellusmarcelo answered 24/5, 2014 at 15:20 Comment(0)
J
18

Solution

This is a perfect place to use a lambda:

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

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

Explanation

Your original statement

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

was actually calling 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 wanted.

Lambda?

Instead, by passing lambda: self.clearTextEdit(x), we give 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 this question for more detail.


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

Jacindajacinta answered 24/5, 2014 at 15:37 Comment(3)
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 advanceMarcellusmarcelo
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 :)Marcellusmarcelo
@Marcellusmarcelo 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)Jacindajacinta

© 2022 - 2024 — McMap. All rights reserved.