Skip to content

Instantly share code, notes, and snippets.

@dnoliver
Created November 3, 2020 03:00
Show Gist options
  • Save dnoliver/276e3e37f0a7cf3d4f66ccb06b7da73e to your computer and use it in GitHub Desktop.
Save dnoliver/276e3e37f0a7cf3d4f66ccb06b7da73e to your computer and use it in GitHub Desktop.
Qt Download Sample

Qt Download URL Sample

This sample have the code to download an image using http and https.

#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QObject>
#include "task.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const QUrl url = QUrl("https://via.placeholder.com/150");
//const QUrl url = QUrl("http://placehold.it/150");
qDebug() << "url" << url;
Task *task = new Task();
QNetworkAccessManager *nam = new QNetworkAccessManager();
QObject::connect(nam, &QNetworkAccessManager::finished, task, &Task::downloadFinished);
QNetworkRequest request(url);
nam->get(request);
return a.exec();
}
#include "task.h"
Task::Task()
{
}
void Task::downloadFinished(QNetworkReply *reply)
{
// Do processing here
qDebug() << "Hello World";
qDebug() << "reply->isFinished()" << reply->isFinished();
qDebug() << "reply->isRunning()" << reply->isRunning();
auto body = reply->readAll();
qDebug() << "body.size()" << body.size();
}
#ifndef TASK_H
#define TASK_H
#include <QObject>
#include <QNetworkReply>
class Task : public QObject
{
Q_OBJECT
public:
Task();
public slots:
void downloadFinished(QNetworkReply *reply);
};
#endif // TASK_H
QT -= gui
QT += network
CONFIG += c++11 console
CONFIG -= app_bundle
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
task.cpp
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
HEADERS += \
task.h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment