QLabel设置网络图片的方法
首先使用QNetworkAccessManager下载网络图片,然后使用setPixmap设置图片。
//从url链接获得图片
QPixmap getPixmapFromUrl(const QString &imageUrl)
{
QUrl url(imageUrl);
QNetworkAccessManager manager;
QEventLoop loop;
QNetworkReply* reply = manager.get(QNetworkRequest(url));
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));//请求结束并下载完成后后,退出子事件循环
loop.exec();//开启子事件循环
QByteArray data = reply->readAll();
QPixmap pixmap;
pixmap.loadFromData(data);
return pixmap;
}
void setNetworkImage(const QString &imageUrl, int imageSize)
{
QPixmap pixmap = getPixmapFromUrl(imageUrl);
pixmap = pixmap.scaledToHeight(imageSize);
setPixmap(pixmap);
this->adjustSize();//让QLabel适应图片的大小
}
QLabel设置资源中图片的方法
资源中的图片可以直接用html标签进行显示。
void setLocalImage(const QString &imagePath, int imageSize)
{
QString text= QString("<img src='%1' height='%2'/>");
text = text.arg(imagePath).arg(imageSize);
QLabel::setText(text);
this->adjustSize();
}
QLabel设置资源中gif的方法
void setLocalGif(const QString &gifPath, int gifSize)
{
QMovie *movie = new QMovie(gifPath);
movie->start();
int height = gifSize;
int width = gifSize;
if(movie->currentImage().height() > 0){//根据动画的当前帧高宽比例,调整QLabel和动画的大小
width = gifSize * movie->currentImage().width() / movie->currentImage().height();
}
this->resize(width, height);
movie->setScaledSize(QSize(width, height));
this->setMovie(movie);
}
网友评论