可以为QObject捕获destroyed()信号,但我想简单地测试Python对象是否仍然引用有效的C ++ Qt对象。有没有直接这样做的方法?
答案 0 :(得分:15)
如果您导入sip模块,则可以调用其.isdeleted函数。
import sip
from PyQt4.QtCore import QObject
q = QObject()
sip.isdeleted(q)
False
sip.delete(q)
q
<PyQt4.QtCore.QObject object at 0x017CCA98>
q.isdeleted(q)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: underlying C/C++ object has been deleted
答案 1 :(得分:2)
您可以在Python标准库中使用WeakRef类。它看起来像是:
import weakref
q = QObject()
w = weakref.ref(q)
if w() is not None: # Remember the parentheses!
print('The QObject is still alive.')
else:
print('Looks like the QObject died.')