使用currentIndeChanged來綁定選擇變化后的函數, 使用QComboBox().currentText()來獲得當前被選中框的文本
QComBoBoxDemo.py
""" 下拉列表控件 (QComboBox) 1.如果將列表項添加到QComboBox控件中 2.如何獲取選中的列表項 """ import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt class QComboxDemo(QWidget): def __init__(self): super(QComboxDemo, self).__init__() self.initUI() def initUI(self): self.setWindowTitle("下拉列表控件演示") #設置框的大小 self.resize(300, 100) #創建垂直布局 layout = QVBoxLayout() #設置起頭標簽 self.label = QLabel("請選擇編程語言") #構建下拉框 self.cb = QComboBox() #往下拉框中添加文本 self.cb.addItem("C++") self.cb.addItem("Python") self.cb.addItems(['Java', 'C#', 'Ruby']) #當下拉框的選項變化時,進行函數綁定 self.cb.currentIndexChanged.connect(self.selectionChange) layout.addWidget(self.label) layout.addWidget(self.cb) self.setLayout(layout) #i表示第幾個下拉框被選中 def selectionChange(self, i): #設置label的內容為下拉框的選中內容 self.label.setText(self.cb.currentText()) #自動跳轉label的大小 self.label.adjustSize() #循環下拉框 for count in range(self.cb.count()): print('item' + str(count) + "=" + self.cb.itemText(count)) #打印被選中下拉框的內容 print('current index', i, 'selection changed', self.cb.currentText()) if __name__ == "__main__": app = QApplication(sys.argv) main = QComboxDemo() main.show() sys.exit(app.exec_())