QComboBox 中addItem("")添加单个选项; addItems(列表)添加多个选项;
例如:下面实现省市级联效果如下:
1 #QComboBox下拉列表控件使用,省市级联 2 from PyQt5.QtWidgets import QPushButton,QVBoxLayout,QWidget,QApplication,QRadioButton,QHBoxLayout,QCheckBox,QGroupBox,QComboBox 3 from PyQt5.QtGui import QIcon,QPixmap 4 from PyQt5.QtCore import Qt 5 6 import sys 7 8 class WindowClass(QWidget): 9 10 def __init__(self,parent=None): 11 self.citys = {"北京": ["北京"], "上海": ["上海"], "河北省": ["石家庄", "邯郸"]} 12 super(WindowClass, self).__init__(parent) 13 layout=QVBoxLayout() 14 self.comboBox_1=QComboBox() 15 self.comboBox_1.addItem("--请选择--") 16 self.comboBox_1.addItem("北京") 17 self.comboBox_1.addItem("上海") 18 self.comboBox_1.addItem("河北省") 19 self.comboBox_1.addItems(["湖南省","湖北省","天津"]) 20 21 self.comboBox_2 = QComboBox() 22 self.comboBox_2.addItem("--请选择--") 23 24 layout.addWidget(self.comboBox_1) 25 layout.addWidget(self.comboBox_2) 26 self.comboBox_1.currentIndexChanged.connect(self.btnState) 27 28 self.setLayout(layout) 29 def btnState(self): 30 print("状态:",self.comboBox_1.currentText()) 31 # for count in range(self.comboBox_1.count()): 32 # print("列表选项:" ,self.comboBox_1.itemText(count),count) 33 34 province=self.comboBox_1.currentText() 35 print(province in self.citys.keys()) 36 if province!="--请选择--": 37 self.comboBox_2.clear() 38 self.comboBox_2.addItems(self.citys[province] if province in self.citys.keys() else ["--请选择--"]) 39 else: 40 self.comboBox_2.clear() 41 self.comboBox_2.addItem("--请选择--") 42 43 44 45 if __name__=="__main__": 46 app=QApplication(sys.argv) 47 win=WindowClass() 48 win.show() 49 sys.exit(app.exec_())