PyQt5 – 复选框的检查状态取决于另一个复选框

PyQt5 – 复选框的检查状态取决于另一个复选框

有时在创建GUI(图形用户界面)应用程序时,需要制作很多复选框,有些复选框取决于前一个复选框,例如有两个复选框,第一个复选框是 “你有笔记本电脑吗?”,第二个复选框是 “你的笔记本电脑有i7处理器?”这里我们可以看到,如果第一个复选框是真的,那么只有第二个复选框才是真的。所以为了克服这种依赖性,如果第一个复选框没有被选中,我们必须阻止第二个复选框被选中。当第一个复选框被选中时,只有用户可以选中第二个复选框。

为了 做到这一点,我们必须做以下工作:

  1. 创建两个复选框。

  2. 将第二个复选框的可检查状态设置为 “假”,即在默认情况下它不能被检查。

  3. 为第一个复选框添加动作,即当第一个复选框的状态改变时,调用与之相关的方法。

  4. 在动作方法中检查第一个复选框是否被选中。

  5. 如果第一个复选框被选中,那么让第二个复选框的可检查状态为真,即现在它可以被检查。
  6. 如果第一个复选框未被选中,则将第二个复选框的状态设为uncheck,使其不能被选中。

下面是实现的过程。

# 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)
 
        # stopping 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())

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程