pyqt5:ComboBox联级
1、数据准备(字典格式)
city = {“安徽”: [“合肥”,“六安”], “上海”: [“上海”], “河北省”: [“石家庄”, “邯郸”]}
2、代码
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test_combox.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog, QApplication,QMainWindow,QMessageBox
from PyQt5 import Qt
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class Ui_Form(QMainWindow):
def __init__(self):
super(Ui_Form,self).__init__()
self.setupUi(self)
self.retranslateUi(self)
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(467, 274)
Form.setStyleSheet("")
self.comboBox = QtWidgets.QComboBox(Form)
self.comboBox.setGeometry(QtCore.QRect(10, 80, 181, 22))
self.comboBox.setObjectName("comboBox")
self.comboBox_2 = QtWidgets.QComboBox(Form)
self.comboBox_2.setGeometry(QtCore.QRect(250, 80, 161, 22))
self.comboBox_2.setObjectName("comboBox_2")
self.city={"安徽": ["合肥","六安"], "上海": ["上海"], "四川省": ["成都", "南充"]}
self.item1=dict(self.city)
self.comboBox.addItem("--请选择--")
self.comboBox.addItems(self.item1.keys())
self.comboBox_2.addItem("--请选择--")
self.comboBox.currentIndexChanged.connect(self.changecom)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def changecom(self):
print("状态:", self.comboBox.currentText())
# for count in range(self.comboBox_1.count()):
# print("列表选项:" ,self.comboBox_1.itemText(count),count)
item_name = self.comboBox.currentText()
print(item_name in self.item1.keys())
if item_name != "--请选择--":
self.comboBox_2.clear()
self.comboBox_2.addItems(self.item1[item_name] if item_name in self.item1.keys() else ["--请选择--"])
else:
self.comboBox_2.clear()
self.comboBox_2.addItem("--请选择--")
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
if __name__ == '__main__':
QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
MainWindow1 = QMainWindow()
ui = Ui_Form()
ui.setupUi(MainWindow1)
MainWindow1.show()
sys.exit(app.exec_())
``结果: