QT5 下载图片JPG 直接显示在QLABEL上
void FormAssets_brow::setNetworkPic(const QString &picUrl) { QUrl url(picUrl); QNetworkAccessManager manager; QEventLoop loop; // qDebug() << "图片下载地址: " << url; QNetworkReply *reply = manager.get(QNetworkRequest(url)); //请求结束并下载完成后,退出子事件循环 QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); //开启子事件循环 loop.exec(); QByteArray jpegData = reply->readAll(); QPixmap pixmap; pixmap.loadFromData(jpegData); int with = ui->labIMG->width(); int height = ui->labIMG->height(); //QPixmap fitpixmap = pixmap.scaled(with, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); // 饱满填充 QPixmap fitpixmap = pixmap.scaled(with, height, Qt::KeepAspectRatio, Qt::SmoothTransformation); // 按比例缩放 ui->labIMG->setPixmap(fitpixmap); // 你在QLabel显示图片; }
下面的代码室用来显示GIF图片的:就是那个 地球
在 头文件里添加:
private slots:
void setNetworkGIF(const QString &GifUrl);
代码如下
void Widget::setNetworkGIF(const QString &GifUrl) { QUrl url(GifUrl); QNetworkAccessManager manager; QEventLoop loop; // qDebug() << "图片下载地址: " << GifUrl; QNetworkReply *reply = manager.get(QNetworkRequest(url)); //请求结束并下载完成后,退出子事件循环 QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit())); //开启子事件循环 loop.exec(); QByteArray gifmsg = reply->readAll(); QString gifname = "logo.gif"; QFile file(gifname); if(!file.open(QFile::WriteOnly)) { qDebug() << "open file fail"; exit(1); } file.write(gifmsg); file.close(); QMovie *movie = new QMovie( "logo.gif"); //path是gif图片的绝对路径 movie->setScaledSize(ui->labGif->size()); ui->labGif->setMovie(movie); movie->start(); }
使用方法:
QString url="http://jinesc.net/zb_users/upload/2020/12/202012101607577246215893.gif"; setNetworkGIF(url);
运行效果:
发表评论