python - 连接信号时为什么要使用不同的方法而不是直接的方法?

标签 python pyqt4

我正在使用 Python 3.3 和 PyQt 4.10.1。下图来自PyQt book .

假设有 5 个按钮,如下所示。单击每个按钮时,他们将更改标签的文本以及包含其按钮编号的上下文。例如,当用户单击标题为“四”的按钮时,它会将标签更改为您单击了按钮“四”

enter image description here

不是为每个按钮创建一个信号槽,而是创建一个接受参数的通用方法,并使用 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/

相关文章:

python - 如何使用 python 在 google app engine blobstore 上创建一个简单的虚拟文件系统?

python - 在空闲状态下停止光标闪烁

python - tf.py_function 无法返回列表?

qt - 在PyQt中覆盖QPaintEvents

pyqt4 - QtWebKit:控制每个http请求可以消耗的时间

python - numpy 中更快的矩阵计算

python - 如何计算 Django 中的 Frechet 距离?

python - 如何在pyqt的QLineEdit中限制用户输入

python - 在 QMenu 中的指定位置插入新项目

python-2.7 - 在pyqt中,按下Ctrl + anyKey时如何在QLineEdit中打印 "Ctrl+key"