在上篇文章网页浏览实的的基础上,实现一般页面文件的下载,并且显示下载进度。进入设计模式, 向界面上拖入Label、Line Edit、Progress Bar和Push Button等部件。
首先,在“mainwindow.h”文件中添加头文件和类的前置声明:
#include <QUrl>
class QFile;
其次,添加如下私有槽声明:
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64,qint64);
再添加一个public()函数声明:
void startRequest(QUrl url);
再次,添加几个私有对象定义:
QNetworkReply *reply;
QUrl url;
QFile *file;
在“mainwindow.cpp”文件中,在构造函数中添加:
ui->progressBar->hide();
这里开始将进度条隐藏了,因此在没有下载文件时是不显示进度条的。
接下来添加几个新函数,首先添加网络请求函数的实现:
void MainWindow::startRequest(QUrl url)
{
reply = manager->get(QNetworkRequest(url));
connect(reply,SIGNAL(readyRead()),this,SLOT(httpReadyRead()));
connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this
,SLOT(updateDataReadProgress(qint64,qint64)));
connect(reply,SIGNAL(finished()),this,SLOT(httpFinished()));
}
下面添加几个槽的定义:
void MainWindow::httpReadyRead()
{
if(file)file->write(reply->readAll());
}
这里首先判断是否创建了文件。如果是,则读取返回的所有数据,然后写入文件中。该文件是在后面的“下载”按钮的单击信号的槽中创建并打开的。
void MainWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(bytesRead);
}
这里设置了进度条的最大值和当前值。
void MainWindow::httpFinished()
{
ui->progressBar->hide();
file->flush();
file->close();
reply->deleteLater();
reply = 0;
delete file;
file = 0;
}
进入设计模式,进入“下载”按钮的单击信号的槽,添加如下代码:
void MainWindow::on_pushButton_clicked()
{
url = ui->lineEdit->text();
QFileInfo info(url.path());
QString fileName(info.fileName());
file = new QFile(fileName);
if(!file->open(QIODevice::WriteOnly))
{
qDebug()<<"file open error";
delete file;
file = 0;
return;
}
startRequest(url);
ui->progressBar->setValue(0);
ui->progressBar->show();
}
最终效果如下图所示,可以输入一个网络文件地址,单击“下载”按钮将其下载到本地。下载完成后,可在项目工程所在路径的build-myHTTP-Desktop_Qt_5_9_0_MinGW_32bit-Debug下找到该文件。