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 60 61 62 63 64 65 66 67 68 69 70
| #include <QApplication> #include <QWidget> #include <QRadioButton> #include <QGroupBox> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QDebug>
void setupRadioButtonDemo(QWidget *parent) { QVBoxLayout *mainLayout = new QVBoxLayout(parent);
QGroupBox *genderGroup = new QGroupBox("性别选择", parent); QHBoxLayout *genderLayout = new QHBoxLayout(genderGroup);
QRadioButton *maleBtn = new QRadioButton("男", genderGroup); QRadioButton *femaleBtn = new QRadioButton("女", genderGroup); QRadioButton *otherBtn = new QRadioButton("保密", genderGroup);
maleBtn->setChecked(true);
genderLayout->addWidget(maleBtn); genderLayout->addWidget(femaleBtn); genderLayout->addWidget(otherBtn);
QGroupBox *diffGroup = new QGroupBox("游戏难度", parent); QVBoxLayout *diffLayout = new QVBoxLayout(diffGroup);
QRadioButton *easyBtn = new QRadioButton("简单 (Easy)", diffGroup); QRadioButton *hardBtn = new QRadioButton("困难 (Hard)", diffGroup);
diffLayout->addWidget(easyBtn); diffLayout->addWidget(hardBtn);
QLabel *statusLabel = new QLabel("当前选择:男 | 未设难度", parent); statusLabel->setStyleSheet("color: blue; font-weight: bold;");
auto updateStatus = [=]() { QString gender = maleBtn->isChecked() ? "男" : (femaleBtn->isChecked() ? "女" : "保密"); QString diff = easyBtn->isChecked() ? "简单" : (hardBtn->isChecked() ? "困难" : "未设"); statusLabel->setText(QString("当前选择:%1 | 难度:%2").arg(gender).arg(diff)); };
QObject::connect(maleBtn, &QRadioButton::toggled, updateStatus); QObject::connect(femaleBtn, &QRadioButton::toggled, updateStatus); QObject::connect(otherBtn, &QRadioButton::toggled, updateStatus); QObject::connect(easyBtn, &QRadioButton::toggled, updateStatus); QObject::connect(hardBtn, &QRadioButton::toggled, updateStatus);
mainLayout->addWidget(genderGroup); mainLayout->addWidget(diffGroup); mainLayout->addWidget(statusLabel); mainLayout->addStretch(); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; w.setWindowTitle("QRadioButton 互斥选择演示"); w.resize(350, 400); setupRadioButtonDemo(&w); w.show(); return a.exec(); }
|