Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Very simple C++ question - synchronous file download



  • I've got this very simple FileDownloader class. What would be the best way to make my program pause while the download is happening? It's downloading a configuration file and I'd rather it wait for the download to complete.

    Thanks!

    @#include "filedownloader.h"

    FileDownloader::FileDownloader(QObject *parent) :
    QObject(parent)
    {
    http = new QHttp(this);
    connect(http, SIGNAL(requestFinished(int,bool)), this, SLOT(requestFinished(int,bool)));

    downloadComplete = false;
    downloadStatus = NOTHING;
    

    }

    void FileDownloader::startDownload()
    {
    if (Host.isNull() || LocalFile.isNull() || RemoteFile.isNull())
    return;

    http->setHost(Host);
    http->get(RemoteFile);
    downloadComplete = false;
    downloadStatus = INPROGRESS;
    

    }

    bool FileDownloader::isDownloadComplete()
    {
    return downloadComplete;
    }

    void FileDownloader::requestFinished(int id, bool error)
    {
    if (error) {
    qDebug() << "Error: ";
    downloadStatus = ERROR;

    } else {
        qDebug() << "OK";
        QFile *DestFile = new QFile&#40;LocalFile&#41;;
    
        qDebug() << "Writing File";
        if (DestFile->open(QFile::Append)) {
            DestFile->write(http->readAll());
            DestFile->flush();
            DestFile->close();
        }
    
        delete DestFile;
        downloadComplete = true;
        downloadStatus   = SUCCESS;
    }
    

    }@



  • Depending the user interface of your application you can disable all controls and just set a loading dialog until the download is completed. Btw this is a simple example "how to download data from URL":http://qt-project.org/wiki/Download_Data_from_URL that you might find useful.



  • Having the signal-slot implementation early on the contructor class is wrong as it will act as asynchronous. You may use QEventLoop to make things synchrous while making your GUI (for example) responsive.

    @http->setHost(Host);
    http->get(RemoteFile);
    QEventLoop loop;
    QObject::connect(reply,SIGNAL(readyRead()),&loop,SLOT(quit()));
    loop.exec();
    //download here
    http->readAll();@

    Why dont you use QNetworkAccessManager by the way? QHttp is already obsolete.

    From QHttp documentation:

    bq. This class is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.


Log in to reply