#QT项目实战(天气预报)

1.IDE:QTCreator


2.实验:


3.记录:

(1)调用API的Url

a.调用API获取IP

whois.pconline.com.cn/ipJson.jsp?ipicon-default.png?t=N7T8http://whois.pconline.com.cn/ipJson.jsp?ip

 if(window.IPCallBack) {IPCallBack({"ip":"123.147.249.72","pro":"重庆市","proCode":"500000","city":"重庆市","cityCode":"500000","region":"渝北区","regionCode":"500112","addr":"重庆市渝北区 铁通","regionNames":"","err":""});}

 b.其他的API

太平洋网络IP地址查询Web接口 (pconline.com.cn)icon-default.png?t=N7T8http://whois.pconline.com.cn/
whois.pconline.com.cn/ipJson.jsp?ip&level=3icon-default.png?t=N7T8https://whois.pconline.com.cn/ipJson.jsp?ip&level=3

加上level=3后,获得的addr为重庆市渝北区,得不到铁通(level=3返回省市区)

if(window.IPCallBack) {IPCallBack({"ip":"123.147.249.72","pro":"重庆市","proCode":"500000","city":"重庆市","cityCode":"500000","region":"渝北区","regionCode":"500112","addr":"重庆市渝北区","regionNames":"","err":""});} 

c.JSON格式校验

I.不加level的返回值拿去校验

可以发现不是JSON格式

II.指定JSON格式获得值拿去校验

whois.pconline.com.cn/ipJson.jsp?ip&json=trueicon-default.png?t=N7T8https://whois.pconline.com.cn/ipJson.jsp?ip&json=true

{"ip":"123.147.249.72","pro":"重庆市","proCode":"500000","city":"重庆市","cityCode":"500000","region":"渝北区","regionCode":"500112","addr":"重庆市渝北区 铁通","regionNames":"","err":""}

 

d.天气类API 

 I.心知天气API(需要密钥和城市拼音)

开发文档:

天气实况 | 心知天气文档 (seniverse.com)

请求示例:当天实时天气

 II.中华万年历(只需要城市,不需要密钥)

已经失效......

e.时间API(苏宁)

https://quan.suning.com/getSysTime.do


 (2)设计UI界面


(3) 编写代码

a.IP地址请求

I.网络请求回应管理类

QNetworkRequest,QNetworkReply,QNetworkManager

II.文本编码类

QTextCodeC

    QNetworkReply *reply = (QNetworkReply *)sender();//可能会有多个函数连接到NetworkReply的信号finished上
    QTextCodec *codec = QTextCodec::codecForName("gbk");
    QString data=codec->toUnicode(reply->readAll());
    qDebug("%s",data.toStdString().data());

 有可能多个Object的signal会连接到同一个signal(例如多个Button可能会connect到一个slot函数onClick()),因此这是就需要判断到底是哪个Object emit了这个signal,根据sender的不同来进行不同的处理

 b.天气数据请求

I.心知天气访问当天实时天气示例

开发文档

天气实况 | 心知天气文档 (seniverse.com)

由于上面介绍的中华万年历已经失效,所以只能使用其他的API,这里我们使用心知天气的API

#include "widget.h"
#include "ui_widget.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDebug>
#include <QTextCodec>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    networkrmanager=new QNetworkAccessManager(this);
    // QNetworkRequest networkrequest;
    // networkrequest.setUrl(QUrl("https://whois.pconline.com.cn/ipJson.jsp?ip&json=true"));
    // QNetworkReply *networkreply=networkrmanager->get(networkrequest);
    // connect(networkreply,SIGNAL(finished()),this,SLOT(NetworkReplyFinished_Slot()));
    QNetworkRequest networkrequest;
    networkrequest.setUrl(QUrl("https://api.seniverse.com/v3/weather/now.json?key=自己的密钥&location=chongqing&language=en&unit=c"));
    QNetworkReply *weatherreply=networkrmanager->get(networkrequest);
    connect(weatherreply,SIGNAL(finished()),this,SLOT(WeatherReplyFinished_Slot()));
}



