思路:
(1)、刚开始时隐藏进度条
(2)、按下下载按钮后,首先取得URL,用来创建文件,并且构造请求
(3)、发送请求,连接信号与槽(槽是准备读数据、更新进度条、相应结束的槽)
(4)、读取相应信息并且写入文件
(5)、重新隐藏进度条,关闭文件,删除应答等
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QFile> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; QNetworkAccessManager *manager; QFile* file; QNetworkReply * reply;//注意要定义成指针的形式 private slots: void onBtnClicked(); void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); void readyRead(); void finished(); }; #endif // MAINWINDOW_H
#include "MainWindow.h" #include "ui_MainWindow.h" #include <QUrl> #include <QString> #include <QFileInfo> #include <QFile> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); manager = new QNetworkAccessManager(this); ui->progressBar->hide(); connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(onBtnClicked())); } void MainWindow::onBtnClicked() { QString text = ui->lineEdit->text(); QUrl url(text); QFileInfo info(url.path()); QString fileName(info.fileName()); file = new QFile(fileName); if( ! file->open(QIODevice::WriteOnly)) { qDebug() << "error"; delete file; file = 0; return; } QNetworkRequest request;//1.构建请求 request.setUrl(url); reply = manager->get(request);//2.发送请求 connect(reply, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64))); connect(reply, SIGNAL(finished()), this, SLOT(finished())); } void MainWindow::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { ui->progressBar->setMaximum(bytesTotal); ui->progressBar->setValue(bytesReceived); } void MainWindow::readyRead() { if(file) { file->write(reply->readAll());//3.处理应答 ui->progressBar->show(); } } void MainWindow::finished() { ui->progressBar->hide(); file->flush(); file->close(); reply->deleteLater(); } MainWindow::~MainWindow() { delete ui; }
#include <QtGui/QApplication> #include "MainWindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }