[PyQt] Cleanup on object destruction

Kyle Altendorf sda at fstab.net
Mon Jun 10 17:10:33 BST 2019


The answer in Python is to be explicit.  Note that there is no guarantee that __del__ will even be called.  Maybe Qt can help but it's a common bug to lose references to the python object and leave the c++ side hanging so I wouldn't bet on having any fool proof solution.  Depending on the scenario (and probably requiring some async library) a context manager can come into play to handle cleanup.  But since lots of people don't use python async features with pyqt...  Anyways, I like the pairing.

Cheers,
-kyle

On June 10, 2019 11:51:43 AM EDT, AnyOldName3 <krizdjali at gmail.com> wrote:
>Hi,
>I've made a Python class that extends QOpenGLWidget, and needs to clean
>up
>some OpenGL objects when it's destroyed. The Qt documentation for this
>says
>cleanup code should be called by the destructor and when the
>QOpenGLContext::aboutToBeDestroyed signal is emitted, so I've tried
>calling
>my cleanup method from __del__ and connecting it as a slot to the
>signal.
>Unfortunately, the signal isn't emitted when the widget is destroyed,
>just
>when the widget has its context replaced, and __del__ seems to be
>called too
>late as calling some of the C++ methods doesn't work (no exception is
>thrown, but nothing after the call is executed).
>The next approach I tried was connecting the cleanup method to the
>widget's
>destroyed signal, which required a lambda as mentioned  here
><https://machinekoder.com/how-to-not-shoot-yourself-in-the-foot-using-python-qt/>
>
>. This signal isn't emitted until after __del__ has been called, and so
>I
>get exceptions due to the C++ object no longer existing.
>The only approach I've had success with is getting the widget's parent
>and
>connecting to /its/ destroyed signal, but this doesn't seem especially
>robust - I can imagine situations where a hypothetical widget wouldn't
>necessarily have a parent when it was destroyed, but may well still
>need to
>do cleanup.
>Is there a nicer way of doing this, for example, a method that SIP will
>call
>as the first thing the C++ destructor does, so that nothing's been
>destroyed
>yet? If not, could something like that be added?
>
>
>
>--
>Sent from: http://python.6.x6.nabble.com/PyQt-f1792048.html


More information about the PyQt mailing list