PyQT4 signal.connect是否保持对象存活? [英] Does PyQT4 signal.connect keep objects live?
问题描述
如果我有一个信号,并且我注册一个对象函数到信号中,这会使对象保持活动并停止对象的垃圾回收?
If I have a signal and I register an objects function to the signal will this keep the object live and stop the garbage collection of that object?
p>
E.g.
class Signals():
signal = Qt.pyqtSignal()
def __init__(self):
QObject.__init__(self)
class Test();
def __init__(self, s):
s.connect(self.done)
def done(self):
print("Done")
s = Signals()
t = Test(s.signal)
t = None
s.signal.emit()
测试对象仍会得到信号吗?
Will the Test objecct still get the signal?
推荐答案
不,它不会让物体保持活力。试试看:
No, it won't, it's not enough to keep the object alive. Just try it:
from PyQt4.QtCore import *
app = QCoreApplication([])
class Signals(QObject):
signal = pyqtSignal()
def __init__(self):
QObject.__init__(self)
class Test():
def __init__(self, s):
s.connect(self.done)
def done(self):
print("Done")
s = Signals()
t = Test(s.signal)
print("first")
s.signal.emit()
app.processEvents()
t = None
print("second")
s.signal.emit()
app.processEvents()
输出:
first
Done
second
此行为仅适用于将信号连接到绑定方法。例如,如果您使用:
This behaviour only applies when connecting a signal to a bound method. As an example, if you use:
s.connect(lambda: self.done())
来代替,那么它将起作用。如果库不会在这里保留一个强有力的参考,那么你永远不能将一个匿名函数连接到一个信号。所以在这种情况下,pyqt必须确保它保持对函数的引用,并且在lambda的闭包中保持引用对象( self
)
instead, then it will work. If the library wouldn't keep a strong reference here, then you could never connect an anonymous function to a signal. So in this case pyqt has to ensure that it keeps a reference to the function, and the object (self
) keeps to be referenced in the closure of the lambda.
这篇关于PyQT4 signal.connect是否保持对象存活?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!