Skip to content
Related Articles

Related Articles

deleteLater() method in PyQt5

View Discussion
Improve Article
Save Article
  • Last Updated : 26 Mar, 2020

While designing an application it could potentially consume a lot of space/memory if care is not taken when closing widgets. The QObject-based classes are designed to be (optionally) linked together in a hierarchy. When a top-level object is deleted, Qt will automatically delete all its child objects as well. However, when closing widgets, automatic deletion will only happen if the Qt.WA_DeleteOnClose attribute is set (which, by default, it usually isn’t).

In PyQt5, there are two aspects to object ownership: the Python part, and the Qt part. Often, removing the last Python reference to an object won’t be enough to fully clean up, because there could still be a reference held on the Qt side. In general, Qt tends not to implicitly delete objects. So if your application creates and removes lots of Widgets, you may need to take steps to delete them explicitly if memory usage is a concern.

deleteLater() method allows us to explicitly delete the reference of the widget.

Syntax : widget.deleteLater()

Argument : It takes no argument.

Action performed : It deletes/remove the reference of the widget from the memory.

Code :

# importing the required libraries
from PyQt5.QtWidgets import * 
from PyQt5 import QtCore
from PyQt5 import QtGui
import sys
class Window(QMainWindow):
    def __init__(self):
        # set the title
        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)
        # creating a label widget
        self.label_1 = QLabel("Label", self)
        # moving position
        self.label_1.move(100, 100)
        # setting up border
        self.label_1.setStyleSheet("border: 1px solid black;")
        # delete reference
        # show all the widgets
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app

It will delete the reference associated with the label widget from memory.
Output :

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!