qt QRadioButton详解

**QRadioButton**是一个可以切换选中(checked)或未选中(unchecked)状态的选项按钮。单选按钮通常呈现给用户一个"多选一"的选择,即在一组单选按钮中,一次只能选中一个按钮。

重要方法

  • QRadioButton(QWidget* parent = nullptr):默认构造函数。
  • QRadioButton(const QString& text, QWidget* parent = nullptr):使用指定的文本创建单选按钮。
  • void setText(const QString& text):设置单选按钮显示的文本。
  • void setChecked(bool checked):设置单选按钮的选中状态,true为选中,false为未选中。
  • bool isChecked() const:返回单选按钮的选中状态,如果选中则返回true,否则返回false。
  • void setIcon(const QIcon& icon):设置单选按钮显示的图标。
  • void setShortcut(const QKeySequence& shortcut):设置单选按钮的快捷键。

重要信号

  • toggled(bool checked):当单选按钮切换选中状态时发射,参数为是否选中。

  • clicked(bool checked):当单选按钮被点击时发射,参数为是否选中。

    #include <QApplication>
    #include <QWidget>
    #include <QHBoxLayout>
    #include <QRadioButton>
    #include <QButtonGroup>

    int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    复制代码
      // 创建主窗口  
      QWidget window;  
      window.setWindowTitle("RadioButton 示例");  
    
      // 创建水平布局  
      QHBoxLayout* layout = new QHBoxLayout(&window);  
    
      // 创建按钮组  
      QButtonGroup* buttonGroup = new QButtonGroup(&window);  
    
      // 创建三个单选按钮  
      QRadioButton* radioBtn1 = new QRadioButton("选项1");  
      QRadioButton* radioBtn2 = new QRadioButton("选项2");  
      QRadioButton* radioBtn3 = new QRadioButton("选项3");  
    
      // 默认设置第一个单选按钮选中  
      radioBtn1->setChecked(true);  
    
      // 将单选按钮添加到按钮组中  
      buttonGroup->addButton(radioBtn1);  
      buttonGroup->addButton(radioBtn2);  
      buttonGroup->addButton(radioBtn3);  
    
      // 将按钮组的 exclusive 属性设置为 true, 确保只能选中一个选项  
      buttonGroup->setExclusive(true);  
    
      // 将单选按钮添加到布局中  
      layout->addWidget(radioBtn1);  
      layout->addWidget(radioBtn2);  
      layout->addWidget(radioBtn3);  
    
      // 设置主窗口的布局  
      window.setLayout(layout);  
    
      // 显示主窗口  
      window.show();  
    
      return app.exec();  

    }

觉得有帮助的话,打赏一下呗。。

相关推荐
哈市雪花4 小时前
相机:以鼠标点为中心缩放(使用OpenGL+QT开发三维CAD)
qt·相机·opengl·cad·缩放·工业软件·渲染效果
Tony小周7 小时前
实现一个点击输入框可以弹出的数字软键盘控件 qt 5.12
开发语言·数据库·qt
雨落倾城夏未凉13 小时前
8.Qt文件操作
c++·后端·qt
TechNomad18 小时前
Qt开发:QtConcurrent介绍和使用
qt
十秒耿直拆包选手1 天前
Qt:主窗体(QMainwindow)初始化注意事项
c++·qt
-凌凌漆-1 天前
【Qt】Qt QML json处理
开发语言·qt·json
海天鹰2 天前
Qt:图片切割
qt
做一个坚强的女汉子2 天前
QT保存日志到文件中以及捕捉崩溃日志
开发语言·qt
顾苏洋19902 天前
qt绘制饼状图并实现点击即放大点击部分
开发语言·qt
笑鸿的学习笔记2 天前
qt-C++笔记之布局管理`space` 和 `margin`的区别
c++·笔记·qt