5

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!

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
mesutali
  • 1,655
  • 2
  • 12
  • 9

1 Answers1

17

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?

Community
  • 1
  • 1
Lily Chung
  • 2,919
  • 1
  • 25
  • 42
  • 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 May 26 '14 at 07:27
  • 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 May 26 '14 at 14:40
  • 1
    @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`) – Lily Chung May 26 '14 at 15:01