根据QCombobox中选择的选项替换相应的复选框

2024-06-27 02:08:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图自动填充一个排他复选框列表,其中复选框的数量根据QComboBox中选择的选项而变化

我被困在如何删除布局中最初附加的小部件并用新的小部件替换它们的部分

例如,如果选择菜单项-food,将显示3个复选框(“good2eat”、“macs”、“popeyes”),如果选择drinks,将删除这3个复选框,并替换为“water”、“tea”选项

class MenuWindow(QtGui.QWidget):
    def __init__(self, dict_items, parent=None):
        super(MenuWindow, self).__init__(parent=parent)

        layout = QtGui.QVBoxLayout()
        self.checkbox_options = {}
        self.menu_tag_dict = defaultdict(set)

        self.menu_combos = QtGui.QComboBox()
        self.menu_combos.currentIndexChanged.connect(self.get_selections)
        self.chkbox_group = QtGui.QButtonGroup()

        for menu_name, submenu_name in dict_items.items():
            self.menu_combos.addItems([menu_name])

            if submenu_name:
                sub_txt = [m for m in submenu_name]
                for s in sub_txt:
                    sub_chk = QtGui.QCheckBox(s)
                    self.checkbox_options[menu_name] = sub_chk
                    self.chkbox_group.addButton(sub_chk)

        print_btn = QtGui.QPushButton('Print selected')

        layout.addWidget(self.menu_combos)
        for s in self.checkbox_options.values():
            layout.addWidget(s)

        layout.addWidget(get_sel_btn)
        layout.addStretch()

        self.setLayout(layout)
        self.show()

    def get_selections(self):
        # Get combobox text
        combo_text = self.menu_combos.currentText()
        # get the menus
        items = self.menu_combos.get(combo_text)



my_items = {
    'food' : ['good2eat', 'macs', 'popeyes'],
    'drinks': ['water', 'tea']
}

myWin = MenuWindow(my_items)
myWin.show()

即便如此,在代码开始时,在菜单项food下填充的选项数量已经是错误的

有没有更好的办法让我处理这个问题


Tags: nameinselfforgetfood选项items
1条回答
网友
1楼 · 发布于 2024-06-27 02:08:09

试试看:

import sys
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *

class MenuWindow(QWidget):
    def __init__(self, dict_items, parent=None):
        super(MenuWindow, self).__init__(parent=parent)

        self.dict_items = dict_items

        self.menu_combos = QComboBox()
        self.menu_combos.currentIndexChanged[str].connect(self.get_selections)
        self.menu_combos.addItems(sorted(self.dict_items.keys()))

        print_btn = QPushButton('Print selected')        # ! Print selected
        print_btn.clicked.connect(self.printSelected)    # ! Print selected

        self.layoutV = QVBoxLayout()
        self.layoutV.addWidget(self.menu_combos)

        for s in self.dict_items[self.menu_combos.currentText()]:
            self.sub_chk = QCheckBox(s)
            self.layoutV.addWidget(self.sub_chk)    

        self.layoutV.addStretch()
        self.layoutV.addWidget(print_btn)                # ! Print selected

        self.setLayout(self.layoutV)
        self.show()

    @pyqtSlot(str)
    def get_selections(self, text):

        if self.layout():
            countLayout = self.layout().count()
            for it in range(countLayout - 3):             # < - removeWidget
                w = self.layout().itemAt(1).widget()
                self.layout().removeWidget(w)     
                w.hide()

            for s in self.dict_items[text][::-1]:         # < - insertWidge
                self.sub_chk = QCheckBox(s)
                self.layoutV.insertWidget(1, self.sub_chk) 

    def printSelected(self):                              # ! Print selected
        checked_list = []
        for i in range(1, self.layoutV.count() - 2):
            chBox = self.layoutV.itemAt(i).widget()
            if chBox.isChecked():
                checked_list.append(chBox.text())
        print("selected QCheckBox: " + str(list(checked_list)))  


my_items = {
    'food'  : ['good2eat', 'macs', 'popeyes'],
    'drinks': ['water',    'tea']
}

if __name__ == '__main__':
    import sys
    app  = QApplication(sys.argv)
    myWin = MenuWindow(my_items)
    myWin.setGeometry(300, 150, 250, 250)
    myWin.show()
    sys.exit(app.exec_())

enter image description here

相关问题 更多 >