Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Update: Forum Guidelines & Code of Conduct

    PySide passing parent self to child widgets

    Language Bindings
    1
    2
    3147
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • A
      abelvedere last edited by

      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?

      1 Reply Last reply Reply Quote 0
      • A
        abelvedere last edited by

        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"))
        @

        1 Reply Last reply Reply Quote 0
        • First post
          Last post