Qtのネットワークでは、ネットワークファイルのダウンロードをプログラミング2

 機能:アドレスリソースを入力し、ダウンロードをクリックし、ファイルやディスプレイダウンロードの進行状況をダウンロードしてください。

コードは以下の通りであります:

myHttp2.pro

QT       += network

 mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QUrl>

namespace Ui {
class MainWindow;
}

class QFile;
class QNetworkReply;
class QNetworkAccessManager;
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    void startRequest(QUrl url);
private:
    Ui::MainWindow *ui;

    QNetworkAccessManager* manager;
    QNetworkReply *reply;
    QUrl url;
    QFile *file;
private slots:
    void httpFinished();
    void httpReadyRead();
    void updateDataReadProgress(qint64,qint64);
    void on_pushButton_clicked();
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtNetwork>
#include <QFile>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    manager = new QNetworkAccessManager(this);
    ui->progressBar->hide();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::startRequest(QUrl url)
{
    reply = manager->get(QNetworkRequest(url));
    connect(reply,&QNetworkReply::readyRead,this,&MainWindow::httpReadyRead);
    connect(reply,&QNetworkReply::downloadProgress,this,&MainWindow::updateDataReadProgress);
    connect(reply,&QNetworkReply::finished,this,&MainWindow::httpFinished);
}

void MainWindow::httpReadyRead()
{
    if (file) {
        file->write(reply->readAll());
    }
}

void MainWindow::updateDataReadProgress(qint64 bytesRead,qint64 totalBytes)
{
    ui->progressBar->setMaximum(totalBytes);
    ui->progressBar->setValue(bytesRead);
}

void MainWindow::httpFinished()
{
    ui->progressBar->hide();
    if (file) {
        file->close();
        delete file;
        file = nullptr;
    }
    reply->deleteLater();
    reply = 0;
}

void MainWindow::on_pushButton_clicked()
{
    url = ui->lineEdit->text();
    QFileInfo info(url.path());
    QString fileName(info.fileName());
    qDebug()<<fileName;
    if (fileName.isEmpty()) {
        fileName = "index.html";
    }
    file = new QFile(fileName);
    if (!file->open(QIODevice::WriteOnly)) {
        delete file;
        file = 0;
        return;
    }
    startRequest(url);
    ui->progressBar->setValue(0);
    ui->progressBar->show();
}

 

本明細書で使用する場合、GET()関数は、ネットワークに要求し、信号QNetworkReply複数のオブジェクトと関連付けられているカスタム溝を送信します。新しいデータを読み出すことができるたびにreadyRead()信号のQIODeviceは、送信信号となり、クラスから継承され;要求されたネットワークのダウンロードの進行状況の更新がダウンロード進行中の()信号がプログレスバーを更新するために使用される送信するたびに。各トランスポンダの端部は、完成()前回のプログラムQNetworAccessManagerクラス()信号が印加されるのと同じ信号が、異なる送信者を終え、パラメータも異なる処理を送信します。

公開された257元の記事 ウォン称賛22 ビュー90000 +

おすすめ

転載: blog.csdn.net/qq_24127015/article/details/104654809