It\'s not the first time I am getting the RuntimeError: underlying C/C++ object has been deleted
. I\'ve solved it many times altering my code in a random but in
The currently accepted answer claims that:
You cannot test if the underlying object exists (e.g., if it has been "deleted")
This is wrong. There must be a way to do this, otherwise it would be impossible for PyQt to raise an exception. Here is some example output that demonstrates how to explicitly test for deletion:
>>> import sip
>>> from PyQt4 import QtCore, QtGui
>>> app = QtGui.QApplication([''])
>>> w = QtGui.QWidget()
>>> w.setAttribute(QtCore.Qt.WA_DeleteOnClose)
>>> sip.isdeleted(w)
False
>>> w.close()
True
>>> sip.isdeleted(w)
True
>>> w.objectName()
Traceback (most recent call last):
File "", line 1, in
RuntimeError: wrapped C/C++ object of type QWidget has been deleted
A PyQt widget consists of a Python part, and a C++ part. If the C++ part is deleted by Qt, an empty Python wrapper object will be left behind. And if you attempt to call any Qt methods via an object in that state, a RuntimeError
will be raised (which is of course preferrable to a likely segfault).
In general, Qt tends not to implicitly delete objects, which is why I had to explicitly mark the widget for deletion in the example above. The exceptions to this general rule are always clearly documented - for example by specifying whether it's Qt or the caller that takes ownership of an object. (This is one reason why it can really pay to become familiar with the Qt documentation, even if you have no knowledge of C++).
In most PyQt code, the simplest way to avoid problems is to either make sure the object has a parent, or explictly keep a reference to the object (often as an instance attribute of the main window).