📅  最后修改于: 2023-12-03 15:03:59.567000             🧑  作者: Mango
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.
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()
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)
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()
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)
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.