初识Qt文件下载

1、新建一个Qt Gui应用,项目名称为http,基类选择为QMainWindow,类名设置为MainWindow。

2、在http.pro文件中的QT  += core gui后添加 network,或者直接添加QT  += network。

3、在mainwindow.ui文件中分别拖入label控件、lineEdit控件、pushButton控件以及progressBar控件,如下。

4、在mainwindow.h头文件中添加以下代码,同时添加#include<QtNetwork>

 1 public:
 2     void startRequest(QUrl url);
 3 
 4 private:
 5     QNetworkReply *reply;
 6     QUrl url;//存储网络地址
 7     QFile *file;//文件指针
 8 
 9 private slots:
10     void on_pushButton_clicked();
11     void httpFinished();
12     void httpReadyRead();
13     void updateDataReadProgress(qint64, qint64);

5、在mainwindow.cpp源文件的构造函数中添加代码

1  ui->progressBar->hide();

同时,在mainwindow.cpp源文件中添加以下函数代码

 1 void MainWindow::on_pushButton_clicked()
 2 {
 3     url = ui->lineEdit->text();
 4     QFileInfo info(url.path());
 5     QString fileName(info.fileName());
 6     if (fileName.isEmpty()) fileName = "index.html";
 7     file = new QFile(fileName);
 8     if(!file->open(QIODevice::WriteOnly))//打开成功返回true,否则返回false
 9     {
10         qDebug() << "file open error";
11         delete file;
12         file = 0;
13         return;
14     }
15     startRequest(url);
16     ui->progressBar->setValue(0);
17     ui->progressBar->show();
18 }
19 
20 void MainWindow::startRequest(QUrl url)
21 {
22     QNetworkAccessManager *manager;
23     manager = new QNetworkAccessManager(this);
24     reply = manager->get(QNetworkRequest(url));
25     connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead()));//readyRead()信号继承自QIODevice类,每当有新的数据可以读取时,都会发射该信号
26     connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateDataReadProgress(qint64, qint64)));//每当网络请求的下载进度更新时都会发射downloadProgress()信号
27     connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));//每当应答处理结束时,都会发射finished()信号
28 }
29 
30 void MainWindow::httpReadyRead()
31 {
32     if (file)
33         file->write(reply->readAll());//如果创建了文件,则读取返回的所有数据,然后写入到文件。
34 }
35 
36 void MainWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
37 {
38     ui->progressBar->setMaximum(totalBytes);
39     ui->progressBar->setValue(bytesRead);
40 }
41 
42 void MainWindow::httpFinished()
43 {
44     ui->progressBar->hide();
45     file->flush(); //文件刷新
46     file->close();//文件关闭
47     reply->deleteLater();
48     reply = 0;
49     delete file;
50     file = 0;
51 }

6、运行,输入文件下载地址,点击下载后界面显示如下

7、文件自动下载到工程根目录下

原文地址:https://www.cnblogs.com/peter-czhang/p/3388410.html