PyQt5 – 在一组复选框中选择任何一个复选框
当我们做一个表单,并且有多个复选框。我们可以选择其中的一些,也可以只选择其中的一个,因为它们之间是相互矛盾的。所以GUI(图形用户界面)阻止我们选择一个以上的复选框,如果我们选择了一个以上的复选框,就会使其他复选框不被选中。
在这篇文章中,我们将看到如何制作一组复选框,以便我们可以选择其中的任何一个。如果我们试图选择其他复选框,它将自动使其他复选框取消选择。
为了 做到这一点,我们必须做到以下几点
1.创建一个复选框组。
2.2. 为每个复选框连接一个方法,以便每次复选框的状态发生变化时,该方法就会被调用。
3.该方法应检查状态是否被选中,如果状态未被选中则不做任何事情。
4.如果状态是勾选的,检查这个方法是由哪个复选框调用的。
5.使所有其他的复选框都不被选中。
下面是实现方法。
# importing libraries
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
# main window class
class Window(QMainWindow):
# constructor
def __init__(self):
super().__init__()
# calling the method for widgets
self.initUI()
def initUI(self):
# creating check box
self.checkBoxNone = QCheckBox("Don't know ?", self)
# setting geometry
self.checkBoxNone.setGeometry(200, 150, 100, 30)
# creating check box
self.checkBoxA = QCheckBox("Geek", self)
# setting geometry
self.checkBoxA.setGeometry(200, 180, 100, 30)
# creating check box
self.checkBoxB = QCheckBox(" Not a geek ?", self)
# setting geometry
self.checkBoxB.setGeometry(200, 210, 100, 30)
# calling the uncheck method if any check box state is changed
self.checkBoxNone.stateChanged.connect(self.uncheck)
self.checkBoxA.stateChanged.connect(self.uncheck)
self.checkBoxB.stateChanged.connect(self.uncheck)
# setting window title
self.setWindowTitle('Python')
# setting geometry of window
self.setGeometry(100, 100, 600, 400)
# showing all the widgets
self.show()
# uncheck method
def uncheck(self, state):
# checking if state is checked
if state == Qt.Checked:
# if first check box is selected
if self.sender() == self.checkBoxNone:
# making other check box to uncheck
self.checkBoxA.setChecked(False)
self.checkBoxB.setChecked(False)
# if second check box is selected
elif self.sender() == self.checkBoxA:
# making other check box to uncheck
self.checkBoxNone.setChecked(False)
self.checkBoxB.setChecked(False)
# if third check box is selected
elif self.sender() == self.checkBoxB:
# making other check box to uncheck
self.checkBoxNone.setChecked(False)
self.checkBoxA.setChecked(False)
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())