我正在寻找关于我的小程序的帮助。我想使用QNetwork类从网站下载设置(.exe)。我已经搜索并阅读了很多关于它的帖子,但它没有用。
download.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();
}
download.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并且它可以工作。我还添加了#34; network&#34;到&#34; .pro&#34;文件。但是,当我运行我的程序时,我点击另一个类的按钮,initialiseDownload()正在工作,但信号似乎是无效的。
提前致谢!
答案 0 :(得分:4)
在Download::initialiseDownload()
函数中,您创建的QNetworkAccessManager
超出了函数末尾的范围。
将QNetworkAccessManager
作为成员变量或至少在下载期间的某个位置放置。
考虑到你打电话给你的班级&#34;下载&#34;,QNetworkAccessManager
生活在Download
实例的父母身上可能是最符合逻辑的,因为你(可以使用相同的QNetworkAccessManager
同时开始多次下载。