QT学习 http ----获取天气Json信息并解析以及下载文件并保存

本文介绍如何使用QT进行网络编程,通过获取天气预报的JSON数据,解析并展示城市、温度和风力信息,同时讲解如何实现文件的下载功能。

前话

      假如我们要用 QT 做个天气预报或者说天气查询的软件,首先,抛开界面不讲,最起码要显示一下感兴趣的对应天气数据信息对吧?天气数据信息从哪里来?怎么拿到数据?拿到数据可以直接用吗?(不能直接用的话怎么进行数据的分析处理呢)

这时候,需要导入新的知识点,那就是QT 的网络编程了。

今天,我们就通过一个简单的例子,了解一下QT的网络编程。

例子简介

(1)获取一条天气信息(Json格式),分析数据,提取出城市、温度、以及风力的数据进行显示;

(2)通过输入下载地址,实现文件的下载;

效果:(这里是基于上一篇博客的实时时钟项目添加的,所以上面显示时间的那两行可以自觉忽略)

代码

 (1) myweather.ui文件

(2) myweather.h文件

#ifndef MYWEATHER_H
#define MYWEATHER_H

#include <QMainWindow>
#include <QUrl>
QT_BEGIN_NAMESPACE
namespace Ui { class MyWeather; }
QT_END_NAMESPACE
class QNetworkAccessManager;
class QNetworkReply;
class QFile;

class MyWeather : public QMainWindow
{
    Q_OBJECT

public:
    MyWeather(QWidget *parent = nullptr);
    void startRequest(QUrl url);
    ~MyWeather();

private:
    Ui::MyWeather *ui;
    QNetworkAccessManager *manager;
    QNetworkAccessManager *testProgress;
    QNetworkReply *reply;
    QNetworkReply *reply1;
    QUrl url;
    QFile *file;
    void analyseJson();
    QByteArray myweatherdata;

public slots:
    void timerUpdata(void);
private slots:
    //void replyFinished(QNetworkReply *);
    void httpFinished();
    void httpReadyRead();
    void updateDataReadProgress(qint64,qint64);

    void on_pushButton_clicked();
    void GetWebJsonData(QNetworkReply *);
};
#endif // MYWEATHER_H

(3)myweather.cpp

#include "myweather.h"
#include "ui_myweather.h"
#include <QFont>
#include <QTime>
#include <QTimer>
#include <QImage>
#include <qdatetime.h>
#include <QPixmap>
#include <QtNetwork>

/*test iamge function
 * // QPixmap Pix(":/clock.png");
    QImage *img = new QImage();
    img -> load(":/clock.png");
    ui->text1->setPixmap(QPixmap::fromImage(*img));
    ui->text1->setScaledContents(true);
    ui->text1->show();
*/

MyWeather::MyWeather(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MyWeather)
{
    ui->setupUi(this);
    QTimer *timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdata()));
    timer->start(1000);

   manager = new QNetworkAccessManager(this);
  // connect(manager,&QNetworkAccessManager::finished,
  //         this,&MyWeather::replyFinished);
   //manager -> get(QNetworkRequest(QUrl("http://pv.sohu.com/cityjson?ie=utf-8")));
   connect(manager,&QNetworkAccessManager::finished,
           this,&MyWeather::GetWebJsonData);
   manager -> get(QNetworkRequest(QUrl("http://www.weather.com.cn/data/sk/101190401.html")));


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

   QImage *img = new QImage();
   img -> load("E:/QT/myproject/myweather/myweather/clock.png");
   ui->text1->setPixmap(QPixmap::fromImage(*img));
   ui->text1->setScaledContents(true);
   ui->text1->show();
}

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

MyWeather::~MyWeather()
{
    delete ui;
}
void MyWeather::timerUpdata()
{
    QFont font("Microsoft YaHei",20,50);
    //QImage *img = new QImage();
    //img -> load(":/clock.png");

    QDateTime time = QDateTime::currentDateTime();
    QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
    QString str1 = time.toString("yyyy-MM-dd hh:mm:ss");
   // this -> ui -> text1 ->setPixmap(QPixmap::fromImage(*img));
  //  ui -> text1 ->setPixmap(QPixmap(":/clock.png"));
    //this -> ui -> text1 ->show();
    this -> ui -> text ->setFont(font);
    this -> ui->text->setText(str);
    //ui->text->show();
    ui -> lcd -> display(str1);
}
/*
void MyWeather::replyFinished(QNetworkReply *reply1)
{
    QString all = reply1 -> readAll();
    ui -> textBrowser -> setText(all);
    reply1 -> deleteLater();
}
*/
void MyWeather::GetWebJsonData(QNetworkReply *reply1)
{
    myweatherdata = reply1 -> readAll();
    ui -> textBrowser -> setText(myweatherdata);
    analyseJson();
    //reply1 -> deleteLater();
}
void MyWeather::analyseJson()
{
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(myweatherdata,&err);
    QJsonObject obj = doc.object().value("weatherinfo").toObject();

    ui -> City -> setText(doc.object().value("weatherinfo").toObject().take("city").toString());
    ui -> temp -> setText(doc.object().value("weatherinfo").toObject().take("temp").toString()+"℃");
    ui -> wind -> setText(doc.object().value("weatherinfo").toObject().take("WD").toString()
                          +doc.object().value("weatherinfo").toObject().take("WS").toString());



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

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

void MyWeather::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
    ui -> progressBar ->setMaximum(totalBytes);
    ui -> progressBar -> setValue(bytesRead);
}
void MyWeather::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 = 0;
        return ;
    }
    startRequest(url);
    ui -> progressBar -> setValue(0);
    ui -> progressBar -> show();
}

(4)main.cpp

#include "myweather.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyWeather w;
    w.setWindowTitle("实时时钟系统");
    w.show();
    return a.exec();
}


 

先将代码附上,知识点总结明日再补上

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值