[PyQt] what is the difference between QMenu() and QMenu(self)

Mike Ramirez gufymike at gmail.com
Sat Jul 30 00:44:52 BST 2011


On Friday, July 29, 2011 04:20:27 PM Algis Kabaila wrote:
> On Sat, 30 Jul 2011 08:18:58 AM Jian Ma wrote:
> > Hi all,
> > 
> > I created a QMenu object in a class. When I created it with menu =
> > QMenu(self) and run the program, it sometimes got the "segmentation
> > fault" after exit the program. When I created the object with menu =
> > QMenu(), it didn't get this problem. I guess the reason is about the
> > QMenu object ownership. In one case, the object is owned by PyQt. In
> > other case, it is owned by Qt. I am not sure my guess. Can someone give
> > some explanation? Below is some code segment.
> > 
> > class DnDMenuListWidget(QListWidget):
> >     ...
> >     ...
> >     
> >     def dropEvent(self, event):
> >         ...
> >         ...
> >         menu = QMenu(self)    # using QMenu(self)
> >         # menu = QMenu()      #  using QMenu()
> >         ...
> >         ...
> > 
> > Thanks!
> 
> In Python in a class instantiation the instance name is automatically
> passed in a parameter, usually in a named variable "self", so if QMenu is
> a method of a class, a varible named "self" needs to be specified, hence
> QMenu(self).
> 
> If Qmenu is used as a function outside of a class creation, the "self"
> argument is not required, so for functions, hence QMenu().
> 
> For further information read up on class creation of Python (and class
> instantiation and class instances).
> 
> Good luck,
> OldAl.
> _______________________________________________

You're right about this stuff for python, but wrong about in this usage. In 
this case self is the parent object that owns the QMenu() child. It's not a 
method of the parent object, but an attribute.   

i.e.

class MainWindow(QMainWindow):
  # your explanation
  def __init__(self, parent=None):
     # his usage.
     self.menu = QMenu(self)

Using QMenu() without self, just sets the menu's parent to None at 
instination.

The problem is appears to bein the destruction of the parent. I'm not sure. It 
does sounds like the parent is being deystroyed before the child (like the 
discussion on the list a few months ago). I can't remember the subject or the 
fix, but I think the fix was to set the child objects parent to None before it 
the parent was destroyed.  This is an _I Think_.  Others who participated in 
that convo would be better at answering it.

Mike

-- 
They are called computers simply because computation is the only significant
job that has so far been given to them.


More information about the PyQt mailing list