C++ QT 加载网络图片、本地图片

源码下载:C++_QT 加载图片

QTShowImage.cpp

#include "QtShowImage.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include

QtShowImage::QtShowImage(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	connect(ui.pushButton, SIGNAL(pressed()), this, SLOT(on_pushButton_clicked()));
	connect(ui.pushButton_2, SIGNAL(pressed()), this, SLOT(on_pushButton_2_clicked()));

}

void QtShowImage::on_pushButton_clicked()
{
	currentPicture = new QPixmap;
	//获取网络图片
	QNetworkAccessManager *manager;
	manager = new QNetworkAccessManager(this);

	connect(manager, SIGNAL(finished(QNetworkReply*)),
		this, SLOT(replyFinished(QNetworkReply*)));
	manager->get(QNetworkRequest(QUrl("http://www.eutrom.com/images/case_unit_1.png")));
}

void QtShowImage::on_pushButton_2_clicked()
{
	currentPicture = new QPixmap("./Images/head.png");
	QPixmap tianqi_pixmap = currentPicture->scaled(ui.labelImage->width(), ui.labelImage->height(), Qt::KeepAspectRatio);
	ui.labelImage->setPixmap(tianqi_pixmap);
}

void QtShowImage::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();
	}
}

QtShowImage.h

#pragma once

#include 
#include "ui_QtShowImage.h"
#include 
#include 
#include 
#include 
#include 
#include 
class QtShowImage : public QMainWindow
{
	Q_OBJECT

public:
	QtShowImage(QWidget *parent = Q_NULLPTR);

private:
	Ui::QtShowImageClass ui;
	QPixmap *currentPicture;
	QString	currentFileName;

private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void replyFinished(QNetworkReply * reply);
};

效果图

C++ QT 加载网络图片、本地图片_第1张图片

你可能感兴趣的:(C++)