取消选中 PyQt5 / PySide2 中所有其他复选框的一个复选框

one checkbox that uncheck all other checkboxes in PyQt5 / PySide2

我有一系列复选框(P1、P2、P3),我希望选中的复选框取消选中其他复选框。下面的代码有效,但因为我在应用程序中总共有 12 个复选框,所以它需要大约 200 行代码。简化代码将减少行数(总共 1075 行)并有望减少应用程序启动所需的时间(目前为 35 秒)

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)

试一试:

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