Skip to content
Related Articles
Open in App
Not now

Related Articles

How to remove all items in a Qlistwidget in PyQt5?

Improve Article
Save Article
Like Article
  • Last Updated : 25 Feb, 2021
Improve Article
Save Article
Like Article

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:


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!