Search code examples
pythoncheckboxpyqt5pyside2

one checkbox that uncheck all other checkboxes in PyQt5 / PySide2


I have a series of checkboxes (P1, P2, P3) an I want that the selected checkbox uncheck the others. The code below works, but as I have in the application a total of 12 checkboxes, it takes around 200 lines of codes. Simplifying the code would reduce the number of lines (1075 in total) and hopefully reduce the time that the application is taking to launch (presently 35 sec)

self.checkbox_P1= QtWidgets.QCheckBox("P1",self)
self.checkbox_P1.clicked.connect(self.P_uncheck_others)
self.checkbox_P2= QtWidgets.QCheckBox("P2",self)
self.checkbox_P2.clicked.connect(self.P_uncheck_others)
self.checkbox_P3= QtWidgets.QCheckBox("P3",self)
self.checkbox_P3.clicked.connect(self.P_uncheck_others)

def P_uncheck_others(self):

    sender = self.sender()

    if sender.text() == "P1":
            # self.checkbox_P1.setChecked(False)
            self.checkbox_P2.setChecked(False)
            self.checkbox_P3.setChecked(False)
    elif sender.text() == "P2":
            self.checkbox_P1.setChecked(False)
            # self.checkbox_P2.setChecked(False)
            self.checkbox_P3.setChecked(False)
    elif sender.text() == "P2":
            self.checkbox_P1.setChecked(False)
            self.checkbox_P2.setChecked(False)
            # self.checkbox_P3.setChecked(False)

Solution

  • Try it:

    import sys
    from PyQt5.QtGui     import *
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore    import *
    
    class CheckBoxDemo(QWidget):
        def __init__(self, parent=None):
            super(CheckBoxDemo , self).__init__(parent)
            self.groupBox = QGroupBox("Checkboxes")
            self.groupBox.setFlat(False)
            self.layout = QVBoxLayout()          
            self.groupBox.setLayout(self.layout)
            mainLayout = QVBoxLayout()
            mainLayout.addWidget(self.groupBox)
            self.setLayout(mainLayout)
            self.setWindowTitle("checkbox demo")
    
            self.add_checkbox()
    
        def add_checkbox(self):
            for i in range(0, 12):
                for j in range(1):
                    self.check_boxes = QCheckBox("P{}".format(i+1))
                    self.layout.addWidget(self.check_boxes)
                    self.check_boxes.clicked.connect(self.count_checkbox)
    
        def count_checkbox(self):
            sender = self.sender()
            for i in range(self.layout.count()):
                self.current_checkbox = self.layout.itemAt(i)
                if self.current_checkbox.widget().isChecked() and self.current_checkbox.widget() != sender: 
                    self.current_checkbox.widget().setChecked(False)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        checkboxDemo = CheckBoxDemo()
        checkboxDemo.show()
        sys.exit(app.exec_())
    

    enter image description here