PySide passing parent self to child widgets

  • I used Qt in C++ for quite sometime, so i am used to pass a parent pointer (this) to a child widget so that the parent takes care of deleting the child when the parent is deleted (great).

    My question is, in PySide, what is the role of self in child widgets, do i need to pass it to a child widget so that the parent takes care of freeing memory? Isn't the child object garbage collected by python even without passing the parent self ?

    What's the best practice?

  • Apologies, suddenly it occurred to me, so in case someone else is wondering too:

    self keeps the scope of the object alive

    for example if a child widget is created in a parent method, the child will be garbage collected by python if self is not passed to it (making the object a child of the parent widget) or a reference is kept on the parent object i.e.


    example 1

    def create_tray_icon(self):
    # without self the tray object is deleted on exit of this method
    # but passing self makes the parent widget own the child object
    tray = QtGui.QSystemTrayIcon(QtGui.QIcon(":/icon.png"), self)

    example 2

    def create_tray_icon(self):
    # we don't pass self but the parent has a reference to tray (self.tray)
    # so the tray object will not be deleted until the parent is.
    self.tray = QtGui.QSystemTrayIcon(QtGui.QIcon(":/icon.png"))

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.