Qt-QRadioButton

 qradiobuttontest.h

#pragma once

#include 
#include "ui_qradiobuttontest.h"

class QRadioButtonTest : public QWidget
{
    Q_OBJECT

public:
    QRadioButtonTest(QWidget *parent = Q_NULLPTR);
public slots:
    void Save();
private:
    Ui::QRadioButtonTestClass ui;
};

  qradiobuttontest.cpp

#include "qradiobuttontest.h"
#include 
#include 
#include 
#include 
#include 
QRadioButtonTest::QRadioButtonTest(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    QRadioButton* rb1 = new QRadioButton("QRadioButton1");
    QRadioButton* rb2 = new QRadioButton("QRadioButton2");
    QRadioButton* rb3 = new QRadioButton("QRadioButton3");

    //按钮组
    QButtonGroup* group = new QButtonGroup(this);
    group->setObjectName("group");  //设置按钮组名字
    group->addButton(rb1);
    group->addButton(rb2);
    group->addButton(rb3);

    //垂直布局器
    QVBoxLayout* vb = new QVBoxLayout(this);

    //遍历按钮组
    for (int i = 0; i < group->buttons().size(); i++)
    {
        vb->addWidget(group->buttons()[i]);
    }
    //保存按钮
    QPushButton* save = new QPushButton("Save");
    vb->addWidget(save);

    QObject::connect(save,SIGNAL(clicked()),this,SLOT(Save()));
}
void QRadioButtonTest::Save()
{
    //获取按钮组
    QButtonGroup* group = this->findChild("group");
    if (!group) return;

    //获取按钮组中选中的按钮,向上转型相当于在做筛选
    QRadioButton* but = (QRadioButton*)group->checkedButton();
    if (!but)
    {
        QMessageBox::warning(this, "", "please checked!");
        return;
    }

    QMessageBox::information(this, "", but->text());
}

Qt-QRadioButton_第1张图片

 

你可能感兴趣的:(C++,qt,c++,qt5)