Course Content
Python PySide6
About Lesson

In this lesson we want to learn about Python PySide6 QListWidget, one of the most useful widgets provided by PySide6 is QListWidget, which is used to display list of items in user interface. 

 

Getting Started with QListWidget

For using PySide6 QListWidget in your application, you will first need to import it from the QtWidgets module. you can then create an instance of the QListWidget and add items to it using addItem() method. this is simple example:

In this example we have created new PySide6 application and QMainWindow object. after that we have created QListWidget object and add three QListWidgetItem objects to it using the addItem() method. Finally, we set the window geometry and title and show the window.

 

 

Run the code and this will be the result.

Python PySide6 QListWidget
Python PySide6 QListWidget

 

Customizing QListWidget

PySide6 QListWidget is highly customizable and provides different options for controlling appearance and behavior of the list. these are a few of the most common customization options:

 

Sorting the List

You can sort the items in the list using the sortItems() method. By default, the sorting is done in ascending order. this is an example:

 

Setting the Current Item

You can set the current item in the list using setCurrentItem() method. this is an example:

 

Selecting Items

You can select one or more items in list using the setItemSelected() method. this is an example that selects the first and third items in the list:

 

Removing Items

You can remove items from the list using the takeItem() method. this is an example that removes the second item from the list:

 

 

Signals and Slots

Like other PySide6 widgets QListWidget provides different signals and slots that you can use to add interactivity to your application. for example you can connect the itemClicked() signal to slot that handles the event when an item in the list is clicked. this is an example:

In this example have we create new PySide6 application and QMainWindow object. after that we have created QListWidget object and added three QListWidgetItem objects to it using addItem() method. also we have connected the itemClicked signal of the QListWidget to  custom slot called on_item_clicked.

on_item_clicked slot is defined to take an argument that represents the item that was clicked in the list. In this case we simply print the text of the clicked item.

Finally we create layout and add the list widget to it using the addWidget() method. we set window geometry and title and show the window. when an item in the list is clicked, the on_item_clicked slot is called, and the text of the clicked item is printed to the console.