问题
The destroyed() signal can be trapped for a QObject, but I would like to simply test if the Python object still references a valid C++ Qt object. Is there a method for doing so directly?
回答1:
If you import the sip module you can call its .isdeleted function.
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
回答2:
You can use the WeakRef class in the Python standard library. It would look something like:
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.')
来源:https://stackoverflow.com/questions/5122451/can-a-pyqt4-qobject-be-queried-to-determine-if-the-underlying-c-instance-has-b