Search code examples
c++qtqt4qnetworkaccessmanagerqtnetwork

QT display image obtained from network access manager


I am trying to display the image obtained from the get request made using networkaccess manager. I am able to compile and even able to run it. but I am unable to show the image in a Qlabel.

QNetworkAccessManager* nam;

void MainWindow::on_pushButton_clicked()
{
    nam = new QNetworkAccessManager(this);
    QUrl url("http://i.imgur.com/Uw7Fk.jpg");
    QNetworkReply* reply = nam->get(QNetworkRequest(url));
    if (reply->error() == QNetworkReply::NoError)
    {
        QImageReader imageReader(reply);
        imageReader.setAutoDetectImageFormat (false);
        QImage pic = imageReader.read();
        ui->label_2->setPixmap(QPixmap::fromImage(pic));

     }


}

Please tell me where I am going wrong.


Solution

  • The data in QNetworkReply is not ready immediately after the call to QNetworkAccessManager::get(). The call is asynchronous, and you need to connect to either the finished() signal of QNetworkAccessManager, or readyRead() signal of QNetworkReply before you attempt to retrieve any data.