Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 834
Judge Maygarden Avatar asked Feb 25 '11 20:02

Judge Maygarden


People also ask

What is a QObject?

QObject is the heart of the Qt Object Model. The central feature in this model is a very powerful mechanism for seamless object communication called signals and slots. You can connect a signal to a slot with connect() and destroy the connection with disconnect().

What is QObject:: connect?

To connect the signal to the slot, we use QObject::connect(). There are several ways to connect signal and slots. The first is to use function pointers: connect(sender, &QObject::destroyed, this, &MyObject::objectDestroyed); There are several advantages to using QObject::connect() with function pointers.

Is PyQt thread safe?

Is PyQt thread safe? Remarks# While some parts of the Qt framework are thread safe, much of it is not. The Qt C++ documentation provides a good overview of which classes are reentrant (can be used to instantiate objects in multiple threads).


2 Answers

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
like image 112
Gary Hughes Avatar answered Oct 19 '22 16:10

Gary Hughes


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.')
like image 2
Peter C Avatar answered Oct 19 '22 16:10

Peter C