获取从QNetworkReply下载的百分比

时间:2015-01-20 17:02:29

标签: c++ qt qnetworkreply

我正在尝试通过使用以下方式获取从QNetworkReply下载的百分比,因为正在下载文件:

connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(getDownloadData(qint64, qint64)) );

但是当我测试我的程序时,我总是得到:

进度: 100

输出两次,我从未得到任何低于100的信号。我希望每次下载进度发生时都会发出信号。

我怎样才能实现这一目标?或者我在代码中犯了一个错误,阻止它发生?

编辑:@dubsjw指出我使用int有一个舍入错误。现在我随着时间的推移从0增加到100以获得大图像,但对于小图像,我仍然只能获得进展:0和进度:100之间没有任何内容。我想发出一个进度条收到的信号,从0到100平稳地增加。我该怎么做?

filedownloader.h:

#ifndef FILEDOWNLOADER_H
#define FILEDOWNLOADER_H

#include <QObject>
#include <QByteArray>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

class FileDownloader : public QObject
{
    Q_OBJECT
public:
    explicit FileDownloader(QUrl imageUrl, QObject *parent = 0);

    virtual ~FileDownloader();

    QByteArray downloadedData() const;



signals:
        void downloaded();

private slots:

    void fileDownloaded();
   void  getDownloadData(qint64 read, qint64 total);

private:

    QNetworkAccessManager m_WebCtrl;
    QByteArray m_DownloadedData;
    QNetworkReply* reply;

};

#endif // FILEDOWNLOADER_H

filedownloader.cpp:

#include "filedownloader.h"

FileDownloader::FileDownloader(QUrl imageUrl, QObject *parent) :
    QObject(parent)
{
    QNetworkRequest request(imageUrl);
    reply = m_WebCtrl.get(request);

    connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(getDownloadData(qint64, qint64)) );

    connect(reply, SIGNAL(finished()),this, SLOT(fileDownloaded()));


}

FileDownloader::~FileDownloader()
{

}

void FileDownloader::fileDownloaded()
{
    m_DownloadedData = reply->readAll();
    //emit a signal
    reply->deleteLater();
    emit downloaded();
}

QByteArray FileDownloader::downloadedData() const
{
    return m_DownloadedData;
}

 void FileDownloader::getDownloadData(qint64 read, qint64 total)
 {

     qDebug() << "Progress:";
     qint64 percent = (read / total) * 100;
     qDebug() << percent;
 }

1 个答案:

答案 0 :(得分:0)

您的请求是否已将get函数传入有效地址?我会在那时尝试调试语句,看看你是否得到了你所期望的。另外,请检查调用getDownloadData()函数的次数。如果您看到它被调用一次,其中0作为读取值和总值,那么您就知道您没有有效请求。