ipykernel
ipykernel copied to clipboard
Clean up QTimer/QSocketNotifier when exiting Qt event loop
The QTimer
and QSocketNotifier
helper objects, created by the _notify_stream_qt()
function as child objects of the global QApplication
, need to be discarded after use when leaving the Qt event loop. Otherwise they keep piling up with each roundtrip between the Qt and the kernel event loop. This code change makes sure that these Qt objects destroy themselves at an appropriate time.
@ccordoba12, mind taking a look at this one as well?
Thanks for the ping @blink1073!
@stukowski, what do you mean by this?
This code change makes sure that these Qt objects destroy themselves at an appropriate time.
I mean, what "an appropriate time" is?
I mean, what "an appropriate time" is?
I meant: Do not delete the QTimer
and QSocketNotifier
objects too early before they have fired, and do not call QObject.deleteLater() too late, because it requires a running Qt event loop.
Note that there are probably more ways of cleaning these objects up. I was just proposing one possible solution, which seems sufficiently simple.
Btw, I observed the problem of the timer and socket notifier not getting released by executing the second notebook cell below multiple times:
%gui qt
from IPython.external.qt_for_kernel import QtCore
for c in QtCore.QCoreApplication.instance().children(): print(c)
The QTimer and QSocketNotifier helper objects, created by the _notify_stream_qt() function as child objects of the global QApplication, need to be discarded after use when leaving the Qt event loop
This is the thing that worries me a bit. I mean, what does this mean for an interactive Matplotlib figure generated with the PyQt5 backend? Closing the figure or simply stop interacting with it after some time?
Pinging @tacaswell about this one too because he could be interested in knowing about it.
No, the QTimer and the QSocketNotifier objects are just an internal implementation detail of the _notify_stream_qt()
function, and deleting these C++ "single-shot" objects after they have fired should have no effect on external Qt application codes (like Matplotlib).
Let me describe the problem again for which I am proposing a solution:
_notify_stream_qt()
creates these two C++ objects to interrupt the Qt event loop as soon as there are new kernel events waiting to be processed. The problem is that _notify_stream_qt()
creates a new set of these single-shot objects each time control returns to the Qt event loop (which happens many times during a session), but forgets to delete them after they have served their one-time purpose. Note that the two objects are created as child objects of the global Qt application. According to Qt's memory management model this means their lifetime is tied to the lifetime of the application object and these C++ objects don't get garbage collected. My pull requests fixes this by deleting the two helper objects explicitly (after they are no longer needed).