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?
Asked
Active
Viewed 2,610 times
7
-
There is no easier possibility in C++ Qt than catching the `destroyed()` signal, so i doubt this is possible with PyQt. – smerlin Feb 26 '11 at 00:30
2 Answers
15
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

Gary Hughes
- 4,400
- 1
- 26
- 40
-
-
I have found that importing sip from PyQt works better in some cases. Done as `from PyQt5 import sip`. – Presbitero Aug 14 '20 at 12:28
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.')

Peter C
- 6,219
- 1
- 25
- 37
-
2The question is about the Qt object, not the Python object. Even if this might happen to work by a mere accident, but it's not the way to do it. And it's more work than listening for the signal. – Rosh Oxymoron Feb 25 '11 at 23:39
-
@Rush: He asked "I would like to simply test if a Python reference is still valid". So that is exactly what this does. – Peter C Feb 26 '11 at 00:03
-
1Sorry, that quote is unclear. I am asking about the underlying C++ object. I'll fix the question. – Judge Maygarden Feb 27 '11 at 19:07