📌  相关文章
📜  PyQt5 – QComboBox(1)

📅  最后修改于: 2023-12-03 15:03:59.567000             🧑  作者: Mango

PyQt5 – QComboBox

Introduction

In PyQt5, QComboBox is a widget that allows the user to choose an item from a list of options. It provides a dropdown menu with a list of options from which the user can select one or multiple items.

Features
  1. Dropdown Menu: QComboBox displays a dropdown list of options when clicked, providing an easy and intuitive way for users to select an item.
  2. Customizable: QComboBox allows customization of various visual aspects like the text color, background color, font, and more.
  3. Item Selection: It allows the user to select a single item or multiple items from the list, depending on the configuration.
  4. Signals and Slots: QComboBox emits signals to notify the program when the selected item is changed, allowing for seamless integration with other PyQt5 widgets and functionality.
  5. Data Handling: QComboBox can handle both string-based and data-based items, making it versatile for different use cases.
  6. Editable: QComboBox can be set as editable, allowing users to enter their own values in addition to selecting predefined options.
Usage

To use QComboBox in your PyQt5 application, you need to import the QComboBox class from the PyQt5.QtWidgets module.

from PyQt5.QtWidgets import QApplication, QMainWindow, QComboBox

# Create a QComboBox instance
combo_box = QComboBox()
Adding Items

To add items to the QComboBox, you can use the addItem() or addItems() methods.

# Adding a single item
combo_box.addItem("Option 1")

# Adding multiple items
items = ["Option 2", "Option 3", "Option 4"]
combo_box.addItems(items)
Retrieving Selected Item

To retrieve the currently selected item in the QComboBox, you can use the currentText() or currentIndex() methods.

# Retrieving the selected item text
selected_text = combo_box.currentText()

# Retrieving the selected item index
selected_index = combo_box.currentIndex()
Signals and Slots

QComboBox provides signals like currentIndexChanged and currentTextChanged that can be connected to functions or methods to perform actions when the selected item is changed.

def selection_changed(index):
    print("Selected Item Index:", index)
    
combo_box.currentIndexChanged.connect(selection_changed)
Conclusion

PyQt5's QComboBox is a versatile and customizable widget that provides a dropdown menu for selecting items from a list of options. Its ability to handle signals and slots makes it a powerful tool in PyQt5 development.