Qt学习(003-1)进度条

创建项目,新建文件MyProgressBar.h:

#ifndef MYPROGRESSBAR_H
#define MYPROGRESSBAR_H

#include <QWidget>
#include <QHBoxLayout>
#include <QProgressBar>
#include <QPushButton>

class MyProgressBar : public QWidget
{
    Q_OBJECT

public:
    MyProgressBar(QWidget *parent = 0);

public slots:
    void add();
    void subtract();

private:
    QProgressBar *pb;
    QPushButton *buttonAdd;
    QPushButton *buttonSubtract;
    QHBoxLayout *hbox;
    int min;
    int max;

};

#endif // MYPROGRESSBAR_H

新建MyProgressBar.cpp:

#include "MyProgressBar.h"
#include <QtDebug>
MyProgressBar::MyProgressBar(QWidget *parent)
    : QWidget(parent)
{
    this->min = 0;
    this->max = 10;
    this->pb = new QProgressBar();
    this->pb->setMinimum(this->min);
    this->pb->setMaximum(this->max);
    this->pb->setValue(this->min);

    this->buttonAdd = new QPushButton("+");
    this->buttonSubtract = new QPushButton("-");

    connect(this->buttonAdd, SIGNAL(clicked()), this, SLOT(add()));
    connect(this->buttonSubtract, SIGNAL(clicked()), this, SLOT(subtract()));

    this->hbox = new QHBoxLayout();
    this->hbox->addWidget(buttonAdd);
    this->hbox->addWidget(buttonSubtract);
    this->hbox->addWidget(pb);

    this->setLayout(hbox);
}

void MyProgressBar::add()
{
    qDebug() << this->pb->value();
    if(this->pb->value() >= this->max) {
        this->pb->setValue(this->max);
    }
    else {
        this->pb->setValue(this->pb->value() + 1);
    }

}

void MyProgressBar::subtract()
{
    qDebug() << this->pb->value();
    if(this->pb->value() <= this->min) {
        this->pb->setValue(this->min);
    }
    else {
        this->pb->setValue(this->pb->value() - 1);
    }

}

修改main.cpp内容:

#include "mainwindow.h"
#include "MyProgressBar.h"
#include <QApplication>

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

    MyProgressBar *mpb = new MyProgressBar();
    mpb->setWindowTitle("进度条");
    mpb->show();

    return a.exec();
}

运行结果:



你可能感兴趣的:(qt,进度条)