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