How to Use QListWidget in PyQt6?

Recently, I was working on a Python GUI application that needed to display a scrollable list of items with selection capabilities. After exploring various options, I found QListWidget to be the perfect solution.

QListWidget is one of the most versatile widgets in PyQt6. It makes it easy to create and manage lists of items in your GUI applications.

In this article, I’ll provide practical examples of how to implement and customize QListWidget in PyQt6.

QListWidget in PyQt6

QListWidget is a convenient widget that provides a list view with a default model. It’s perfect for displaying a simple list of items that users can view, select, and interact with.

Unlike more complex list views in PyQt6, QListWidget doesn’t require you to create a separate model, making it ideal for simple list implementations.

Basic QListWidget Implementation

Let me explain to you the basic QListWidget implementation.

Create a Simple List

Let’s start with a basic implementation of QListWidget in Python PyQt6:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout

class SimpleListExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Basic QListWidget Example")
        self.setGeometry(100, 100, 400, 300)

        # Create a QListWidget
        self.list_widget = QListWidget(self)

        # Add items to the list
        states = ["California", "Texas", "Florida", "New York", "Pennsylvania"]
        self.list_widget.addItems(states)

        # Create layout and add widget
        layout = QVBoxLayout()
        layout.addWidget(self.list_widget)

        # Set the layout
        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = SimpleListExample()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

PyQt6 QListWidget

In this example, I’ve created a simple list showing five U.S. states. The addItems() method makes it easy to add multiple items at once.

Add Items Individually

You can also add items one by one using the addItem() method in Python:

# Add items individually
self.list_widget.addItem("California")
self.list_widget.addItem("Texas")
self.list_widget.addItem("Florida")

Work with QListWidgetItem in PyQt6

Now, I will explain how to use QListWidgetItem in PyQt6.

Create Custom List Items

For more control over each item, you can use Python PyQt6 QListWidgetItem:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QListWidgetItem
from PyQt6.QtGui import QFont, QColor

