2011-06-23 80 views
4

我試圖顯示使用networkaccess管理器獲取的獲取請求中獲取的圖像。我能夠編譯,甚至能夠運行它。但我無法在Qlabel中顯示圖像。從網絡訪問管理器獲取的QT顯示圖像

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)); 

    } 


} 

請告訴我我哪裏出錯了。

回答

5

QNetworkReply中的數據在撥打QNetworkAccessManager::get()後沒有立即準備好。該呼叫是異步的,在嘗試檢索任何數據之前,您需要連接到QNetworkAccessManager的finished()信號或QNetworkReply的readyRead()信號。

+0

謝謝,我想它,一段時間後,我會更新。 – Vamsi

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)); 

    } 


}