Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed?

早过忘川 提交于 2021-01-27 04:21:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!