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

Tags: , , , ,



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 :

# Import necessary modules
import sys

from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton
from PyQt5.QtCore import Qt

class EntryWindow(QWidget): # Inherits QWidget

def __init__(self): # Constructor
    super().__init__() # Initializer which calls constructor for QWidget

    self.initializeUI() # Call function used to set up window

def initializeUI(self):
    """
    Initialize the window and display its contents to the screen
    """
    self.setGeometry(400, 300, 400, 200)
    self.setWindowTitle('QLineEdit Widget')
    self.displayWidgets()

    self.show() # Show everything

def displayWidgets(self):
    '''
    Setup the QLineEdit and other widgets.
    '''
    # Create name label and line edit widgets
    QLabel("Please enter your name below.", self).move(100, 20)
    name_label = QLabel("Name:", self)
    name_label.move(55, 70)

    self.name_entry = QLineEdit(self)
    self.name_entry.move(120, 68)
    self.name_entry.resize(200, 25) # Change size of entry field

    self.name_entry.setAlignment(Qt.AlignLeft) # The default alignment

    
    text_font = self.name_entry.font() # Get font option from the Qlineedit
    text_font.setPointSize(12)         # Modify font size
    #text_font.setBold(True)           # Bold
    self.name_entry.setFont(text_font) # Apply font
    

    self.clear_button = QPushButton('Clear text', self)
    self.clear_button.clicked.connect(self.clearEntries)
    self.clear_button.move(120, 130)

    self.exit_button = QPushButton("Exit", self)
    self.exit_button.clicked.connect(self.exitApplication)
    self.exit_button.move(240, 130)

def clearEntries(self):
    
    sender = self.sender()
    if sender.text() == 'Clear text':
        self.name_entry.clear()

def exitApplication(self):

    sender = self.sender()
    if sender.text() == "Exit":
        self.close() # Close the window

   # Run program
   if __name__ == '__main__':
       app = QApplication(sys.argv)
       window = EntryWindow()
       sys.exit(app.exec_())

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 :

QLabel("Please enter your name below.", self).move(100, 20)
self.name_entry = QLineEdit(self)

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.


Source: stackoverflow