user2234234
user2234234

Reputation: 349

arguments for partial function in python

I have a function defined like this:

def func(self, boolVal):

and I want to create a connection between QPushButton() and this function like this:

self.button1.clicked.connect(partial(self.func, False))

when I run this, it tells me that func() takes exactly 2 arguments (3 given) anyone knows why this could happened?

Upvotes: 4

Views: 4477

Answers (2)

falsetru
falsetru

Reputation: 369334

functools.partial works fine.

See following example:

from functools import partial
from PyQt4.QtGui import *

class MyWindow(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.button = QPushButton('test', parent=self)
        self.button.clicked.connect(partial(self.func, False))
        self.button.show()
    def func(self, boolVar):
        print boolVar

app = QApplication([])
win = MyWindow()
win.show()
app.exec_()

If you still get error replace func signature with:

def func(self, boolVar, checked):
    print boolVar

Upvotes: 5

ecatmur
ecatmur

Reputation: 157424

The first argument is the self parameter, which is bound when you write self.func. The second argument is the False you supplied to partial, so when Qt calls it with a third bool checked parameter from QPushButton.clicked you end up with 3 arguments.

Just write:

self.button1.clicked.connect(self.func)

However, the checked parameter is optional so func should be defined as:

def func(self, checked=False):

Upvotes: 0

Related Questions