Home » Tutorial on PyQt6 QComboBox widget

Tutorial on PyQt6 QComboBox widget

1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Oracle Java Certification
Spring Framework Basics Video Course

The QComboBox widget in PyQt6 is a dropdown menu that allows users to select one item from a list.

It supports adding items dynamically, retrieving the selected item, and customizing the dropdown appearance and behavior.

In this tutorial, we’ll cover:

1. Basics of QComboBox

A QComboBox is created by instantiating the class and adding it to a layout or a parent widget.

Example: Basic QComboBox Setup

from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Basic QComboBox Example")
    window.setGeometry(100, 100, 300, 200)

    combo_box = QComboBox(window)
    combo_box.setGeometry(50, 50, 150, 30)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A window with an empty dropdown menu.

2. Adding Items to a QComboBox

You can add items to a QComboBox using the addItem() method or multiple items at once with addItems().

Example: Adding Items

combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)

# Add single items
combo_box.addItem("Option 1")
combo_box.addItem("Option 2")

# Add multiple items
combo_box.addItems(["Option 3", "Option 4", "Option 5"])

3. Retrieving Selected Items

You can retrieve the selected item or its index using:

  • currentText(): Returns the currently selected item as a string.
  • currentIndex(): Returns the index of the selected item.

Example: Get Selected Item

from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox, QPushButton

def show_selected_item():
    print(f"Selected Item: {combo_box.currentText()} (Index: {combo_box.currentIndex()})")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Retrieve Selected Item Example")
window.setGeometry(100, 100, 300, 200)

combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)
combo_box.addItems(["Option 1", "Option 2", "Option 3"])

button = QPushButton("Show Selected", window)
button.setGeometry(50, 100, 150, 30)
button.clicked.connect(show_selected_item)

window.show()
app.exec()

Output:

  • Clicking “Show Selected” prints the selected item and its index to the console.

4. Handling Signals for Interactions

The QComboBox emits signals when users interact with it. Common signals include:

  • currentIndexChanged: Triggered when the selected index changes.
  • activated: Triggered when an item is activated (clicked or selected).

Example: Responding to Selection Changes

from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox

def on_selection_change(index):
    print(f"Selected Index: {index} | Selected Item: {combo_box.itemText(index)}")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Selection Change Signal Example")
window.setGeometry(100, 100, 300, 200)

combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)
combo_box.addItems(["Red", "Green", "Blue"])
combo_box.currentIndexChanged.connect(on_selection_change)

window.show()
app.exec()

Output:

  • Prints the selected index and item text whenever the selection changes.

5. Adding Icons to Dropdown Items

You can add icons to items using addItem() with a QIcon.

Example: Adding Icons

from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox
from PyQt6.QtGui import QIcon

combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)

combo_box.addItem(QIcon("path/to/icon1.png"), "Option 1")
combo_box.addItem(QIcon("path/to/icon2.png"), "Option 2")
combo_box.addItem(QIcon("path/to/icon3.png"), "Option 3")

6. Making Editable QComboBox

An editable QComboBox allows the user to type in custom input.

Example: Editable QComboBox

combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)
combo_box.addItems(["Python", "Java", "C++"])
combo_box.setEditable(True)

7. Styling QComboBox with CSS

You can customize the appearance of a QComboBox using the setStyleSheet() method.

Example: Custom Styling

combo_box.setStyleSheet("""
    QComboBox {
        background-color: lightblue;
        border: 1px solid darkblue;
        border-radius: 5px;
        padding: 5px;
    }
    QComboBox QAbstractItemView {
        background-color: white;
        border: 1px solid lightgray;
        selection-background-color: lightgray;
    }
""")

8. Practical Examples

Example 1: Fruit Selector

from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox, QLabel

def update_label():
    label.setText(f"Selected Fruit: {combo_box.currentText()}")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Fruit Selector")
window.setGeometry(100, 100, 300, 200)

combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)
combo_box.addItems(["Apple", "Banana", "Cherry"])
combo_box.currentIndexChanged.connect(update_label)

label = QLabel("Selected Fruit: None", window)
label.setGeometry(50, 100, 200, 30)

window.show()
app.exec()

Output:

  • Displays the selected fruit in the label.

Example 2: Dynamic Item Addition

from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox, QPushButton

def add_item():
    item = f"Item {combo_box.count() + 1}"
    combo_box.addItem(item)
    print(f"Added: {item}")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Dynamic Item Addition")
window.setGeometry(100, 100, 300, 200)

combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)

button = QPushButton("Add Item", window)
button.setGeometry(50, 100, 150, 30)
button.clicked.connect(add_item)

window.show()
app.exec()

Output:

  • Adds a new item to the dropdown whenever the button is clicked.

Example 3: Editable Dropdown with Validation

from PyQt6.QtWidgets import QApplication, QMainWindow, QComboBox, QLabel

def validate_input():
    text = combo_box.currentText()
    if text in combo_box_items:
        label.setText("Valid selection!")
    else:
        label.setText("Invalid input!")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Editable Dropdown Example")
window.setGeometry(100, 100, 300, 200)

combo_box_items = ["Dog", "Cat", "Bird"]
combo_box = QComboBox(window)
combo_box.setGeometry(50, 50, 150, 30)
combo_box.addItems(combo_box_items)
combo_box.setEditable(True)

combo_box.editTextChanged.connect(validate_input)

label = QLabel("Start typing...", window)
label.setGeometry(50, 100, 200, 30)

window.show()
app.exec()

Output:

  • Validates user input in real-time against predefined options.

Summary

In this tutorial, we covered:

  1. Basics of QComboBox: Creating dropdowns and adding items.
  2. Retrieving Selected Items: Using currentText() and currentIndex().
  3. Signals: Handling user interactions with currentIndexChanged.
  4. Icons: Adding icons to dropdown items.
  5. Editable Dropdowns: Allowing custom user input.
  6. Styling: Customizing appearance with CSS.
  7. Practical Examples: Building a fruit selector, dynamic item addition, and editable dropdown with validation.

The QComboBox widget is a versatile tool for creating dropdown menus in PyQt6 applications, and mastering its features will greatly enhance your ability to build interactive GUIs.

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More