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);
QCheckBox *agreeCheck = new QCheckBox("我已阅读并同意服务协议", parent); QPushButton *regBtn = new QPushButton("注册", parent); regBtn->setEnabled(false);
QObject::connect(agreeCheck, &QCheckBox::stateChanged, [regBtn](int state) { regBtn->setEnabled(state == Qt::Checked); });
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(); }
|