我已经看到了一些使用 @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/