Skip to content
Advertisement

In PyQT why somes widgets needs the “self” parameter before calling them, while others don’t

I’m a little bit confused about the use of the “self” parameter with some widgets like (QLineEdit), indeed when learning to use the QLabel widget, I used to call the class without the self paramater, or when using the QLineEdit widget, the widget wouldn’t work without the “self” parameter, here’s the code I’m working on :

JavaScript

So here is where I’m confused, when using QLabel, I didn’t have to put the “self” parameter before, or when using QLineEdit, I had to put “self” otherwise my code wouldn’t work :

JavaScript

Advertisement

Answer

First of all, the problem or difference has nothing to do with the “self”, but what it is for, pre-established rules in Qt design.

In Qt there is a hierarchy tree between the QObjects where it is established that the parent QObject manages the memory (the life cycle of its children) so if the parent deleted the children, they will also be deleted. This allows avoiding memory leaks since many QObjects are generally used in many applications.

On the other hand, that concept of kinship is also passed to QWidgets since they are also QObjects, but there is also another characteristic: a QWidget in general will be drawn on top of its parent. So if you want the QLineEdit and QLabel to be part of the window then they must be children of the window so it is necessary that you pass the window object which is “self” as parent.

So when you go to the window (in this case “self”) you avoid 2 problems:

  • That the object has a longer life cycle (the same as the window).
  • And you make the widget (either QLabel or QLineEdit) be placed on top of the window.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement