用以实现一个读取文件进度条的功能
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.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.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();
}
6.效果展示
改进版本参考链接:http://blog.chinaunix.net/uid-27225886-id-3352398.html