Widget::~Widget()
{
    delete ui;
}
/*
//ip地址网络请求回应完成
void Widget::NetworkReplyFinished_Slot()
{
    QNetworkReply *reply = (QNetworkReply *)sender();   //可能会有多个函数连接到NetworkReply的信号finished上
    QTextCodec *codec = QTextCodec::codecForName("gbk"); //编码为gbk
    QString data=codec->toUnicode(reply->readAll());
    qDebug("%s",data.toStdString().data());
    reply->deleteLater();              //删除避免内存泄露
    int city_start = data.indexOf("city")+7;
    int city_end=data.indexOf("cityCode")-3;
    QString city_name=data.mid(city_start,city_end-city_start);
    qDebug()<<city_name;
    ui->location_txt->setText(city_name);
 //请求天气数据
    QNetworkRequest networkrequest;
    networkrequest.setUrl(QUrl("https://api.seniverse.com/v3/weather/now.json?key=SFeVqqT5EMlRWi6D0&location=chongqing&language=en&unit=c"));
    QNetworkReply *weatherreply=networkrmanager->get(networkrequest);
    connect(weatherreply,SIGNAL(finished()),this,SLOT(WeatherReplyFinished_Slot()));
}
*/
//获取天气
void Widget::WeatherReplyFinished_Slot()
{
    qDebug("hh");

    QNetworkReply *reply = (QNetworkReply *)sender();   //可能会有多个函数连接到NetworkReply的信号finished上
    QTextCodec *codec = QTextCodec::codecForName("gbk"); //编码为gbk
    QString data=codec->toUnicode(reply->readAll());
    qDebug("%s",data.toStdString().data());
    reply->deleteLater();              //删除避免内存泄露
    //查找城市
    int city_start = data.indexOf("name")+7;
    int city_end=data.indexOf("country")-3;
    QString city=data.mid(city_start,city_end-city_start);
    qDebug()<<city;
    ui->location_txt->setText(city);
    //查找天气
    int weather_start = data.indexOf("text")+7;
    int weather_end=data.indexOf("code")-3;
    QString weather=data.mid(weather_start,weather_end-weather_start);
    qDebug()<<weather;
    ui->weather_txt2->setText(weather);
    //查找温度
    int temperature_start = data.indexOf("temperature")+14;
    int temperature_end=data.indexOf("last_update")-4;
    QString temperature=data.mid(temperature_start,temperature_end-temperature_start);
    qDebug()<<temperature;
    ui->now_temperature_txt->setText(temperature);
}

 在代码中我们获得了三个信息,第一个是城市,第二个是天气,第三个是温度

{
    "results": [
        {
            "location": {
                "id": "***********",
                "name": "Chongqing",
                "country": "CN",
                "path": "Chongqing,Chongqing,China",
                "timezone": "Asia/Shanghai",
                "timezone_offset": "+08:00"
            },
            "now": {
                "text": "Cloudy",
                "code": "4",
                "temperature": "27"
            },
            "last_update": "2024-04-01T16:07:48+08:00"
        }
    ]
}

 运行效果:

II.心知天气连续几天天气获取示例

从昨天开始获取一直到未来三天

https://api.seniverse.com/v3/weather/daily.json?key=密钥&location=chongqing&language=zh-Hans&unit=c&start=-1&days=5

由于我们是免费用户,所以不能查询到昨日的天气信息。

c.关于解决编码问题-简体中文

上面第一次做出的界面为英文,我们获取的语言也是英文,我们后面把language改为zh-Hans(中文简体)更适合国人。修改编码为utf-8

d.使用心知天气连续访问几天天气的方式获取数据

从今天开始的五天(免费用户受限3天)

https://api.seniverse.com/v3/weather/daily.json?key=自己的密钥&location=chongqing&language=zh-Hans&unit=c&start=0&days=5

