pyqt5:ComboBox联级

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_())

``结果:
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值