Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

python - Is the PySide Slot Decorator Necessary?

I've seen some example code for PySide slots that uses the @QtCore.Slot decorator, and some that does not. Testing it myself, it doesn't seem to make a difference. Is there a reason I should or should not use it? For example, in the following code:

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()

the @QtCore.Slot decorator makes no difference; I can omit it, call @QtCore.Slot(str), or even @QtCore.Slot(int), and it still nicely says, "Hi."

The same seems to be true for PyQt's pyqtSlot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This link explains the following about the pyqtSlot decorator:

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.

and

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

Since the pyqtSlot decorator can take additional argument such as name, it allows different Python methods to handle the different signatures of a signal.

If you don't use the slot decorator, the signal connection mechanism has to manually work out all the type conversions to map from the underlying C++ function signatures to the Python functions. When the slot decorators are used, the type mapping can be explicit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...