Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Signal-slot disconnection and Python objects



  • I'd like to try and clear up my understanding of how Python, C++, and signal-slot connections interact with object deletion and garbage collection. For some reason, I can't find any solid documentation on this topic.

    What I'm trying to find out, is under what circumstances signals and slots must be manually disconnected, and under what circumstances a signal-slot connection will prevent garbage collection, if any.

    For example, say I have a pure-python object like this:

    class Example(object):
        def __init__(self):
            self.timer = QtCore.QTimer()
            self.timer.timeout.connect(self.timed_out)
    
        def timed_out(self):
            print "Timer timed out!"
    
    x = Example()
    ... stuff ...
    ... some time later ...
    x = None or del x
    

    The questions I have are:

    1. Will having a signal-slot connection like the above prevent the python object from being garbage-collected? When x is deleted or set to None so that the Example instance is no longer referenced, will the slot connection inside Example cause it to be retained?

    2. Is the signal-slot connection automatically disconnected when the python object is garbage collected? So, assuming that an instance of Example has no more references, and it gets garbage collected, does the signal-slot connection get disconnected?

    3. Are there other caveats to be aware of here? What if Example were a subclass of QObject? Or if I were to use the decorators for automatic connection of signals and slots?

    I'm just trying to get a clear picture of when I should be worried about manually disconnecting slots, if it would prevent garbage collection of a python object, and when I can expect disconnection to be automatic.


  • Lifetime Qt Champion

    Hi,

    In C++ disconnection happens on object destruction.

    There should be no reason for a connection to extend the lifetime of any object.

    Depending on how you create your object (for example external helper function) it might need a parent to not get garbage collected.



  • @SGaist ok, so that's what I was hoping was the case, if I'm understanding you correctly. Since the signal-slot connection does not prevent the python Example instance from getting garbage collected when all references are gone, it means the QTimer instance is also released, and when it is garbage collected, the C++ object will be destroyed, and any connections will be severed.

    That makes sense to me, just wanted to be sure it was the case.
    In my tests, it certainly seems to be.


Log in to reply