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' , 'neveropen' ]) # 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: