March 21, 2012

abelvedere abelvedere
Lab Rat
1 posts

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?

1 reply

March 21, 2012

abelvedere abelvedere
Lab Rat
1 posts

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.

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

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

 
  ‹‹ PySide compile from source on Windows 7 64-bit      pyside-rcc command line compression question ››

You must log in to post a reply. Not a member yet? Register here!