我看到另一个线程谈论这个,但我没有成功地显示我的图像。
目前,我正在像这样下载我的图像:
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是从Json解析中获得的代码构建的,url看起来像这样:http://l.yimg.com/a/i/us/we/52/33.gif
_img是我们班的QImage。
在另一个类中,我这样做:
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);
}
最后…什么都没有显示!
您应该检查QImageReader::read
结果:
QImageReader imageReader(reply);
imageReader.setAutoDetectImageFormat(false);
QImage _img = imageReader.read();
if (_img.isNull())
{
qDebug() << imageReader.errorString();
}
在您的情况下,错误是"不支持的图像格式"。默认情况下,QImageReader
尝试自动检测图像格式,您刚刚通过调用setAutoDetectImageFormat(false)
禁用它。删除它,QImageReader
将完成工作。