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

时间:2018-06-10 10:17:27

标签: python checkbox pyqt5 pyside2 uncheck

我有一系列复选框(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)

1 个答案:

答案 0 :(得分:1)

试一试:

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