QComboBox Widget in PyQt6

If you are working with desktop applications using PyQt6 and need to let users select from a list of options, like choosing a country, selecting a theme, etc QComboBox Widget in PyQt6 is the perfect tool that you can use.

In this tutorial, I will walk you through how to use QComboBox in PyQt6 to create drop-down menus. Whether you want a static list or a dynamic one that updates based on user input, QComboBox makes it easy.

By the end of this guide, you will know how to add items, respond to user selection, and even customize your dropdowns for a polished user experience.

If you have not installed PyQt6 in your system, this blog will guide you on “How to Install PyQt6 on Different Platforms?“.

QComboBox in PyQt6

A QComboBox is a widget that combines a button and a drop-down list. When the user clicks on the button, the dropdown list appears, allowing them to select from predefined options. It’s perfect for situations where you want to:

  • Save screen space compared to radio buttons
  • Provide a clear list of mutually exclusive choices
  • Implement form fields like state selection, category filters, or sorting options

Read Create a Random Number Generator with QLCDNumber in PyQt6

Create Your First QComboBox in PyQt6

Let us create a simple combo box (drop-down menu) to list a few U.S. states using the QComboBox widget.

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

class ComboBoxOnlyDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QComboBox Only Demo")
        self.setGeometry(100, 100, 400, 200)

        # Create layout
        layout = QVBoxLayout()

        # Label
        label = QLabel("Select a state:")
        layout.addWidget(label)

        # Combo box with items
        combo = QComboBox()
        combo.addItems(["California", "Texas", "New York", "Florida", "Illinois"])
        layout.addWidget(combo)

        self.setLayout(layout)

# Create the application
if __name__ == "__main__":
    app = QApplication(sys.argv)
    demo = ComboBoxOnlyDemo()
    demo.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot.

QComboBox Widget in PyQt6

This is a simple way to show a drop-down list in a PyQt6 app. You can always expand on this by adding interactivity later if needed.

Check out Build a Simple Digital Clock with QLCDNumber in PyQt6

Essential Methods to Create QComboBox

The QComboBox class offers numerous methods to control its behavior and appearance. Here are some of the most useful ones:

1. Add and Remove Items

Let’s start by learning how to add and remove items from a combo box. This is helpful when you want to build dynamic interfaces where options can change based on user actions or data updates.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QComboBox, QPushButton

class ComboBoxItemDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QComboBox Item Management")
        self.setGeometry(100, 100, 400, 200)

        layout = QVBoxLayout()

        # Label to show current item
        self.label = QLabel("ComboBox Items:")
        layout.addWidget(self.label)

        # Create combo box
        self.combo_box = QComboBox()
        layout.addWidget(self.combo_box)

        # Add a single item
        self.combo_box.addItem("Washington")

        # Add multiple items at once
        self.combo_box.addItems(["Oregon", "Nevada", "Arizona"])

        # Insert an item at index 2
        self.combo_box.insertItem(2, "Colorado")

        # Remove the item at index 1 ("Oregon")
        self.combo_box.removeItem(1)

        # Button to clear all items
        clear_button = QPushButton("Clear All Items")
        clear_button.clicked.connect(self.combo_box.clear)
        layout.addWidget(clear_button)

        self.setLayout(layout)

# Run the application
app = QApplication(sys.argv)
demo = ComboBoxItemDemo()
demo.show()
sys.exit(app.exec())

I executed the above example code and added the screenshot.

Create QComboBox Widget in PyQt6

Managing combo box items is super flexible. Whether you’re loading states from a database or updating them based on user choices, these methods make it easy to control what’s shown.

Read QSpinBox Widget in PyQt6

2. Get and Set the Current Selection

Next, let’s see how to read or change what’s currently selected in the combo box. This is important when you want to respond to user input or pre-fill the combo box with a default choice.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QComboBox, QPushButton

class ComboBoxSelectionDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QComboBox Selection Demo")
        self.setGeometry(100, 100, 400, 200)

        layout = QVBoxLayout()

        # Create combo box
        self.combo_box = QComboBox()
        self.combo_box.addItems(["New York", "Florida", "California", "Texas", "Nevada"])
        layout.addWidget(self.combo_box)

        # Label to display current selection
        self.selection_label = QLabel("Selected: ")
        layout.addWidget(self.selection_label)

        # Button to show current selection
        show_button = QPushButton("Show Current Selection")
        show_button.clicked.connect(self.show_current_selection)
        layout.addWidget(show_button)

        # Button to set selection by index
        set_index_button = QPushButton("Set Selection (Index 3)")
        set_index_button.clicked.connect(lambda: self.combo_box.setCurrentIndex(3))  # Sets to "Texas"
        layout.addWidget(set_index_button)

        # Button to set selection by text
        set_text_button = QPushButton("Set Selection ('California')")
        set_text_button.clicked.connect(lambda: self.combo_box.setCurrentText("California"))
        layout.addWidget(set_text_button)

        self.setLayout(layout)

    def show_current_selection(self):
        # Get current text and index
        current_text = self.combo_box.currentText()
        current_index = self.combo_box.currentIndex()
        self.selection_label.setText(f"Selected: {current_text} (Index: {current_index})")

# Run the application
app = QApplication(sys.argv)
demo = ComboBoxSelectionDemo()
demo.show()
sys.exit(app.exec())

I executed the above example code and added the screenshot.

PyQt6Q ComboBox Widget

These methods help your app understand user choices and even pre-select an option for convenience. They’re commonly used when working with forms and filters.

Check out QCheckBox Widget in PyQt6

3. Handle Editable Combo Boxes

By default, combo boxes in PyQt6 are read-only, but what if you want users to type in their value too? You can easily make a combo box editable.