{
	"results": [{
		"location": {
			"id": "*********",
			"name": "重庆",
			"country": "CN",
			"path": "重庆,重庆,中国",
			"timezone": "Asia/Shanghai",
			"timezone_offset": "+08:00"
		},
		"daily": [{
			"date": "2024-04-02",
			"text_day": "多云",
			"code_day": "4",
			"text_night": "小雨",
			"code_night": "13",
			"high": "28",
			"low": "19",
			"rainfall": "0.69",
			"precip": "0.36",
			"wind_direction": "西北",
			"wind_direction_degree": "315",
			"wind_speed": "8.4",
			"wind_scale": "2",
			"humidity": "91"
		}, {
			"date": "2024-04-03",
			"text_day": "小雨",
			"code_day": "13",
			"text_night": "中雨",
			"code_night": "14",
			"high": "27",
			"low": "18",
			"rainfall": "31.53",
			"precip": "0.99",
			"wind_direction": "西北",
			"wind_direction_degree": "315",
			"wind_speed": "8.4",
			"wind_scale": "2",
			"humidity": "87"
		}, {
			"date": "2024-04-04",
			"text_day": "小雨",
			"code_day": "13",
			"text_night": "中雨",
			"code_night": "14",
			"high": "21",
			"low": "17",
			"rainfall": "8.35",
			"precip": "0.79",
			"wind_direction": "西",
			"wind_direction_degree": "270",
			"wind_speed": "3.0",
			"wind_scale": "1",
			"humidity": "91"
		}],
		"last_update": "2024-04-02T08:00:00+08:00"
	}]
}

(4)JSON格式解析

a.JSON格式

可以看到上面获得几天天气的API会返回一大串JSON格式数据,用我们上述的办法一个一个找非常麻烦,这个时候我们可以使用QT中的JSON类来解析。

#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonDocument>

b.解析参考

Qt 常用JSON解析示例 - fengMisaka - 博客园 (cnblogs.com)icon-default.png?t=N7T8https://www.cnblogs.com/linuxAndMcu/p/13040194.html

