import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox class ComboBoxExample(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): vbox = QVBoxLayout() self.combo = QComboBox(self) self.combo.addItem("Item 1", 1) self.combo.addItem("Item 2", 2) self.combo.addItem("Item 3", 3) self.combo.currentIndexChanged.connect(self.printIndex) vbox.addWidget(self.combo) self.setLayout(vbox) self.show() def printIndex(self, i): print(self.combo.currentData()) if __name__ == '__main__': app = QApplication(sys.argv) ex = ComboBoxExample() sys.exit(app.exec_())
import sys from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QComboBox, QMessageBox class ComboBoxExample(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): vbox = QVBoxLayout() self.combo = QComboBox(self) self.combo.addItem("Option A", 1) self.combo.addItem("Option B", 2) self.combo.addItem("Option C", 3) self.combo.addItem("Option D", 4) self.combo.addItem("Option E", 5) self.combo.currentIndexChanged.connect(self.showSelectedValue) vbox.addWidget(self.combo) self.setLayout(vbox) self.show() def showSelectedValue(self, i): value = self.combo.currentData() msg = QMessageBox() msg.setWindowTitle("Selected Value") msg.setText(f"You selected option {value}.") msg.exec_() if __name__ == '__main__': app = QApplication(sys.argv) ex = ComboBoxExample() sys.exit(app.exec_())Both examples use the PyQt5.QtWidgets package.