Qt5.8 (1).网络图片下载与显示
2017-06-13 本文已影响253人
七双叶
1. 实现效果如下图
最终效果2.核心源代码
(1) mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QNetworkAccessManager>
#include <QNetworkReply>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
private slots:
void on_m_pBtn_clicked();
void replyFinished(QNetworkReply *reply);
private:
Ui::MainWindow *ui;
QNetworkAccessManager netManager;
};
#endif // MAINWINDOW_H
(2) mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->m_pBtn->setText("Start Download");
ui->imageLabel->setFixedSize(100,100);
ui->imageLabel->setScaledContents(true);
connect(&netManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_m_pBtn_clicked()
{
ui->m_pBtn->setEnabled(false);
QUrl url;
url = QUrl(ui->urlInput->text());
QNetworkRequest request;
request.setUrl(url);
netManager.get(request);
}
void MainWindow::replyFinished(QNetworkReply *reply)
{
ui->m_pBtn->setEnabled(true);
if(reply->error() == QNetworkReply::NoError)
{
QByteArray bytes = reply->readAll();
QPixmap pixmap;
pixmap.loadFromData(bytes);
ui->imageLabel->setPixmap(pixmap);
QFile file("E:/test.png");
if (file.open(QIODevice::Append))
{
file.write(bytes);
}
file.close();
}
else
{
qDebug() << "Error\n";
}
}