用以实现一个读取文件进度条的功能
1.新建一个无ui界面的工程,其基类为dialog对话框类
2.代码实现
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QLabel>
#include <QProgressBar>
#include <QPushButton>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
private slots:
void startProgress(); //定义一个槽函数
private:
QLabel * fileNum; //控件声明
QProgressBar * progressBar; //控件声明
QPushButton * startBtn; //控件声明
};
#endif // DIALOG_H
dialog.cpp
#include "dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
this->setWindowTitle(tr("进度条"));
fileNum = new QLabel(this);
fileNum->setText(tr("复制文件数目:0"));
fileNum->setGeometry(20,10,200,18);
progressBar = new QProgressBar(this);
progressBar->setGeometry(20,35,200,10);
startBtn = new QPushButton(this);
startBtn->setText(tr("开始"));
startBtn->setGeometry(20,55,80,30);
//连接信号与槽
connect(startBtn,SIGNAL(clicked()),this,SLOT(startProgress()));
}
Dialog::~Dialog()
{
}
//槽函数实现
void Dialog::startProgress()
{
progressBar->setRange(0,100000); //设置进度条的范围
for(int i = 1; i <= 100000; i++)
{
progressBar->setValue(i);
QString str = QString("%1").arg(i);
str = "复制文件数目: " +str;
fileNum->setText(str);
}
}
3.效果展示
4.不足与需改进之处
1.进程过快。效果不宜呈现,可以将进度条的值调大一点
2.后面可以引入QTimer定时器功能,以实现文件复制
5.改进之后
progressbar.h
#ifndef PROGRESSBAR_H
#define PROGRESSBAR_H
#include <QMainWindow>
#include <QProgressBar>
class ProgressBar : public QMainWindow
{
Q_OBJECT
public:
ProgressBar(QWidget *parent = 0);
~ProgressBar();
};
//新建类
class QString;
class Progressbar : public QProgressBar
{
Q_OBJECT
public:
Progressbar(QWidget *parent = 0):QProgressBar(parent){}
QString strText;
public slots:
void stepOne();
};
#endif // PROGRESSBAR_H
progressbar.cpp
#include "progressbar.h"
#include <QString>
ProgressBar::ProgressBar(QWidget *parent)
: QMainWindow(parent)
{
}
ProgressBar::~ProgressBar()
{
}
void Progressbar::stepOne()
{
if(this->value()+1 <= this->maximum())
{
this->setValue(this->value() + 1);
strText = "进度条 : " + this->text();
this->setWindowTitle(strText);
}
else
{
this->setValue(this->minimum());
}
}
main.cpp
#include "progressbar.h"
#include <QApplication>
#include <QTimer>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ProgressBar w;
w.show();
//进度条设置
Progressbar * progress = new Progressbar;
progress->setWindowTitle("进度条");
progress->resize(400,40);
progress->setMaximum(100);
progress->setMinimum(0);
progress->setValue(0);
//设置一个定时器
QTimer *timer = new QTimer;
timer->start(500);
QObject::connect(timer, SIGNAL(timeout()), progress, SLOT(stepOne()));
progress->show();
return a.exec();
}