C++ QT 加载网络图片显示到界面

2 篇文章 1 订阅
本文介绍了如何使用C++创建一个名为RecipeL的对话框,通过QNetworkAccessManager获取并显示网络图片。重点展示了getImg函数获取图片和replyFinished槽处理图片下载完成的流程。
摘要由CSDN通过智能技术生成

感谢原文链接 https://blog.csdn.net/wzq806341010/article/details/84553742
.h 文件内容

#ifndef RECIPEL_H
#define RECIPEL_H

#include <QDialog>
#include <QString>

#include <QMovie>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QPixmap>

namespace Ui {
class Recipel;
}

class Recipel : public QDialog
{
    Q_OBJECT

public:
    explicit Recipel(QWidget *parent = nullptr);
    ~Recipel();
public:
    void tableWidgetSet();//处方表格设置
    void getImg(QString imgUrl);//获取网络图片
public slots:
    void replyFinished(QNetworkReply *reply);//获取图片完成 槽
private:
    Ui::Recipel *ui;

    QPixmap *currentPicture;
    QString	currentFileName;
};

#endif // RECIPEL_H

cpp 文件内容

#include "recipel.h"
#include "ui_recipel.h"

Recipel::Recipel(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Recipel)
{
    QString imgUrl = "https://img-blog.csdnimg.cn/20181126175528867.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d6cTgwNjM0MTAxMA==,size_16,color_FFFFFF,t_70";  
   this->getImg(imgUrl);
}

//显示网络图片
void Recipel::getImg(QString imgUrl)
{
        currentPicture = new QPixmap;
        //获取网络图片
        QNetworkAccessManager *manager;
        manager = new QNetworkAccessManager(this);

        connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
        manager->get(QNetworkRequest(QUrl(imgUrl )));
}

void Recipel::replyFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        //获取字节流构造 QPixmap 对象
        currentPicture->loadFromData(reply->readAll());
        QDateTime now;
        QString filename = now.currentDateTime().toString("yyMMddhhmmss.jpg");
        currentPicture->save(filename);//保存图片
        currentFileName = filename;
        //可以在onpaint中 用QPixmap 显示currentPicture,则这种方法则不需要保存
        QPixmap tianqi_pixmap = currentPicture->scaled(ui->labelImage->width(), ui->labelImage->height(), Qt::KeepAspectRatio);
        //Qt::IgnoreAspectRatio, Qt::SmoothTransformation);//设置图片大小和label的长宽一致
        ui->labelImage->setPixmap(tianqi_pixmap);
        //显示图片,
        QMovie *move = new QMovie(currentFileName);
        //ui->lableImg->setMovie(move);
        move->start();
    }
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值