QCheckBox类继承自QAbstractButton类。
QCheckBox(复选框)和 QRadioButton(单选钮)都是选项按钮,因为他们都可以在开(选中)挥着关(未选中)之间切换。他们的区别是对用户选择的限制;单选钮提供了“多选一”的选择;而复选框提供的是“多选多”的选择。
QCheckBox类中的常用方法:
setChecked() 设置复选框的状态,设置为True时表示选中复选框,设置为False时表示取消选中复选框
setText() 设置复选框的显示文本
text() 返回复选框的显示文本
isChecked() 检查复选框是否被选中
setTriState() 设置复选框为一个三态复选框
三态复选框有三种状态
Qt.Checked 2 组件没有被选中(默认值)
Qt.PartiallyChecked 1 组件被半选中
Qt.Unchecked 0 组件被选中
案例16 QCheckBox按钮的使用
import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import * from PyQt5.QtWidgets import QWidget, QApplication, QCheckBox, QGroupBox, QHBoxLayout, QVBoxLayout class CheckBoxDemo(QWidget): def __init__(self, parent=None): super().__init__(parent) groupbox = QGroupBox("Checkboxes") groupbox.setFlat(True) layout = QHBoxLayout() self.checkbox1 = QCheckBox("&Checkbox1") # 为checkBox1设置快捷键,通过“Alt+C”可以选择checkbox1复选框 self.checkbox1.setChecked(True) self.checkbox1.stateChanged.connect(lambda: self.btnstate(self.checkbox1)) layout.addWidget(self.checkbox1) self.checkbox2 = QCheckBox("Checkbox2") self.checkbox2.toggled.connect(lambda: self.btnstate(self.checkbox2)) layout.addWidget(self.checkbox2) self.checkbox3 = QCheckBox("Checkbox3") self.checkbox3.setTristate(True) # 开启三态模式 self.checkbox3.setCheckState(Qt.PartiallyChecked) self.checkbox3.stateChanged.connect(lambda: self.btnstate(self.checkbox3)) layout.addWidget(self.checkbox3) groupbox.setLayout(layout) mainlayout = QVBoxLayout() mainlayout.addWidget(groupbox) self.setLayout(mainlayout) self.setWindowTitle("CheckBox Demo") def btnstate(self, btn): chk1status = (self.checkbox1.text() + ", is Checked = " + str(self.checkbox1.isChecked()) + ", is checkState = " + str(self.checkbox1.checkState()) + " ") chk2status = (self.checkbox2.text() + ", is Checked = " + str(self.checkbox2.isChecked()) + ", is checkState = " + str(self.checkbox2.checkState()) + " ") chk3status = (self.checkbox3.text() + ", is Checked = " + str(self.checkbox3.isChecked()) + ", is checkState = " + str(self.checkbox3.checkState()) + " ")
print(chk1status + chk2status + chk3status) if __name__ == "__main__": app = QApplication(sys.argv) checkboxdemo = CheckBoxDemo() checkboxdemo.show() sys.exit(app.exec_())