import sys
from PyQt6.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QLabel, QComboBox, QCompleter
)

class EditableComboBoxDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Editable QComboBox with Completer")
        self.setGeometry(100, 100, 400, 200)

        layout = QVBoxLayout()

        # Label
        label = QLabel("Type or select a U.S. state:")
        layout.addWidget(label)

        # Combo box
        self.combo_box = QComboBox()

        # Add state items
        states = ["California", "Texas", "New York", "Florida", "Illinois", "Nevada", "Oregon"]
        self.combo_box.addItems(states)

        # Make it editable
        self.combo_box.setEditable(True)

        # Set completer
        completer = QCompleter(states)
        self.combo_box.setCompleter(completer)

        layout.addWidget(self.combo_box)

        self.setLayout(layout)

# Run the application
app = QApplication(sys.argv)
demo = EditableComboBoxDemo()
demo.show()
sys.exit(app.exec())

Editable combo boxes give users more freedom and improve usability, especially when the list of options is long or open-ended.

Read QRadioButton Widget in PyQt6

Advanced QComboBox Techniques in PyQt6

Let me explain to you some advanced techniques of QComboBox in PyQt6

Adding Icons to Items

Want to make your combo box more visually appealing? You can easily add icons next to each item, great for categories, countries, apps, or anything that benefits from a visual cue.

from PyQt6.QtGui import QIcon

# Add items with icons
combo_box.addItem(QIcon("california.png"), "California")
combo_box.addItem(QIcon("texas.png"), "Texas")
combo_box.addItem(QIcon("newyork.png"), "New York")

Adding icons improves user experience and makes your interface feel more polished.

Use Custom Item Delegates

If you want to customize how items appear inside the combo box, you can go beyond icons and labels using item delegates. These let you control the entire rendering process of each item.

from PyQt6.QtWidgets import QStyledItemDelegate

class CustomDelegate(QStyledItemDelegate):
    def paint(self, painter, option, index):
        # Custom painting logic
        super().paint(painter, option, index)

combo_box.setItemDelegate(CustomDelegate())

Custom item delegates give you full control over the appearance of combo box items, making them highly customizable for advanced UI needs.

Check out Handle Button Click Events Using Signals and Slots in PyQt6

Implement a ComboBox with Data Roles

Sometimes what the user sees isn’t enough, you may want to associate extra data with each combo box item, like a code, ID, or value behind the scenes.

# Add items with user data
combo_box.addItem("California", "CA")
combo_box.addItem("Texas", "TX")
combo_box.addItem("New York", "NY")

# Retrieve the user data
state_code = combo_box.currentData()
print(f"The state code for {combo_box.currentText()} is {state_code}")

Using data roles keeps your UI clean while storing useful information in the background. It’s especially useful for forms, settings, and database apps.

Read Arrange Widgets Using QGridLayout in PyQt6

Real-World Examples

Let us consider some real-world scenarios where we use the PyQt QComboBox widget.

State Selection Form

Imagine you’re building a shipping form for an e-commerce app. You need users to select their U.S. state from a list. Instead of typing it manually, we use a QComboBox to provide a dropdown list of state names.

class AddressForm(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Shipping Address")

        layout = QVBoxLayout()

        # State selection
        state_label = QLabel("State:")
        self.state_combo = QComboBox()

        # Dictionary mapping state names to abbreviations
        self.states = {
            "Alabama": "AL", "Alaska": "AK", "Arizona": "AZ",
            "Arkansas": "AR", "California": "CA", "Colorado": "CO",
            # Add more states...
        }

        # Add states to combo box
        self.state_combo.addItems(sorted(self.states.keys()))

        layout.addWidget(state_label)
        layout.addWidget(self.state_combo)

        # Rest of your form...

        self.setLayout(layout)

Using QComboBox for state selection improves accuracy, saves time, and makes the form easier to fill out, an essential component of real-world data entry forms.

Dynamic ComboBox for Filtering Data

Now let’s take a business scenario. Suppose you’re building a simple product listing screen, and you want users to filter products by category. You can use a QComboBox for that too.

class ProductFilter(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Product Filter")

        layout = QVBoxLayout()

        # Category filter
        category_label = QLabel("Filter by category:")
        self.category_combo = QComboBox()
        self.category_combo.addItem("All Categories")
        self.category_combo.addItems(["Electronics", "Clothing", "Home & Garden", "Sports"])
        self.category_combo.currentIndexChanged.connect(self.filter_products)

        layout.addWidget(category_label)
        layout.addWidget(self.category_combo)

        # Product display area (simplified)
        self.product_list = QLabel("Product list will appear here")
        layout.addWidget(self.product_list)

        self.setLayout(layout)

    def filter_products(self):
        category = self.category_combo.currentText()
        if category == "All Categories":
            # Show all products
            self.product_list.setText("Showing all products")
        else:
            # Filter products by category
            self.product_list.setText(f"Showing {category} products only")

Using QComboBox for filtering is a powerful technique. It’s perfect for dashboards, product catalogs, or any place where users need to narrow down information with ease.

Check out Use QVBoxLayout in PyQt6 for Vertical Layouts

Common Issues of QComboBox and Solutions

IssueSolution
Combo box not updatingCheck for duplicates before adding or using combo_box.findText()
Make sure you’re not blocking signals or connecting to the right signalUse combo_box.setMaxVisibleItems(15) to show more items
Unwanted duplicatesCheck for duplicates before adding or use combo_box.findText()
Items not sortableUse combo_box.model().sort(0) to sort alphabetically

In this article, I discussed the QComboBox Widget in PyQt6. I explained creating QComboBox in PyQt6, as well as the essential methods of QComboBox, and advanced QComboBox techniques in PyQt6. I also covered real-world examples.

Related tutorials you may like to 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.