我正在尝试显示从使用networkaccess manager获取的get请求中获取的图像。我能够编译甚至能够运行它。但是我无法在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));
}
}
请告诉我哪里出错了。
答案 0 :(得分:5)
调用QNetworkReply
后,QNetworkAccessManager::get()
中的数据尚未就绪。该调用是异步的,您需要在尝试检索任何数据之前连接到QNetworkAccessManager的finished()
信号或QNetworkReply的readyRead()
信号。
答案 1 :(得分:0)
要同步获取图像,您可以使用如下的QEventLoop:
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));
QEventLoop eventloop;
connect(reply,SIGNAL(finished()),&eventloop,SLOT(quit()));
eventLoop.exec();
if (reply->error() == QNetworkReply::NoError)
{
QImageReader imageReader(reply);
imageReader.setAutoDetectImageFormat (false);
QImage pic = imageReader.read();
ui->label_2->setPixmap(QPixmap::fromImage(pic));
}
}