Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to remove all items in a Qlistwidget in PyQt5?

  • Last Updated : 25 Feb, 2021

Prerequisite:

There are so many options provided by Python to develop GUI applications and PyQt5 is one of them. PyQt5 is a cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library.

In this article, we will learn how to remove all items from QlistWidget in PyQt5. To achieve the required functionality i.e. to cleaning the window or deleting all elements using Qlistwidget in Python, its clear() method is used.

Syntax:

clear()

Approach

  • Import module
  • Create QListWidget
  • Add title and button
  • Add mechanism to delete all items of the list when the button is pressed
  • Display window

Program:

Python3




# Import Module
import sys
from PyQt5.QtWidgets import *
  
  
class ListBox(QWidget):
  
    def __init__(self):
        super().__init__()
  
        self.initUI()
  
    def initUI(self):
        # Vertical box layout
        vbox = QVBoxLayout(self)
  
        # Horizontal box layout
        hbox = QHBoxLayout()
  
        # Create QlistWidget Object
        self.listWidget = QListWidget(self)
  
        # Add Items to QlistWidget
        self.listWidget.addItems(
            ['python', 'c++', 'java', 'pyqt5', 'javascript', 'geeksforgeeks'])
  
        # Add Push Button
        clear_btn = QPushButton('Clear', self)
        clear_btn.clicked.connect(self.clearListWidget)
  
        vbox.addWidget(self.listWidget)
        hbox.addWidget(clear_btn)
        vbox.addLayout(hbox)
  
        self.setLayout(vbox)
  
        # Set geometry
        self.setGeometry(300, 300, 350, 250)
  
        # Set window title
        self.setWindowTitle('QListWidget')
  
        # Display QlistWidget
        self.show()
  
    def clearListWidget(self):
        self.listWidget.clear()
  
  
if __name__ == '__main__':
    app = QApplication(sys.argv)
  
    # Call ListBox Class
    ex = ListBox()
  
    # Close the window
    sys.exit(app.exec_())

Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!