初識Qt文件下載

一、新建一個Qt Gui應用,項目名稱爲http,基類選擇爲QMainWindow,類名設置爲MainWindow。html

二、在http.pro文件中的QT  += core gui後添加\ network,或者直接添加QT  += network。網絡

三、在mainwindow.ui文件中分別拖入label控件、lineEdit控件、pushButton控件以及progressBar控件,以下。ide

四、在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);

五、在mainwindow.cpp源文件的構造函數中添加代碼ui

1  ui->progressBar->hide();

同時,在mainwindow.cpp源文件中添加如下函數代碼this

 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 }

六、運行,輸入文件下載地址,點擊下載後界面顯示以下url

七、文件自動下載到工程根目錄下spa

相關文章
相關標籤/搜索