PyQt5 – 复选框选中状态取决于另一个复选框
有时在创建 GUI(图形用户界面)应用程序时需要制作很多复选框,并且某些复选框取决于前一个复选框,例如有两个以下复选框第一个复选框是“你有笔记本电脑吗? ”第二个复选框是
“你的笔记本电脑有 i7 处理器吗?”在这里我们可以看到,如果第一个复选框为真,那么只有第二个复选框可以为真。
因此,为了克服这种依赖关系,如果未选中第一个复选框,我们必须停止第二个复选框以进行检查。当第一个复选框被选中时,只有用户可以选中第二个复选框。
In order to do this we have to do the following:
1. Create two check boxes.
2. Set second check box check-able state to False i.e by default it can’t get checked.
3. Add action to first check box i.e when state of first check box changes call the associated method with it.
4. Inside the action method check if the first check box is checked.
5. If first check box is checked then make second check box check-able state to True i.e now it can get checked.
6. If first check box is unchecked make second check box state to uncheck and make it uncheck-able.
下面是实现。
# importing libraries
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.setGeometry(100, 100, 600, 400)
# calling method
self.UiComponents()
# showing all the widgets
self.show()
# method for widgets
def UiComponents(self):
# creating the check-box
self.checkbox1 = QCheckBox('Geek ?', self)
# setting geometry of check box
self.checkbox1.setGeometry(200, 150, 100, 40)
# adding action to check box
self.checkbox1.stateChanged.connect(self.allow)
# creating the check-box
self.checkbox2 = QCheckBox('Geeky Geek ?', self)
# setting geometry of check box
self.checkbox2.setGeometry(200, 180, 100, 40)
# stooping check box to get checked
self.checkbox2.setCheckable(False)
# method called by checkbox1
def allow(self):
# checking if checkbox1 is checked ?
if self.checkbox1.isChecked():
# allow second check box to get checked
self.checkbox2.setCheckable(True)
# first check box is unchecked
else:
# make second check box unchecked
self.checkbox2.setCheckState(0)
# make second check box uncheckable
self.checkbox2.setCheckable(False)
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出 :