Search code examples
c++qtqnetworkreply

Getting the percentage downloaded from a QNetworkReply


I'm attempting to get the percentage downloaded from a QNetworkReply as a file is being downloaded by using:

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

but when I test my program, I always get:

Progress: 100

which outputs twice and I never get anything below 100. I would like the signal to be emitted every time the download progress changes.

How can I get this to happen? Or have I made a mistake in my code which is preventing it from happening?

EDIT: @dubsjw pointed out that I had a rounding error by using an int. Now I get an increase from 0 to 100 over time for a large image but for a small image, I still only get progress: 0 and progress: 100 with nothing in between. I would like to emit a signal which is received by a progress bar, which smoothly increases from 0 to 100. How can I do this?

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;
 }

Solution

  • Is your request that you are passing into the get function a valid address? I would try a debug statement at that point to see if you are getting what you expect. Also, check to see how many times you the getDownloadData() function is being called. If you see it getting called once with 0 as both the read and total values then you know you don't have a valid request.