我正在使用Python 3.3和PyQt 4.10.1。下图来自PyQt book。
假设有5个按钮,如下所示。单击每个时,它们将更改标签的文本,其中包含其按钮编号。例如,当用户点击标题为“四”的按钮时,它会将标签更改为You clicked button 'Four'
不是为每个按钮创建一个信号槽,而是创建一个接受参数并使用partial()
方法的通用方法:
...
self.label = QLabel("Click on a button.")
self.button1 = QPushButton("One")
...
self.button5 = QPushButton("Five")
self.connect(self.button1, SIGNAL("clicked()")
, partial(self.anyButton, "One"))
...
self.connect(self.button5, SIGNAL("clicked()")
, partial(self.anyButton, "Five"))
...
def anyButton(self, buttonNumber):
self.label.setText("You clicked button '%s'" % buttonNumber)
每当我想将partial(self.anyButton, "One")
更改为self.anyButton("One")
时,我都会收到如下错误。
Traceback (most recent call last):
File "C:\Users\abdullah\Desktop\test.py", line 47, in <module>
form = Form()
File "C:\Users\abdullah\Desktop\test.py", line 20, in __init__
, self.anyButton("One"))
TypeError: arguments did not match any overloaded call:
QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoC
onnection): argument 3 has unexpected type 'NoneType'
QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnecti
on): argument 3 has unexpected type 'NoneType'
QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection
): argument 3 has unexpected type 'NoneType'
这是什么原因?为什么我不能直接调用该函数?另外,为什么partial()
方法有效?
答案 0 :(得分:4)
partial
会返回函数 anyButton
,其中参数被替换。
self.anyButton("One")
为您提供函数返回的值。