-3

我正在寻求有关我的小程序的帮助。我想使用 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() 正在工作,但信号似乎处于非活动状态。

提前致谢 !

4

1 回答 1

4

在您的Download::initialiseDownload()函数中,您创建了一个QNetworkAccessManager在函数末尾超出范围的函数。

将您的QNetworkAccessManager作为成员变量或至少在下载期间它所在的位置。

考虑到您将您的类称为“Download”,最合乎逻辑的可能是实例QNetworkAccessManager的父级中(或者是)Download,因为您(可以)同时启动多个下载QNetworkAccessManager

于 2015-01-17T17:55:52.423 回答