PyQt5 - 在一组复选框中选择任何一个复选框
当我们制作一个表格并且有多个复选框时。我们可以选择其中一些或只选择其中一个,因为它们相互矛盾。所以 GUI(图形用户界面)阻止我们选择多个复选框,如果我们选择多个复选框,它会使其他复选框未选中。
在本文中,我们将看到如何制作一组复选框,以便我们可以选择其中任何一个。如果我们尝试选择另一个复选框,它会自动取消选中其他复选框。
In order to do this we have to do the following –
1. Create a group of check box.
2. For each check box connect a method such that every time state of check box get changed that method should get called.
3. That method should check if the state is checked, if the state is unchecked do nothing.
4. If the state is checked, check by which check box this method is called.
5. Make all other check boxes to unchecked.
下面是实现。
# 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())
输出 :