QT5-控件-QCheckBox


#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QButtonGroup>
#include <QCheckBox>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

    QCheckBox* exclusive[3];
    QCheckBox* non_exclusive[3];
public slots:
    void chkChanged();
};

#endif // MAINWINDOW_H
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->resize(270,191); // 重新设置窗体大小
    this->centralWidget(); // 将窗体放置在屏幕中间
    QString str1[] = {"游戏","办公","开发"};
    QString str2[] = {"Programming","Qt","OS"};
    int xpos = 30 ;
    int ypos = 30 ;
    QButtonGroup* chk_group[2]; // 按钮组控件,只是逻辑上的分类而已
    chk_group[0] = new QButtonGroup(this);
    chk_group[1] = new QButtonGroup(this);
    for(int i=0;i<3;i++)
    {
        exclusive[i] = new QCheckBox(str1[i],this);
        exclusive[i]->setGeometry(xpos,ypos,100,30);
        chk_group[0]->addButton(exclusive[i]);

        non_exclusive[i] = new QCheckBox(str2[i],this);
        non_exclusive[i]->setGeometry(xpos+120,ypos,100,30);
        chk_group[1]->addButton(non_exclusive[i]);

        ypos += 40 ;
     }
    chk_group[0]->setExclusive(false); // 单选失能
    chk_group[1]->setExclusive(true); // 单选使能

    exclusive[0]->setIcon(QIcon("res/01.png"));
    exclusive[1]->setIcon(QIcon("res/02.png"));
    exclusive[2]->setIcon(QIcon("res/03.png"));

    non_exclusive[0]->setIcon(QIcon("res/04.png"));
    non_exclusive[1]->setIcon(QIcon("res/05.png"));
    non_exclusive[2]->setIcon(QIcon("res/06.png"));

    connect(exclusive[0],SIGNAL(clicked()),this,SLOT(chkChanged()));
    connect(exclusive[1],SIGNAL(clicked()),this,SLOT(chkChanged()));
    connect(exclusive[2],SIGNAL(clicked()),this,SLOT(chkChanged()));
}

MainWindow::~MainWindow()
{

}

void MainWindow::chkChanged()
{
    for(int i=0 ; i<3 ; i++)
    {
        if(exclusive[i]->checkState())
        {
            qDebug("checkbox %d selected",i+1);
        }
    }
}
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM