以下是一个简单的Qt中Radio Button的实例:
main.cpp:
#include <QApplication>
#include "radiobutton.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
RadioButton w;
w.show();
return a.exec();
}
radiobutton.h:
#ifndef RADIOBUTTON_H
#define RADIOBUTTON_H
#include <QWidget>
#include <QRadioButton>
#include <QHBoxLayout>
class RadioButton : public QWidget
{
Q_OBJECT
public:
RadioButton(QWidget *parent = nullptr);
private:
QRadioButton *maleButton;
QRadioButton *femaleButton;
};
#endif // RADIOBUTTON_H
radiobutton.cpp:
#include "radiobutton.h"
RadioButton::RadioButton(QWidget *parent)
: QWidget(parent)
{
maleButton = new QRadioButton("Male", this);
femaleButton = new QRadioButton("Female", this);
QHBoxLayout *hbox = new QHBoxLayout(this);
hbox->addWidget(maleButton);
hbox->addWidget(femaleButton);
setLayout(hbox);
}
在这个例子中,我们创建了一个简单的窗口,其中包含两个Radio Button:男性和女性。使用QHBoxLayout将它们放在一行中。
当用户点击其中一个按钮时,可以使用isChecked()
函数来检查哪个按钮被选中。例如:
if (maleButton->isChecked()) {
qDebug() << "Male button is checked!";
} else if (femaleButton->isChecked()) {
qDebug() << "Female button is checked!";
}