001-radioButton关联id

方法1:使用 setProperty() 动态绑定

#include <QApplication>
#include <QRadioButton>
#include <QWidget>
#include <QVariant>

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    QWidget widget;

    // 创建两个单选按钮
    QRadioButton *radioYes = new QRadioButton("是", &widget);
    QRadioButton *radioNo = new QRadioButton("否", &widget);

    // 存储自定义数据
    radioYes->setProperty("value", 1);
    radioYes->setProperty("isActive", true);
    
    radioNo->setProperty("value", 0);
    radioNo->setProperty("isActive", false);

    // 读取数据(例如在槽函数中)
    QObject::connect(radioYes, &QRadioButton::toggled, [radioYes](bool checked) {
        if (checked) {
            int value = radioYes->property("value").toInt();
            bool isActive = radioYes->property("isActive").toBool();
            qDebug() << "Value: " << value << ", Active: " << isActive;
        }
    });

    widget.show();
    return a.exec();
}

方法2:使用 QButtonGroup 进行映射(适合单选互斥组)

#include <QButtonGroup>
#include <QRadioButton>

// 在窗口的构造函数中初始化
{
    QButtonGroup *group = new QButtonGroup(this);
    QRadioButton *rbtOption1 = new QRadioButton("选项1", this);
    QRadioButton *rbtOption2 = new QRadioButton("选项2", this);
    QRadioButton *rbtOption3 = new QRadioButton("选项3", this);

    // 将按钮添加到组中,并分配ID
    group->addButton(rbtOption1, 0); // 按钮对应ID 0
    group->addButton(rbtOption2, 1); // 按钮对应ID 1
    group->addButton(rbtOption3, 2); // 按钮对应ID 2

    // 连接组的信号,以获取选中的ID
    //在qt5.15中buttonClicked方法已被弃用,使用idClicked代替
    QObject::connect(group, QOverload<int>::of(&QButtonGroup::idClicked), 
        [](int id) {
            qDebug() << "Selected button ID:" << id;
            // 根据ID执行不同操作
        });
}

方法3:自定义类拓展功能

// 1. 定义 MyRadioButton 类
// MyRadioButton.h
#include <QRadioButton>

class MyRadioButton : public QRadioButton {
    Q_OBJECT
public:
    explicit MyRadioButton(const QString &text, int id, QWidget *parent = nullptr) 
        : QRadioButton(text, parent), m_id(id) {}

    int id() const { return m_id; }
    void setId(int id) { m_id = id; }

    // 如果需要存储更复杂的数据,可以在这里添加成员变量和方法

private:
    int m_id; // 存储自定义ID
};

// 2. 使用 MyRadioButton
// main.cpp 或某个窗口类的构造函数中
{
    MyRadioButton *opt1 = new MyRadioButton("选项 A", 101, this);
    MyRadioButton *opt2 = new MyRadioButton("选项 B", 102, this);
    MyRadioButton *opt3 = new MyRadioButton("选项 C", 103, this);

    // 使用信号槽处理
    QObject::connect(opt1, &MyRadioButton::toggled, [opt1](bool checked) {
        if (checked) {
            qDebug() << "Selected Option ID:" << opt1->id();
        }
    });
}