1.效果展示
2.头文件
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_QtWidgetsApplication1.h"
#include "QProgressDialog"
#include "QNetworkAccessManager"
#include "QNetworkReply"
#include "QNetworkRequest"
#include "QFile"
//用于下载时弹出一个进度条
class ProgressDialog : public QProgressDialog {
Q_OBJECT
public:
explicit ProgressDialog(const QUrl &url, QWidget *parent = Q_NULLPTR);
public slots:
void networkReplyProgress(qint64 bytesRead, qint64 totalBytes);
};
class QtWidgetsApplication1 : public QMainWindow
{
Q_OBJECT
public:
QtWidgetsApplication1(QWidget *parent = Q_NULLPTR);
public slots:
void SlotStartDownload();
void SlotHttpFinished();
void SlotHttpReadyRead();
void SlotCancelDownload();
private:
Ui::QtWidgetsApplication1Class ui;
QNetworkAccessManager *m_pNet;
QUrl m_reqUrl;
QNetworkReply *m_pReply;
QFile m_downloadFile;
};
3.源文件
#include "QtWidgetsApplication1.h"
ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent /*= Q_NULLPTR*/)
{
setWindowTitle(tr("Download Progress"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setLabelText(tr("Downloading %1.").arg(url.toDisplayString()));
setMinimum(0);
setValue(0);
setMinimumDuration(0);
}
void ProgressDialog::networkReplyProgress(qint64 bytesRead, qint64 totalBytes)
{
setMaximum(totalBytes);
setValue(bytesRead);
}
QtWidgetsApplication1::QtWidgetsApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
connect(ui.pushButton,&QPushButton::clicked,this, &QtWidgetsApplication1::SlotStartDownload);
}
void QtWidgetsApplication1::SlotStartDownload()
{
//下载链接
m_reqUrl = QUrl("https://d13lb3tujbc8s0.cloudfront.net/onlineinstallers/qt-unified-windows-x86-4.3.0-online.exe");
m_pNet = new QNetworkAccessManager;
//请求下载
m_pReply = m_pNet->get(QNetworkRequest(m_reqUrl));
//下载完成处理
connect(m_pReply, &QNetworkReply::finished, this, &QtWidgetsApplication1::SlotHttpFinished);
//有下载的数据到达时
connect(m_pReply, &QIODevice::readyRead, this, &QtWidgetsApplication1::SlotHttpReadyRead);
//下载时的进度条
ProgressDialog *progressDialog = new ProgressDialog(m_reqUrl, this);
progressDialog->setAttribute(Qt::WA_DeleteOnClose);
connect(progressDialog, &QProgressDialog::canceled, this, &QtWidgetsApplication1::SlotCancelDownload);
connect(m_pReply, &QNetworkReply::downloadProgress, progressDialog, &ProgressDialog::networkReplyProgress);
connect(m_pReply, &QNetworkReply::finished, progressDialog, &ProgressDialog::deleteLater);
progressDialog->show();
//保存下载的文件
m_downloadFile.setFileName("D:\\qt-unified-windows-x86-4.3.0-online.exe");
if (!m_downloadFile.open(QIODevice::WriteOnly))
{
return;
}
}
void QtWidgetsApplication1::SlotHttpFinished()
{
m_downloadFile.close();
}
void QtWidgetsApplication1::SlotHttpReadyRead()
{
m_downloadFile.write(m_pReply->readAll());
}
void QtWidgetsApplication1::SlotCancelDownload()
{
m_pReply->abort();
}