I am developing a Qt C++ application. I need to download some files (which can be large) and show downloading progress to user. To perform this task, I use this code:
QNetworkAccessManager* networkManager = new QNetworkAccessManager();
QNetworkRequest request(fileUrl); //fileUrl is a QUrl variable
QVariant responseLength = request.header(QNetworkRequest::ContentLengthHeader);
int fileSize = responseLength.toInt();
ui->progressBar->setMaximum(fileSize);
QNetworkReply reply = networkManager->get(request);
QObject::connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgressChanged(qint64,qint64)));
Where downloadProgressChanged
is a slot with this code:
void downloadProgressChanged(qint64 downloaded, qint64 total)
{
ui->progressBar->setValue(ui->progressBar->value() + 1);
ui->labelProgress->setText(QString::number((downloaded / 1024)));
}
(I use QProgressBar named progressBar
to show progress and QLabel named labelProgress
to show downloaded kilobytes).
My problem is that I can't access Content-Length header (int fileSize
value is 0) and so I am not able to show the progress of the operation. I checked HTTP headers on my web-server - Content-Length works fine.
In this SO question I read that I can use QNetworkReply::metaDataChanged()
signal, but how can I use it to show progress? Documentation says that the signal can be emitted when downloading has been already started, but I need to get header content before downloading will start - to set up my progressBar.
Have you tried using readyRead signal? And in slot you could prepare the GUI. Something like this shoud do the work:
connect(reply, SIGNAL(readyRead()), this, SLOT(updateProgressBar()))