c.编写解析代码

    QJsonParseError jsonparseerror;
    QJsonDocument jsondocument;
    QJsonObject jsonobject;
    jsondocument = QJsonDocument::fromJson(data.toUtf8().data(),&jsonparseerror);
    if((jsonparseerror.error==QJsonParseError::NoError)&&(jsondocument.isEmpty()==false))  //判断是否解析成功
    {
        qDebug("成功");
        if(jsondocument.isObject()){
        jsonobject=jsondocument.object();
        QJsonValue resultsvalue=jsonobject.value("results");  //results是一个对象,得到它的值
        QJsonObject resultobject=resultsvalue.toArray().at(0).toObject();   //将results数组里面的第一个元素作为对象

        //解析last_update
        QString last_update=resultobject.value("last_update").toString();
        qDebug()<<last_update;

        //解析地址
        QJsonObject locationobject=resultobject.value("location").toObject();  //将location作为对象
        QString location=locationobject.value("name").toString(); //将location对象里面的name的值取出来(转换为string)
        ui->location_txt->setText(location);  //设置地址
        qDebug()<<location;  //打印location

        //解析日期以及天气
        QJsonValue dailyvalue=resultobject.value("daily");
        QJsonArray dailyarray=dailyvalue.toArray();
        //qDebug()<<dailyarray.size();   //打印数组的个数
        QString weather[3];      //天气
        QString date[3];         //日期
        QString high_temprature[3];  //最高温
        QString low_temprature[3];   //最低温
        QString humidity[3];        //湿度
        for(int i=0;i<dailyarray.size();i++)
        {
            QJsonObject jsob=dailyarray.at(i).toObject();   //数组转换为JSON对象
            weather[i]=jsob.value("text_day").toString();   //获取天气
            date[i]=jsob.value("date").toString();          //获取日期
            high_temprature[i]=jsob.value("high").toString(); //获取最高温
            low_temprature[i]=jsob.value("low").toString();  //获取最低温
            humidity[i]=jsob.value("humidity").toString();   //获取湿度
            qDebug()<<weather[i];
        }

 (5)QT解析JSON数据的方法

a.体系结构

[]代表的是数组,{}代表的是对象,从最外层开始一层一层往里面剥开,最外层始终是一个"{}"。最重要的就是分清对象和数组。有"[]"数组则使用QJsonArray将其转换为QJson数组,当没有"[]"即数组时最简单。我们主要操控Object。

b.把整个JSON文本转换用的是QJsonDocument。

需要注意检验文本是否是正确的QJson格式,这里推荐先使用网上的在线工具,比如Be Json

在线JSON校验格式化工具(Be JSON)icon-default.png?t=N7T8https://www.bejson.com/

c.综合详解

以上面的心知天气返回的JSON为例:

I.先用QJsonDocument转换的文本转换给一个QJsonObject

    QJsonParseError jsonparseerror;
    QJsonDocument jsondocument;
    QJsonObject jsonobject;
    jsondocument = QJsonDocument::fromJson(data.toUtf8().data(),&jsonparseerror);
    if((jsonparseerror.error==QJsonParseError::NoError)&&(jsondocument.isEmpty()==false))  //判断是否解析成功
    {
        qDebug("成功");
        if(jsondocument.isObject()){
        jsonobject=jsondocument.object();

II.用QJsonObject.value提取results将其转换为QJsonObject

QJsonValue resultsvalue=jsonobject.value("results");  //results是一个对象,得到它的值

III.此时紧接着就是一个"["说明这是一个数组,然后由"{"囊括一直到last_update后面才有一个"}"结束囊括紧跟的就是"]",说明这个results数组只有一个元素

IIII.将results转换为QJsonArray数组并且取下标为0的值转换为QJsonObject(因为数组下标从0开始,并且只有一个元素)

QJsonObject resultobject=resultsvalue.toArray().at(0).toObject();

IIIII.此时results下标为0的对象(resultobject)中有三个元素"location"、"daily"、"last_update",因为location以及daily内部都有很多内容,所以我们先提取最简单的"last_update"

IIIIII.此时可直接用resultobject.value("last_update")提取last_update的值。

QString last_update=resultobject.value("last_update").toString();
qDebug()<<last_update;

IIIIIII.再看location,用resultobject.value("location").toObject转换为QJsonObject(locationobject),再将用location.value("").tostring将想要的值提出来。

QJsonObject locationobject=resultobject.value("location").toObject();  //将location作为对象
QString location=locationobject.value("name").toString(); //将location对象里面的name的值取出来(转换为string)
qDebug()<<location;  //打印location

IIIIIIII.再看daily,[],说明是数组,但是它有三个元素"{},{},{}",遇到数组将其转换为QJsonArray

QJsonArray dailyarray=resultobject.value("daily").toArray();

 再将Array的下标值转换为对象,再获取数据

        for(int i=0;i<dailyarray.size();i++)
        {
            QJsonObject jsob=dailyarray.at(i).toObject();   //数组转换为JSON对象
            weather[i]=jsob.value("text_day").toString();   //获取天气
            date[i]=jsob.value("date").toString();          //获取日期
            high_temprature[i]=jsob.value("high").toString(); //获取最高温
            low_temprature[i]=jsob.value("low").toString();  //获取最低温
            humidity[i]=jsob.value("humidity").toString();   //获取湿度
            qDebug()<<weather[i];
        }

至此获取所有数据完毕。 

(6)UI界面数据加载以及天气图标切换

  //设置界面数据
        ui->humidity1->setText(humidity[0]);
        ui->humidity2->setText(humidity[1]);
        ui->humidity3->setText(humidity[2]);
        ui->today->setText(date[0]);
        ui->tomorrow->setText(date[1]);
        ui->dayaftertomorrow->setText(date[2]);
        ui->weather_txt1->setText(weather[0]);
        ui->weather_txt2->setText(weather[1]);
        ui->weather_txt3->setText(weather[2]);
        ui->temprature_txt1->setText(low_temprature[0]+'/'+high_temprature[0]);
        ui->temprature_txt2->setText(low_temprature[1]+'/'+high_temprature[1]);
        ui->temprature_txt3->setText(low_temprature[2]+'/'+high_temprature[2]);
        //更改图标

        if(weather[0]=="多云")
        {
            QString pic(":/pic/pic/multicloud.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="小雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="大雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="阴")
        {
            QString pic(":/pic/pic/cloudy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="晴")
        {
            QString pic(":/pic/pic/sunny.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
//
        if(weather[1]=="多云")
        {
            QString pic(":/pic/pic/multicloud.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="小雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="大雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="阴")
        {
            QString pic(":/pic/pic/cloudy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="晴")
        {
            QString pic(":/pic/pic/sunny.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
//
        if(weather[2]=="多云")
        {
            QString pic(":/pic/pic/multicloud.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="小雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="大雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="阴")
        {
            QString pic(":/pic/pic/cloudy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="晴")
        {
            QString pic(":/pic/pic/sunny.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }

 (7)实时刷新数据(使用一个定时器来定时获取数据)

//定时器溢出事件
void Widget::timeout_slot()
{
    counter++;
     //10秒更新一次时间信息
    if((counter%2==0)&&(counter!=60))
    {
        QNetworkRequest networkrequest;
        networkrequest.setUrl(QUrl("https://quan.suning.com/getSysTime.do"));
        QNetworkReply *timereply=networkrmanager->get(networkrequest);
        connect(timereply,SIGNAL(finished()),this,SLOT(TimeReplyFinished_Slot()));
    }
    //5分钟获取一次天气数据
    else if(counter==60)
    {
        counter=0;
        QNetworkRequest networkrequest;
        networkrequest.setUrl(QUrl("https://api.seniverse.com/v3/weather/daily.json?key=用户密钥&location=chongqing&language=zh-Hans&unit=c&start=0&days=5"));
        QNetworkReply *weatherreply=networkrmanager->get(networkrequest);
        connect(weatherreply,SIGNAL(finished()),this,SLOT(WeatherReplyFinished_Slot()));
    }
}

(8)最终运行效果(UI有修改)

4.代码

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDebug>
#include <QTextCodec>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QStringLiteral>
#include <QJsonArray>
#include <QPixmap>
#include <QTimer>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    networkrmanager=new QNetworkAccessManager(this);
    QNetworkRequest networkrequest;
    //当日的天气
   // networkrequest.setUrl(QUrl("https://api.seniverse.com/v3/weather/now.json?key=用户密钥&location=chongqing&language=zh-Hans&unit=c"));
    //连续几日的天气
    networkrequest.setUrl(QUrl("https://api.seniverse.com/v3/weather/daily.json?key=用户密钥&location=chongqing&language=zh-Hans&unit=c&start=0&days=5"));

    QNetworkReply *weatherreply=networkrmanager->get(networkrequest);
    connect(weatherreply,SIGNAL(finished()),this,SLOT(WeatherReplyFinished_Slot()));

    timer_5s.start(5000);
    connect(&timer_5s,SIGNAL(timeout()),this,SLOT(timeout_slot()));

}



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


//获取天气
void Widget::WeatherReplyFinished_Slot()
{

    QNetworkReply *reply = (QNetworkReply *)sender();   //可能会有多个函数连接到NetworkReply的信号finished上
    QTextCodec *codec = QTextCodec::codecForName("utf-8"); //编码为gbk
    QString data=codec->toUnicode(reply->readAll());
    qDebug("%s",data.toStdString().data());
    reply->deleteLater();              //删除避免内存泄露
 //    //查找城市
 //    int city_start = data.indexOf("name")+7;
 //    int city_end=data.indexOf("country")-3;
 //    QString city=data.mid(city_start,city_end-city_start);
 // //   qDebug()<<city;
 //    ui->location_txt->setText(city);
 //    //查找天气
 //    int weather_start = data.indexOf("text")+7;
 //    int weather_end=data.indexOf("code")-3;
 //    QString weather=data.mid(weather_start,weather_end-weather_start);
 // //   qDebug()<<weather;
 //    ui->weather_txt1->setText(weather);
 //    //查找温度
 //    int temperature_start = data.indexOf("temperature")+14;
 //    int temperature_end=data.indexOf("last_update")-4;
 //    QString temperature=data.mid(temperature_start,temperature_end-temperature_start);
 // //   qDebug()<<temperature;
 //    ui->now_temperature_txt->setText(temperature);
    QJsonParseError jsonparseerror;
    QJsonDocument jsondocument;
    QJsonObject jsonobject;
    jsondocument = QJsonDocument::fromJson(data.toUtf8().data(),&jsonparseerror);
    if((jsonparseerror.error==QJsonParseError::NoError)&&(jsondocument.isEmpty()==false))  //判断是否解析成功
    {
        qDebug("成功");
        if(jsondocument.isObject()){
        jsonobject=jsondocument.object();
        QJsonValue resultsvalue=jsonobject.value("results");  //results是一个对象,得到它的值
        QJsonObject resultobject=resultsvalue.toArray().at(0).toObject();   //将results数组里面的第一个元素作为对象
        //解析last_update
        QString last_update=resultobject.value("last_update").toString();
        qDebug()<<last_update;

        //解析地址
        QJsonObject locationobject=resultobject.value("location").toObject();  //将location作为对象
        QString location=locationobject.value("name").toString(); //将location对象里面的name的值取出来(转换为string)
        ui->location_txt->setText(location);  //设置地址
        qDebug()<<location;  //打印location

        //解析日期以及天气
        QJsonArray dailyarray=resultobject.value("daily").toArray();
        //qDebug()<<dailyarray.size();   //打印数组的个数
        QString weather[3];      //天气
        QString date[3];         //日期
        QString high_temprature[3];  //最高温
        QString low_temprature[3];   //最低温
        QString humidity[3];        //湿度
        for(int i=0;i<dailyarray.size();i++)
        {
            QJsonObject jsob=dailyarray.at(i).toObject();   //数组转换为JSON对象
            weather[i]=jsob.value("text_day").toString();   //获取天气
            date[i]=jsob.value("date").toString();          //获取日期
            high_temprature[i]=jsob.value("high").toString(); //获取最高温
            low_temprature[i]=jsob.value("low").toString();  //获取最低温
            humidity[i]=jsob.value("humidity").toString();   //获取湿度
            qDebug()<<weather[i];
        }
        //设置界面数据
        ui->humidity1->setText(humidity[0]);
        ui->humidity2->setText(humidity[1]);
        ui->humidity3->setText(humidity[2]);
        ui->today->setText(date[0]);
        ui->tomorrow->setText(date[1]);
        ui->dayaftertomorrow->setText(date[2]);
        ui->weather_txt1->setText(weather[0]);
        ui->weather_txt2->setText(weather[1]);
        ui->weather_txt3->setText(weather[2]);
        ui->temprature_txt1->setText(low_temprature[0]+'/'+high_temprature[0]);
        ui->temprature_txt2->setText(low_temprature[1]+'/'+high_temprature[1]);
        ui->temprature_txt3->setText(low_temprature[2]+'/'+high_temprature[2]);
        //更改图标

        if(weather[0]=="多云")
        {
            QString pic(":/pic/pic/multicloud.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="小雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="大雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="阴")
        {
            QString pic(":/pic/pic/cloudy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
        else if(weather[0]=="晴")
        {
            QString pic(":/pic/pic/sunny.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img1->height(),ui->weather_img1->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img1->setPixmap(pixmap);
        }
//
        if(weather[1]=="多云")
        {
            QString pic(":/pic/pic/multicloud.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="小雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="大雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="阴")
        {
            QString pic(":/pic/pic/cloudy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
        else if(weather[1]=="晴")
        {
            QString pic(":/pic/pic/sunny.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img2->height(),ui->weather_img2->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img2->setPixmap(pixmap);
        }
//
        if(weather[2]=="多云")
        {
            QString pic(":/pic/pic/multicloud.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="小雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="大雨")
        {
            QString pic(":/pic/pic/rainy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="阴")
        {
            QString pic(":/pic/pic/cloudy.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }
        else if(weather[2]=="晴")
        {
            QString pic(":/pic/pic/sunny.png");
            QPixmap pixmap(pic);
            pixmap=pixmap.scaled(ui->weather_img3->height(),ui->weather_img3->width(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
            ui->weather_img3->setPixmap(pixmap);
        }

    //时间请求
        QNetworkRequest networkrequest;
        networkrequest.setUrl(QUrl("https://quan.suning.com/getSysTime.do"));
        QNetworkReply *timereply=networkrmanager->get(networkrequest);
        connect(timereply,SIGNAL(finished()),this,SLOT(TimeReplyFinished_Slot()));

        }

    }
}

//时间请求相应
void Widget::TimeReplyFinished_Slot()
{
    QNetworkReply *reply = (QNetworkReply *)sender();   //可能会有多个函数连接到NetworkReply的信号finished上
    QTextCodec *codec = QTextCodec::codecForName("utf-8"); //编码为gbk
    QString data=codec->toUnicode(reply->readAll());
    qDebug("%s",data.toStdString().data());
    reply->deleteLater();              //删除避免内存泄露

    int Date_start;
    int Date_end;
    int hour_start;
    int hour_end;
    int min_start;
    int min_end;
    int sec_start;
    int sec_end;

    Date_start=data.indexOf("sysTime2")+11;
    Date_end=data.indexOf("sysTime1")-12;
    QString Date=data.mid(Date_start,Date_end-Date_start);
    //qDebug()<<Date;
    hour_start=data.indexOf("sysTime2")+22;
    hour_end=data.indexOf("sysTime1")-9;
    QString hour=data.mid(hour_start,hour_end-hour_start);
    //qDebug()<<hour;
    min_start=data.indexOf("sysTime2")+25;
    min_end=data.indexOf("sysTime1")-6;
    QString min=data.mid(min_start,min_end-min_start);
    //qDebug()<<min;
    sec_start=data.indexOf("sysTime2")+28;
    sec_end=data.indexOf("sysTime1")-3;
    QString sec=data.mid(sec_start,sec_end-sec_start);
    //qDebug()<<sec;
    ui->Date_txt->setText(Date);
    ui->time_hour->display(hour);
    ui->time_min->display(min);
    ui->time_sec->display(sec);
}

//定时器溢出事件
void Widget::timeout_slot()
{
    counter++;
     //10秒更新一次时间信息
    if((counter%2==0)&&(counter!=60))
    {
        QNetworkRequest networkrequest;
        networkrequest.setUrl(QUrl("https://quan.suning.com/getSysTime.do"));
        QNetworkReply *timereply=networkrmanager->get(networkrequest);
        connect(timereply,SIGNAL(finished()),this,SLOT(TimeReplyFinished_Slot()));
    }
    //5分钟获取一次天气数据
    else if(counter==60)
    {
        counter=0;
        QNetworkRequest networkrequest;
        networkrequest.setUrl(QUrl("https://api.seniverse.com/v3/weather/daily.json?key=用户密钥&location=chongqing&language=zh-Hans&unit=c&start=0&days=5"));
        QNetworkReply *weatherreply=networkrmanager->get(networkrequest);
        connect(weatherreply,SIGNAL(finished()),this,SLOT(WeatherReplyFinished_Slot()));
    }
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QNetworkAccessManager>
#include <QTimer>
QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    QNetworkAccessManager *networkrmanager;
    QTimer timer_5s;
    int counter=0;
private:
    Ui::Widget *ui;


public slots:
    void WeatherReplyFinished_Slot();
    void timeout_slot();
    void TimeReplyFinished_Slot();
};
#endif // WIDGET_H

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值