3

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?

4

2 回答 2

5

functools.partial工作正常。

请参见以下示例:

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_()

如果您仍然收到错误,请将func签名替换为:

def func(self, boolVar, checked):
    print boolVar
于 2013-10-07T10:45:44.910 回答
0

第一个参数是self参数,在你写的时候绑定self.func。第二个参数是False您提供给 的partial,因此当 Qt 使用您的第三个 boolchecked参数调用它时,QPushButton.clicked最终会得到 3 个参数。

写吧:

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

但是,该checked参数是可选的,因此func应定义为:

def func(self, checked=False):
于 2013-10-07T10:39:42.397 回答