class CustomListItems(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Custom List Items")
        self.setGeometry(100, 100, 400, 300)

        # Create a QListWidget
        self.list_widget = QListWidget(self)

        # Add custom items
        states = [
            {"name": "California", "population": "39.5 million"},
            {"name": "Texas", "population": "29.1 million"},
            {"name": "Florida", "population": "21.5 million"},
            {"name": "New York", "population": "19.8 million"},
            {"name": "Pennsylvania", "population": "13.0 million"}
        ]

        for state in states:
            item = QListWidgetItem(f"{state['name']} - {state['population']}")

            # Customize the item
            if state["name"] == "California":
                item.setForeground(QColor("blue"))
                font = QFont()
                font.setBold(True)
                item.setFont(font)

            self.list_widget.addItem(item)

        # Create layout and add widget
        layout = QVBoxLayout()
        layout.addWidget(self.list_widget)

        # Set the layout
        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CustomListItems()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

Use QListWidget in PyQt6

In this example, I’ve created custom list items showing U.S. states with their populations. I’ve also customized the appearance of the “California” item to make it blue and bold.

Read Create Icons for Windows in PyQt6

Handle QListWidget Events in PyQt6

Let me show you an example of handling QListWidget Events in PyQt6.

Respond to Item Selection

One of the most common tasks is responding to item selection:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QListWidget, QVBoxLayout, QLabel

class SelectionExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Selection Handling")
        self.setGeometry(100, 100, 400, 300)

        # Create a QListWidget
        self.list_widget = QListWidget(self)

        # Add items to the list
        national_parks = ["Yellowstone", "Yosemite", "Grand Canyon", "Zion", "Olympic"]
        self.list_widget.addItems(national_parks)

        # Create a label to display selection
        self.selection_label = QLabel("Select a national park")

        # Connect the itemSelectionChanged signal
        self.list_widget.itemSelectionChanged.connect(self.on_selection_change)

        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(self.list_widget)
        layout.addWidget(self.selection_label)

        # Set the layout
        self.setLayout(layout)

    def on_selection_change(self):
        selected_items = self.list_widget.selectedItems()
        if selected_items:
            self.selection_label.setText(f"You selected: {selected_items[0].text()}")
        else:
            self.selection_label.setText("No park selected")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = SelectionExample()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

How to Use QListWidget in PyQt6

Here, I’m using the itemSelectionChanged signal to detect when the user selects an item from the list of U.S. national parks.

Check out Install PyQt6 on Different Platforms

Handle Double-Clicks

You can also respond to double-clicks on list items:

# Connect double-click signal
self.list_widget.itemDoubleClicked.connect(self.on_item_double_clicked)

def on_item_double_clicked(self, item):
    print(f"You double-clicked: {item.text()}")

Advanced QListWidget Features

I help you learn more about Advanced QListWidget Features.

1. Multi-Selection Mode

QListWidget in Python PyQt6 supports different selection modes:

import sys
from PyQt6.QtWidgets import (QApplication, QWidget, QListWidget, QVBoxLayout, 
                            QLabel, QComboBox)
from PyQt6.QtCore import Qt

class MultiSelectionExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Selection Modes")
        self.setGeometry(100, 100, 400, 350)

        # Create a QListWidget
        self.list_widget = QListWidget(self)

        # Add items to the list
        cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix", 
                 "Philadelphia", "San Antonio", "San Diego", "Dallas"]
        self.list_widget.addItems(cities)

        # Create a selection mode combo box
        self.mode_combo = QComboBox()
        self.mode_combo.addItems(["Single", "Extended", "Multi", "NoSelection"])
        self.mode_combo.currentTextChanged.connect(self.change_selection_mode)

        # Set default selection mode
        self.list_widget.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
        self.mode_combo.setCurrentText("Extended")

        # Create a label to display selection
        self.selection_label = QLabel("Select U.S. cities")

        # Connect the itemSelectionChanged signal
        self.list_widget.itemSelectionChanged.connect(self.on_selection_change)

        # Create layout and add widgets
        layout = QVBoxLayout()
        layout.addWidget(QLabel("Selection Mode:"))
        layout.addWidget(self.mode_combo)
        layout.addWidget(self.list_widget)
        layout.addWidget(self.selection_label)

        # Set the layout
        self.setLayout(layout)

    def change_selection_mode(self, mode_text):
        modes = {
            "Single": QListWidget.SelectionMode.SingleSelection,
            "Extended": QListWidget.SelectionMode.ExtendedSelection,
            "Multi": QListWidget.SelectionMode.MultiSelection,
            "NoSelection": QListWidget.SelectionMode.NoSelection
        }
        self.list_widget.setSelectionMode(modes[mode_text])

    def on_selection_change(self):
        selected_items = self.list_widget.selectedItems()
        if selected_items:
            names = [item.text() for item in selected_items]
            self.selection_label.setText(f"Selected: {', '.join(names)}")
        else:
            self.selection_label.setText("No cities selected")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MultiSelectionExample()
    window.show()
    sys.exit(app.exec())

This example demonstrates the different selection modes available in QListWidget, allowing users to select U.S. cities in various ways.

2. Drag and Drop Support

Python QListWidget can support drag and drop operations:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QListWidget, QHBoxLayout
from PyQt6.QtCore import Qt

class DragDropExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Drag and Drop Lists")
        self.setGeometry(100, 100, 600, 400)
        
        # Create source QListWidget
        self.source_list = QListWidget(self)
        self.source_list.setDragEnabled(True)
        self.source_list.setAcceptDrops(True)
        self.source_list.setDropIndicatorShown(True)
        
        # Create destination QListWidget
        self.dest_list = QListWidget(self)
        self.dest_list.setDragEnabled(True)
        self.dest_list.setAcceptDrops(True)
        self.dest_list.setDropIndicatorShown(True)
        
        # Enable drag and drop for both lists
        self.source_list.setDragDropMode(QListWidget.DragDropMode.DragDrop)
        self.dest_list.setDragDropMode(QListWidget.DragDropMode.DragDrop)
        
        # Add items to the source list
        states = ["California", "Texas", "Florida", "New York", "Pennsylvania", 
                 "Illinois", "Ohio", "Georgia", "North Carolina", "Michigan"]
        self.source_list.addItems(states)
        
        # Create layout and add widgets
        layout = QHBoxLayout()
        layout.addWidget(self.source_list)
        layout.addWidget(self.dest_list)
        
        # Set the layout
        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DragDropExample()
    window.show()
    sys.exit(app.exec())

This example demonstrates how to implement intuitive drag-and-drop functionality between two QListWidgets in PyQt6.

In this article, I have explained how to use QListWidget in PyQt6. I discussed creating a basic QListWidget implementation, adding items individually, working with QListWidgetItem in PyQt6, handling QListWidget events in PyQt6, and advanced QListWidget features.

Related tutorials you may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.