我正在寻求有关我的小程序的帮助。我想使用 QNetwork 类从网站下载安装程序 (.exe)。我已经搜索并阅读了许多关于它的帖子,但它不起作用。
下载.cpp :
Download::Download(QObject *parent) :
QObject(parent)
{
}
void Download::initialiseDownload()
{
QNetworkAccessManager manager;
QNetworkRequest request;
request.setUrl(QUrl("http://www.mylink.com/setup.exe"));
reply = manager.get(request);
QObject::connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(downloadError(QNetworkReply::NetworkError)));
QObject::connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(updateProgress(qint64, qint64)));
QObject::connect(reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
}
void Download::downloadError(QNetworkReply::NetworkError err)
{
qDebug() << reply->errorString();
reply->deleteLater();
}
void Download::updateProgress(qint64 read, qint64 total)
{
qDebug() << "Progress...";
qint64 percent = (read / total) * 100;
qDebug() << percent;
}
void Download::downloadFinished()
{
qDebug() << "Finished !";
QByteArray b = reply->readAll();
QFile file("./sdk/setup.exe");
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out << b;
reply->deleteLater();
}
下载.h :
#include "launcher.h"
#include <QObject>
#include <QtNetwork>
class Download : public QObject, public Launcher
{
Q_OBJECT
public:
explicit Download(QObject *parent = 0);
void Download::initialiseDownload();
private slots:
void downloadError(QNetworkReply::NetworkError err);
void updateProgress(qint64 read, qint64 total);
void downloadFinished();
private:
QNetworkReply *reply;
};
我已经为OpenSSL添加了dll,它可以工作。我还在".pro"文件中添加了"网络"。但是,当我运行我的程序,并点击另一个类的按钮时,initialiseDownload() 正在工作,但信号似乎处于非活动状态。
提前感谢!
在 Download::initialiseDownload()
函数中,创建一个超出函数范围的QNetworkAccessManager
。
将您的QNetworkAccessManager
作为成员变量或至少在下载期间存在的位置。
考虑到您将类称为"下载",QNetworkAccessManager
位于(或)Download
实例的父实例中可能是最合乎逻辑的,因为您(可以)使用相同的QNetworkAccessManager
同时启动多个下载。