非常抱歉,以下是修改后的代码示例,它会存储所选省、市、县的名称:
from PySide6.QtWidgets import QApplication, QMainWindow, QComboBox, QVBoxLayout, QWidget
from openpyxl import load_workbook
def create_cascading_combobox(excel_file):
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("行政区划")
self.combo_province = QComboBox()
self.combo_city = QComboBox()
self.combo_county = QComboBox()
self.selected_province_name = "" # 存储已选中省级选项的名称
self.selected_city_name = "" # 存储已选中市级选项的名称
self.selected_county_name = "" # 存储已选中县级选项的名称
layout = QVBoxLayout()
layout.addWidget(self.combo_province)
layout.addWidget(self.combo_city)
layout.addWidget(self.combo_county)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
self.load_data(excel_file)
self.init_comboboxes()
self.combo_province.currentIndexChanged.connect(self.on_province_changed)
self.combo_city.currentIndexChanged.connect(self.on_city_changed)
self.combo_county.currentIndexChanged.connect(self.on_county_changed)
def load_data(self, excel_file):
wb = load_workbook(excel_file)
ws = wb.active
self.data_model = []
for row in ws.iter_rows(values_only=True):
level, code, name = row
if level == 1:
self.data_model.append((code, name))
elif level == 2:
self.data_model.append((code, name))
elif level == 3:
self.data_model.append((code, name))
def init_comboboxes(self):
self.combo_province.clear()
self.combo_city.clear()
self.combo_county.clear()
self.combo_province.addItem("请选择省级")
for _, name in self.data_model:
self.combo_province.addItem(name)
def on_province_changed(self, index):
self.selected_province_name = self.combo_province.itemText(index) # 存储已选中省级选项的名称
# 清除之前选择的市级和县级选项
self.combo_city.clear()
self.combo_county.clear()
self.combo_city.addItem("请选择市级")
self.combo_county.addItem("请选择县级")
def on_city_changed(self, index):
self.selected_city_name = self.combo_city.itemText(index) # 存储已选中市级选项的名称
# 清除之前选择的县级选项
self.combo_county.clear()
self.combo_county.addItem("请选择县级")
def on_county_changed(self, index):
self.selected_county_name = self.combo_county.itemText(index) # 存储已选中县级选项的名称
app = QApplication()
window = MainWindow()
window.show()
app.exec()
create_cascading_combobox("行政区划.xlsx")
现在,当选择省、市、县选项时,`self.selected_province_name`、`self.selected_city_name` 和 `self.selected_county_name` 变量中分别储存了对应的名称。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |