python - PySide Slot Decorator 是必需的吗?

标签 python pyqt pyside signals-slots

我已经看到了一些使用 @QtCore.Slot 装饰器的 PySide 插槽示例代码,而有些则没有。自己测试了一下,好像没什么区别。我有理由应该或不应该使用它吗?例如,在以下代码中:

import sys
from PySide import QtCore

# the next line seems to make no difference
@QtCore.Slot()
def a_slot(s):
    print s

class SomeClass(QtCore.QObject):
    happened = QtCore.Signal(str)
    def __init__(self):
        QtCore.QObject.__init__(self)
    def do_signal(self):
        self.happened.emit("Hi.")

sc = SomeClass()
sc.happened.connect(a_slot)
sc.do_signal()

@QtCore.Slot 装饰器没有区别;我可以省略它,调用@QtCore.Slot(str),甚至调用@QtCore.Slot(int),它仍然很好地表示“嗨”。

PyQt 的 pyqtSlot 似乎也是如此。

最佳答案

This链接解释了关于 pyqtSlot 装饰器的以下内容:

Although PyQt4 allows any Python callable to be used as a slot when connecting signals, it is sometimes necessary to explicitly mark a Python method as being a Qt slot and to provide a C++ signature for it. PyQt4 provides the pyqtSlot() function decorator to do this.

Connecting a signal to a decorated Python method also has the advantage of reducing the amount of memory used and is slightly faster.

由于 pyqtSlot 装饰器可以接受额外的参数,例如 name,它允许不同的 Python 方法处理信号的不同签名。

如果您不使用插槽装饰器,则信号连接机制必须手动完成所有类型转换,以从底层 C++ 函数签名映射到 Python 函数。当使用 slot 装饰器时,类型映射可以是显式的。

关于python - PySide Slot Decorator 是必需的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14421897/

相关文章:

python - 从其中一项的事件中清除 QGraphicsScene

python - 更改 tkinter Messagebox 按钮上的文字

python - 如何使用 'with' 语句对 Python 锁进行单元测试?

python - PyQt5 unicode 翻译 : pylupdate5 outputs escape sequences

qt - 在不向撤消堆栈中添加撤消命令的情况下对 QTextEdit 进行更改

python - 实现 PySide 标注

python - 如何按 1)、2) 拆分文本?

python - 想要知道有多少对象位于两个不同子集的重叠部分

python - PyQT——如何使 QTreeview 不可编辑但可选择?

python - 如何使用 PyQt 组织布局