[PyQt] deleteLater vs setParent(None)

Elvis Stansvik elvstone at gmail.com
Tue May 10 16:24:23 BST 2016


2016-05-10 17:21 GMT+02:00 Elvis Stansvik <elvstone at gmail.com>:
> Hi all,
>
> I have this slot of mine which fires up a process:
>
> @pyqtSlot(int)
> def moveToSlot(self, slot):
>     assert slot in range(1, 5)
>
>     def succeeded():
>         if self._slot != slot:
>             self._slot = slot
>             self.slotChanged.emit(self._slot)
>
>     def failed():
>         log.error('moveToSlot: process failed')
>
>     process = Process(timeout=10000, parent=self)
>     process.succeeded.connect(succeeded)
>     process.failed.connect(failed)
>     process.finished.connect(process.deleteLater)
>     process.start(_control('--carousel {}'.format(slot)))

I realize now that the names here are a little confusing for the
uninitiated. The slot is called moveToSlot because it moves a physical
slot. The naming of the slot and its parameter has nothing to do with
Qt slots :)

Elvis

>
> (The Process class here is just a subclass of QProcess with a built-in
> timeout and a couple of convenient signals (failed/succeeded).)
>
> My question is about:
>
>     process.finished.connect(process.deleteLater)
>
> Can I count on that the Process object being destroyed eventually
> here, or should I rather use
>
>     def cleanup():
>         process.setParent(None)
>
>     process.finished.connect(cleanup)
>
> That is, setting its parent to None.
>
> The reason I'm asking is this old post
>
>     https://riverbankcomputing.com/pipermail/pyqt/2007-November/017795.html
>
> where Phil explains:
>
> "When a QObject has a parent it is owned by that parent. When the C++ object is
> owned an extra reference is kept to the Python object under the covers. This
> is needed in case the object is either a Python sub-class or you have stashed
> extra attributes in the instance dictionary.
>
> Therefore you need to either call the C++ dtor (using sip.delete()), arrange
> for it to be called (using deleteLater()), or change the ownership back to
> Python (using setParent()). Changing the ownership also removes that extra
> reference so that the object is available to be garbage collected when it
> goes out of scope."
>
> It's that extra reference talked about here that I'm thinking of, is
> that a good reason to use setParent(None) + letting the variable go
> out of scope in Python, than calling deleteLater?
>
> This slot of mine will be called many times over a long period of
> time, so I don't want to leak memory.
>
> Thanks in advance!


More information about the PyQt mailing list