Search code examples
c++qtrapidjson

Download image from QNetworkAccessManager


I saw an other thread talking about this, but I'm not succeeding in the display of my image.

Currently, I'm downloading my image like this :

void MyClass::imgHandle() {
QNetworkAccessManager *nam = new QNetworkAccessManager(this);
  QUrl url(_code.c_str());
  QNetworkReply* reply = nam->get(QNetworkRequest(url));

  QEventLoop eventLoop;

  connect(reply,SIGNAL(finished()),&eventLoop,SLOT(quit()));
  eventLoop.exec();

  if (reply->error() == QNetworkReply::NoError)
    {
      QImageReader imageReader(reply);
      imageReader.setAutoDetectImageFormat (false);
      _img = imageReader.read();
    }

}

_code is built from a code got from a Json parsing, and the url looks like this : http://l.yimg.com/a/i/us/we/52/33.gif
_img is a QImage in my class.

And in my other class I do this :

int OtherClass::displayWeather()
{
 MyClass mC = new MyClass;

  mC->exec() // Where I get the code from the Json


  QLabel *imgWeather = new QLabel(this);                                              

  imgWeather->setPixmap(QPixmap::fromImage(mC->getImg())); 
  // getImg() return a QImage. 
  //The QImage created in MyClass.

  imgWeather->setGeometry(1700, 0, 120, 120);
}

And at the end .. Nothing is displayed !


Solution

  • You should check the QImageReader::read result:

    QImageReader imageReader(reply);
    imageReader.setAutoDetectImageFormat(false);
    QImage _img = imageReader.read();
    if (_img.isNull())
    {
        qDebug() << imageReader.errorString();
    }
    

    In your case the error is "Unsupported image format". By default QImageReader tries to autodetect the image format and you've just disabled it by calling setAutoDetectImageFormat(false). Remove it and QImageReader will do the job.