Table of Content
Download Data from URL
The following code snippet demonstrates how to download data as QByteArray [qt-project.org] from URL. The downloaded data can be saved as a file or converted to appropriate object. For example if an image is downloaded it can be converted to QPixmap [qt-project.org] or QImage [qt-project.org] using method loadFromData() [qt-project.org]
Please note that although the name of the class is FileDownloader the downloaded data is not saved on the disk as file!
Important Classes
- QNetworkAccessManager [qt-project.org]
- QNetworkRequest [qt-project.org]
- QNetworkReply [qt-project.org]
- QUrl [qt-project.org]
.pro File
- QT += network
If you are targeting Symbian devices remember to add the capability for network services.
- symbian:TARGET.CAPABILITY += NetworkServices
filedownloader.h
- #ifndef FILEDOWNLOADER_H
- #define FILEDOWNLOADER_H
- #include <QObject>
- #include <QByteArray>
- #include <QNetworkAccessManager>
- #include <QNetworkRequest>
- #include <QNetworkReply>
- {
- Q_OBJECT
- public:
- virtual ~FileDownloader();
- signals:
- void downloaded();
- private slots:
- private:
- QNetworkAccessManager m_WebCtrl;
- QByteArray m_DownloadedData;
- };
- #endif // FILEDOWNLOADER_H
filedownloader.cpp
- #include "filedownloader.h"
- {
- m_WebCtrl.get(request);
- }
- FileDownloader::~FileDownloader()
- {
- }
- {
- m_DownloadedData = pReply->readAll();
- //emit a signal
- pReply->deleteLater();
- emit downloaded();
- }
- {
- return m_DownloadedData;
- }
Usage
Load Pixmap from URL
- Declare slot
- private slots:
- void loadImage();
- Connect signal downloaded() to the slot
- m_pImgCtrl = new FileDownloader(imageUrl, this);
- connect(m_pImgCtrl, SIGNAL(downloaded()), SLOT(loadImage()));
- Load QPixmap from the downloaded data
- void MainWindow::loadImage()
- {
- QPixmap buttonImage;
- buttonImage.loadFromData(m_pImgCtrl->downloadedData());
- }

