依赖下拉菜单,其值基于字典[重复]

问题描述 投票:0回答:1

我在根据字典值创建依赖下拉列表时遇到问题,我对 Python 很陌生,但有 SAS、SQL、VBA 和次要 HTML 的经验。我能够将 Excel 表格导入到 Python 中使用,当我打印它时,结果如下:

{'one':['Blue', 'Green'],'two':['Green','Red'],'three':['Orange']}

我想做的是将其变成两个下拉菜单,第一个有选项:

一个
两个

然后关联的值填充第二个下拉列表。例如,如果选择“两个”,我希望“绿色”和“红色”成为可用选项。

我使用 Python 3.12、Pandas 和 Qt6 来执行此操作。

我尝试在线搜索多天,不幸的是,不断遇到各种错误。我无法发布我正在使用的代码,因为这是用于工作的,因此是专有的(我实际上是在家工作,并从我的家用电脑上发布这个问题,因为我的工作阻止了大多数网站)。我能够将钥匙拉入第一个下拉菜单,但这只是我成功获得的。我知道如果没有代码,就很难完全回答,我希望如果有人知道使用该字典来解决这个问题的基本方法,我应该能够对其进行逆向工程以与我现有的代码一起使用。

python pyqt6 qcombobox
1个回答
0
投票

您可以使用

addItems()
方法将选项添加到组合框 所以你的代码将是这样的

self.data = {'one':['Blue', 'Green'],'two':['Green','Red'],'three':['Orange']}
self.combobox = QComboBox()
self.combobox.addItems(data.keys())
self.combobox2 = QComboBox()

好吧

data.keys()
返回字典中的键列表 当所选项目发生变化时,您可以设置这样的信号

self.combobox.currentTextChanged.connect(self.myfunc)

myfunc
会是这样的

def myfunc(self,selectedText):
    self.combobox2.additems(self.data[selectedText])

因此,当第一个组合框更改时,第二个组合框也会更改,但您应该确保在设置任何项目之前清除第二个组合框,为此您可以使用

clear
这样的方法

def myfunc(self,selectedText):
    self.combobox2.clear()
    self.combobox2.additems(self.data[selectedText])

这是我制作的完整示例,看看它的用词如何

from PyQt6.QtWidgets import QComboBox, QMainWindow, QApplication, QWidget, QVBoxLayout
import sys


class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.data = {'one':['Blue', 'Green'],'two':['Green','Red'],'three':['Orange']}
        self.combobox = QComboBox()
        self.combobox.addItems(self.data.keys()) # self.data.keys() returns -> ['one', 'two', 'three']
        self.combobox2 = QComboBox()
        # i added this line becuse first key is selected by defulte
        self.combobox2.addItems(self.data[self.combobox.currentText()])

        layout = QVBoxLayout()
        layout.addWidget(self.combobox)
        layout.addWidget(self.combobox2)
        
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
        
        self.combobox.currentTextChanged.connect(self.changeSecondCombobox)
        
    def changeSecondCombobox(self,selectedText):
        self.combobox2.clear()
        self.combobox2.addItems(self.data[selectedText])
        


app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec()
© www.soinside.com 2019 - 2024. All rights reserved.