4. 复选框与单选按钮
任务目标
使用 Qt Widgets 创建一组复选框(QCheckBox)和单选按钮(QRadioButton),当用户切换选择状态时,实时在标签中显示当前所有选项的组合结果。
界面与交互逻辑
- 复选框组:包含“加糖”“加奶”“加冰”三个选项,可多选,任意切换时更新结果。
- 单选按钮组:包含“小杯”“中杯”“大杯”三个选项,互斥选择,切换时更新结果。
- 结果标签:实时显示当前选中的杯型与所有勾选的配料;若未勾选任何配料,则显示“无配料”。
完整代码(main.cpp)
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QCheckBox>
#include <QRadioButton>
#include <QLabel>
#include <QGroupBox>
#include <QButtonGroup>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget window;
window.setWindowTitle("复选框与单选按钮");
// 创建复选框
QCheckBox *sugarCheck = new QCheckBox("加糖");
QCheckBox *milkCheck = new QCheckBox("加奶");
QCheckBox *iceCheck = new QCheckBox("加冰");
// 创建单选按钮(放入同一布局即自动互斥)
QRadioButton *smallRadio = new QRadioButton("小杯");
QRadioButton *mediumRadio = new QRadioButton("中杯");
QRadioButton *largeRadio = new QRadioButton("大杯");
mediumRadio->setChecked(true); // 默认选中中杯
// 结果标签
QLabel *resultLabel = new QLabel();
resultLabel->setWordWrap(true);
// 复选框组布局
QGroupBox *checkGroup = new QGroupBox("配料选择");
QVBoxLayout *checkLayout = new QVBoxLayout(checkGroup);
checkLayout->addWidget(sugarCheck);
checkLayout->addWidget(milkCheck);
checkLayout->addWidget(iceCheck);
// 单选按钮组布局
QGroupBox *radioGroup = new QGroupBox("杯型选择");
QVBoxLayout *radioLayout = new QVBoxLayout(radioGroup);
radioLayout->addWidget(smallRadio);
radioLayout->addWidget(mediumRadio);
radioLayout->addWidget(largeRadio);
// 更新结果的lambda函数
auto updateResult = [&]() {
QString size;
if (smallRadio->isChecked()) size = "小杯";
else if (mediumRadio->isChecked()) size = "中杯";
else if (largeRadio->isChecked()) size = "大杯";
QStringList toppings;
if (sugarCheck->isChecked()) toppings << "加糖";
if (milkCheck->isChecked()) toppings << "加奶";
if (iceCheck->isChecked()) toppings << "加冰";
QString toppingText = toppings.isEmpty() ? "无配料" : toppings.join("、");
resultLabel->setText(QString("您选择了:%1,%2").arg(size, toppingText));
};
// 连接所有控件的状态变化信号
connect(sugarCheck, &QCheckBox::toggled, updateResult);
connect(milkCheck, &QCheckBox::toggled, updateResult);
connect(iceCheck, &QCheckBox::toggled, updateResult);
connect(smallRadio, &QRadioButton::toggled, updateResult);
connect(mediumRadio, &QRadioButton::toggled, updateResult);
connect(largeRadio, &QRadioButton::toggled, updateResult);
// 主布局
QHBoxLayout *topLayout = new QHBoxLayout;
topLayout->addWidget(checkGroup);
topLayout->addWidget(radioGroup);
QVBoxLayout *mainLayout = new QVBoxLayout(&window);
mainLayout->addLayout(topLayout);
mainLayout->addWidget(resultLabel);
updateResult(); // 初始化显示
window.show();
return app.exec();
}
运行方式
- 在项目文件(.pro)中确认包含
QT += widgets。 - 将上述代码保存为
main.cpp,与项目文件放在同一目录。 - 使用 qmake 生成 Makefile 并编译:
qmake && make(或直接在 Qt Creator 中打开 .pro 文件运行)。
验证方法
- 程序启动后,默认显示“您选择了:中杯,无配料”。
- 勾选“加糖”和“加冰”,结果变为“您选择了:中杯,加糖、加冰”。
- 切换单选按钮为“大杯”,结果同步更新为“您选择了:大杯,加糖、加冰”。
- 取消所有复选框勾选,结果中配料部分恢复为“无配料”。
以上交互无需重新编译即可实时响应,说明信号槽连接与状态读取逻辑正确。