美文网首页Hacker WoomIT程序员
Qt5.8 (1).网络图片下载与显示

Qt5.8 (1).网络图片下载与显示

作者: 七双叶 | 来源:发表于2017-06-13 20:36 被阅读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";
       }
    }
    

    相关文章

      网友评论

      本文标题:Qt5.8 (1).网络图片下载与显示

      本文链接:https://www.haomeiwen.com/subject/rbrjqxtx.html