Qt学习笔记-http服务的初步认识(使用程序下载网站上的图片)
生活随笔
收集整理的這篇文章主要介紹了
Qt学习笔记-http服务的初步认识(使用程序下载网站上的图片)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
關(guān)鍵是:QNetworkAccessManager類用來協(xié)調(diào)網(wǎng)絡(luò)操作,可以調(diào)度創(chuàng)建好的請(qǐng)求,并發(fā)射信號(hào)來報(bào)告進(jìn)度。
運(yùn)行截圖如下:
代碼如下:
widget.h
#ifndef WIDGET_H #define WIDGET_H#include <QWidget>class QNetworkReply; class QNetworkAccessManager; #include <QUrl> class QFile;namespace Ui { class Widget; }class Widget : public QWidget {Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();void startRequest(QUrl url);private slots:void httpFinished();void httpReadyRead();void updateProgress(qint64,qint64);void on_pushButton_clicked();private:Ui::Widget *ui;QNetworkAccessManager *manager;QNetworkReply *reply;QUrl url;QFile *file;};#endif // WIDGET_Hwidget.cpp
#include "widget.h" #include "ui_widget.h" #include <QtNetwork>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget) {ui->setupUi(this);this->setWindowTitle("CSDN IT1995");manager=new QNetworkAccessManager(this);ui->progressBar->hide();connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(on_pushButton_clicked())); }Widget::~Widget() {delete ui; }void Widget::startRequest(QUrl url) {reply=manager->get(QNetworkRequest(url));connect(reply,&QNetworkReply::readyRead,this,&Widget::httpReadyRead);connect(reply,&QNetworkReply::downloadProgress,this,&Widget::updateProgress);connect(reply,&QNetworkReply::finished,this,&Widget::httpFinished); }void Widget::httpFinished() {ui->progressBar->hide();if(file){file->close();delete file;file=0;}reply->deleteLater();reply=0; }void Widget::httpReadyRead() {if(file)file->write(reply->readAll()); }void Widget::updateProgress(qint64 byteRead, qint64 totalBytes) {ui->progressBar->setMaximum(totalBytes);ui->progressBar->setValue(byteRead); }void Widget::on_pushButton_clicked() {url=ui->lineEdit->text();QFileInfo info(url.path());QString fileName(info.fileName());if(fileName.isEmpty())fileName="index.html";file=new QFile(fileName);if(!file->open(QIODevice::WriteOnly)){delete file;file=NULL;return;}startRequest(url);ui->progressBar->setValue(0);ui->progressBar->show(); }main.cpp
#include "widget.h" #include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); }總結(jié)
以上是生活随笔為你收集整理的Qt学习笔记-http服务的初步认识(使用程序下载网站上的图片)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++工作笔记-stl中map基础用法(
- 下一篇: Qt学习笔记-使用QStyleFacto