[PyKDE] PyQt4 problems with underlying C/C++ objects [weird]

Giovanni Bajo rasky at develer.com
Tue Nov 21 15:17:44 GMT 2006

Krystian Samp wrote:

>> It seems that when you create an item the python object holds a
>> reference to it. However, if you assign that item to a hierarchy of
>> items (for instance using setParentItem()) the python object loses
>> (or you can say hands over) the reference. This reference still
>> exists in the C/C++ level in the hierarchy but only there. So If you
>> stop referencing to the parent of the item then the item itself will
>> be destroyed as well. This is weird since you still have a python
>> object representing the item but as I said it handed over the
>> reference to the C/C++ layer. This is my observation and I think
>> it's not a good behavior of PyQt since you actually have to think
>> about C/C++ and the principle I've described.

Well, you HAVE to know what C++ does anyway. If the C++-side thinks that the
parent owns the ownership of the child, there is nothing PyQt can do to
prevehent it. If the C++ side then destroys that item (because eg. the
parent kills it), there's nothing PyQt can do to prevent the object from
being deallocate. I'll give you a short example of what I mean:

class Foo(QWidget):
    def __init__(self, parent):
         QWidget.__init__(self, parent)
         self.bar = QWidget(self)

f = Foo(None)
b = f.bar
del f
# what about b?

In this case, Python still holds a reference to "b", but the underlying
QWidget in C++ has been destroyed because it was child of "f" and "f" was
destroyed. There's nothing PyQt can do to prehevent this: on the contrary,
it *exposes* this behaviour, which is the way QObject's ownership system

In other words, you can't ignore this problem, you must know and understand
QObject lifetime. You can't assume that, since you have a Python reference,
the underlying object will stay alive forever.
Giovanni Bajo

More information about the PyQt mailing list