Qt学习(003-4)复选框

在Qt5.1使用creator创建GUI项目mycheckbox。

建立文件mycheckbox.h:

#ifndef MYCHECKBOX_H
#define MYCHECKBOX_H

#include <QMainWindow>
#include <QStatusBar>
#include <QString>
#include <QCheckBox>
#include <QSize>
#include <QWidget>
#include <QVBoxLayout>

class MyCheckBox : public QMainWindow
{
    Q_OBJECT

public:
    MyCheckBox();

public slots:
    void changeStatus(int );

private:
    QCheckBox *cb1;
    QCheckBox *cb2;
    int cb1State;
    int cb2State;
};

#endif // MYCHECKBOX_H

建立文件mycheckbox.cpp:

#include "mycheckbox.h"

MyCheckBox::MyCheckBox()
    :QMainWindow()
{
    this->cb1 = new QCheckBox("1",this);
    this->cb1->move(20,20);
    this->cb1->setChecked(false);
    this->cb1State = this->cb1->checkState();

    this->cb2 = new QCheckBox("2",this);
    this->cb2->move(20,60);
    this->cb2->setChecked(false);
    this->cb2State = this->cb2->checkState();

    this->statusBar()->showMessage("ready");

    this->connect(this->cb1, SIGNAL(stateChanged(int)),      this, SLOT(changeStatus(int)));
    this->connect(this->cb2, SIGNAL(stateChanged(int)),      this, SLOT(changeStatus(int)));
}

void MyCheckBox::changeStatus(int state)
{
    int who;
    if(this->cb1State != cb1->checkState()) {
        who = 1;
    }
    if(this->cb2State != cb2->checkState()) {
        who = 2;
    }
    if (state == Qt::Checked) {
        this->statusBar()->showMessage( QString::number(who) + "被选中了");
    }
    else {
        this->statusBar()->showMessage(QString::number(who) + "被撤销了");
    }
    this->cb1State = cb1->checkState();
    this->cb2State = cb2->checkState();

}

更改main.cpp:

#include <QApplication>
#include "mycheckbox.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyCheckBox w;

    w.setMinimumSize(QSize(300,200));
    w.setMaximumSize(QSize(300,200));
    w.show();
    return a.exec();
}

运行结果:

Qt学习(003-4)复选框

你可能感兴趣的:(qt)