PyQt - QList Widget



QListWidget class is an item-based interface to add or remove items from a list. Each item in the list is a QListWidgetItem object. ListWidget can be set to be multiselectable.

Following are the frequently used methods of QListWidget class −

Sr.No. Methods & Description
1

addItem()

Adds QListWidgetItem object or string in the list

2

addItems()

Adds each item in the list

3

insertItem()

Inserts item at the specified index

4

clear()

Removes contents of the list

5

setCurrentItem()

Sets currently selected item programmatically

6

sortItems()

Rearranges items in ascending order

Following are the signals emitted by QListWidget −

Sr.No. Methods & Description
1

currentItemChanged()

Whenever current item changes

2

itemClicked()

Whenever an item in the list is clicked

Example

The following example shows the click event being captured to pop up a message box.

from PyQt4.QtGui import *
from PyQt4.QtCore import *

import sys

class myListWidget(QListWidget):

   def Clicked(self,item):
      QMessageBox.information(self, "ListWidget", "You clicked: "+item.text())
		
def main():
   app = QApplication(sys.argv)
   listWidget = myListWidget()
	
   #Resize width and height
   listWidget.resize(300,120)
	
   listWidget.addItem("Item 1"); 
   listWidget.addItem("Item 2");
   listWidget.addItem("Item 3");
   listWidget.addItem("Item 4");
	
   listWidget.setWindowTitle('PyQT QListwidget Demo')
   listWidget.itemClicked.connect(listWidget.Clicked)
   
   listWidget.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
Advertisements