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

click, function, pyside, python, qpushbutton

Solution

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?

Problem

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!

Original source

Related problems