QCheckBox

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <QApplication>
#include <QWidget>
#include <QCheckBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QDebug>

void setupCheckBoxDemo(QWidget *parent) {
QVBoxLayout *layout = new QVBoxLayout(parent);

// --- 1. 基础用法:开关控制 ---
QCheckBox *agreeCheck = new QCheckBox("我已阅读并同意服务协议", parent);
QPushButton *regBtn = new QPushButton("注册", parent);
regBtn->setEnabled(false); // 初始状态禁用按钮

// 逻辑:只有勾选了协议,注册按钮才可用
QObject::connect(agreeCheck, &QCheckBox::stateChanged, [regBtn](int state) {
// state 的值:Qt::Unchecked (0), Qt::Checked (2)
regBtn->setEnabled(state == Qt::Checked);
});

// --- 2. 进阶用法:三态复选框 (Tristate) ---
// 常用于“全选”按钮:部分选中、全部选中、未选中
QCheckBox *triCheck = new QCheckBox("开启高级选项(支持半选)", parent);
triCheck->setTristate(true);

QLabel *statusLabel = new QLabel("当前状态:未选中", parent);

QObject::connect(triCheck, &QCheckBox::stateChanged, [statusLabel](int state) {
if (state == Qt::Checked) {
statusLabel->setText("当前状态:已选中 (Checked)");
} else if (state == Qt::PartiallyChecked) {
statusLabel->setText("当前状态:半选中 (PartiallyChecked)");
} else {
statusLabel->setText("当前状态:未选中 (Unchecked)");
}
});

layout->addWidget(new QLabel("<h3>注册流程演示:</h3>"));
layout->addWidget(agreeCheck);
layout->addWidget(regBtn);
layout->addSpacing(20);
layout->addWidget(new QLabel("<h3>三态逻辑演示:</h3>"));
layout->addWidget(triCheck);
layout->addWidget(statusLabel);
layout->addStretch();
}

int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QWidget w;
w.setWindowTitle("QCheckBox 交互演示");
w.resize(350, 300);
setupCheckBoxDemo(&w);
w.show();
return a.exec();
}