[PyKDE] question about tutorial

Phil Thompson phil at river-bank.demon.co.uk
Sat Dec 16 12:28:31 GMT 2000


dan wrote:
> 
> if a question like this does not belong in the mailing list, i apologize.
> 
> In the aclock.py tutorial
> (snip)
> class AnalogClock(QWidget):
>   def __init__(self, *args):
>     apply(QWidget.__init__,(self,) + args)
>     self.time = QTime.currentTime()
>     internalTimer = QTimer(self)
>     self.connect(internalTimer, SIGNAL("timeout()"), self.timeout)
>     internalTimer.start(5000)
> ...
> (/snip)
> 
> there is a Qtimer created in the __init__ method, but isn't it local? Won't
> it be garbage collected upon exit of the method? Obviously it isn't because
> the demo works, but that really confuses me. Was some code put it so used
> QObjects aren't destroyed once they are out of scope?

There are always 2 objects - the Python object and the C++ object.
Normally the Python object "owns" the C++ object, ie. the Python object
is responsible for calling the C++ object's dtor when it itself is
garbarge collected. This is the behaviour you are expecting.

However, Qt QObjects (and its sub-classes) know about their children and
will call their dtors from the parent dtor. There is, therefore, the
possibility of the C++ dtor being called twice - once from the
corresponding Python object and once from the parent C++ object's dtor -
resulting in a core dump.

PyQt knows when Qt takes responsibilty for calling the dtor and doesn't
try to do it itself. So, in the above example, QTimer has a parent and
so "ownership" of the QTimer C++ object is transfered to Qt
(specifically the parent of the QTimer). When the Python object is
garbage collected as it goes out of scope, it leaves the C++ object
alone which continues to function as expected.

If the QTimer didn't have a parent (ie. "internalTimer = QTimer()") then
the behaviour would be exactly as you were expecting.

If you look at the .sip files, this type of transfer of ownership (there
are others) is specified by the "/TransferThis/" flag. It's subtle
things like this that caused me to write SIP rather than try and use
SWIG.

Phil




More information about the PyQt mailing list