PyQt4中的QObject如何查询其底层C++实例是否已销毁?
可以监听一个叫做 destroyed() 的信号,这个信号是针对 QObject 的。不过,我想知道有没有简单的方法来检查一个 Python 对象是否还指向一个有效的 C++ Qt 对象?有没有直接的方法可以做到这一点?
2 个回答
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.')
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