PyQt5 - Getting the text of selected item in ComboBox

PyQt5 - Getting the text of selected item in ComboBox

In PyQt5, if you want to get the text of the selected item in a QComboBox, you can use the currentText() method of the QComboBox object.

Here's a simple example to demonstrate this:

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


class ComboBoxApp(QWidget):
    def __init__(self):
        super().__init__()

        # Initialize the UI elements
        self.init_ui()

    def init_ui(self):
        # Set up the layout
        layout = QVBoxLayout()

        # Create a QComboBox
        self.combo = QComboBox(self)
        self.combo.addItems(["Option 1", "Option 2", "Option 3"])

        # Create a QLabel to display the selected item
        self.label = QLabel('Selected: ')

        # Create a button to get the selected item when clicked
        btn = QPushButton("Get Selected Item", self)
        btn.clicked.connect(self.on_button_clicked)

        # Add widgets to the layout
        layout.addWidget(self.combo)
        layout.addWidget(self.label)
        layout.addWidget(btn)

        self.setLayout(layout)

    def on_button_clicked(self):
        selected_text = self.combo.currentText()
        self.label.setText('Selected: ' + selected_text)


app = QApplication(sys.argv)
window = ComboBoxApp()
window.show()
sys.exit(app.exec_())

In this example, a QComboBox is created with three options. There's also a QPushButton. When you press the button, the currently selected text in the QComboBox is fetched using the currentText() method and then displayed in a QLabel.

You can modify the on_button_clicked method as needed to process or use the selected text from the combo box.


More Tags

ionic2 manifest.json author asp.net-core-2.2 pyuic curve-fitting nouislider system.net formbuilder cloud

More Programming Guides

Other Guides

More Programming Examples