0

I am trying to auto-populate a list of exclusive checkboxes where the number of checkboxes changes according the the option chosen in QComboBox.

I'm stuck at the portion of how to remove the initially appended widgets in the layout and replace them with the new widgets.

For example, if the menu item -food is chosen, 3 checkboxes ('good2eat', 'macs', 'popeyes') will be shown and if drinks is chosen, those 3 checkboxes will be removed and replaced with 'water', 'tea' options

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

Even so, at the start of the code, the number of options populated under the menu item food is already wrong.

Is there a better way that I can handle this??

Teh Ki
  • 455
  • 1
  • 3
  • 14

1 Answers1

0

Try it:

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

S. Nick
  • 12,879
  • 8
  • 25
  • 33