我正在使用 Python 3.3 和 PyQt 4.10.1。下图来自PyQt book .
假设有 5 个按钮,如下所示。单击每个按钮时,他们将更改标签的文本以及包含其按钮编号的上下文。例如,当用户单击标题为“四”的按钮时,它会将标签更改为您单击了按钮“四”
不是为每个按钮创建一个信号槽,而是创建一个接受参数的通用方法,并使用 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()
方法有效?
最佳答案
partial
返回参数被替换的函数 anyButton
。
self.anyButton("One")
为您提供函数返回的值。
关于python - 连接信号时为什么要使用不同的方法而不是直接的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16998766/