我在qt標籤中顯示圖像。下面是我的代碼:在調用函數時獲取Pixmap是一個空像素圖500次
void MyClass::onPushButtonClicked(QString myurl)
{
this->setCursor(Qt::WaitCursor);
ui.qtImageLabel->clear();
qDebug()<<QTime::currentTime()<<"MyClass: onPushButtonClicked";
QNetworkAccessManager *qnam_push_button_clicked_show_image;
QNetworkReply *reply;
QNetworkRequest request;
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrl url(myurl);
request.setUrl(url);
qnam_push_button_clicked_show_image = new QNetworkAccessManager(this);
if(qnam_push_button_clicked_show_image)
{
QObject::connect(qnam_push_button_clicked_show_image, SIGNAL(finished(QNetworkReply*)),
this, SLOT(onPushButtonClickedRequestCompleted(QNetworkReply*)));
reply = qnam_push_button_clicked_show_image->post(request, url.encodedQuery());
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
}
}
void MyClass::onPushButtonClickedRequestCompleted(QNetworkReply *reply)
{
qDebug()<<QTime::currentTime()<<"MyClass: onPushButtonClickedRequestCompleted request completed";
if (reply->error() != QNetworkReply::NoError)
{
qDebug() << "Error in" << reply->url() << ":" << reply->errorString();
this->setCursor(Qt::ArrowCursor);
return;
}
QByteArray data = reply->readAll();
QPixmap pixmap;
pixmap.loadFromData(data);
int width;
int height;
//application size can be changed
QRect rec = QApplication::desktop()->screenGeometry();
height = rec.height();
width = rec.width();
qDebug()<<QTime::currentTime()<<width<<","<<height;
QSize *size = new QSize(width,height);
if(size)
{
QPixmap scaledPixmap = pixmap.scaled(*size);
ui.qtImageLabel->setPixmap(scaledPixmap);
}
if(size)
{
delete size;
size = NULL;
}
data.clear();
this->setCursor(Qt::ArrowCursor);
reply->deleteLater();
return;
}
在點擊按鈕將發送到服務器的請求並顯示從服務器接收到的不同的圖像。如果不超過500次,它工作正常。如果超過第一個這個錯誤已經顯示
QPixmap::scaled: Pixmap is a null pixmap
並且它不顯示圖像。然後,如果有人再次發送圖像請求,則會顯示以下錯誤: Qt捕獲了事件處理程序引發的異常。在Qt中不支持從事件處理程序中拋出異常事件 。您必須 重新實施QApplication::notify()
並在那裏捕獲所有異常。
我沒有得到上面代碼中的錯誤。有人可以告訴我如何解決這個問題嗎?
噢,還有,當你從'onPushButtonClickedRequestCompleted(QNetworkReply *回覆月初返回)另一個小泄漏'如果'回覆「有錯誤。你在這種情況下不會調用'reply-> deleteLater();'來泄漏回覆。通常這是我在這種插槽中調用的第一件事,這是安全的,因爲直到插槽退出後纔會實際刪除回覆,所以不需要在最後調用它。 –