#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"); //编码为gbkQString 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"); //编码为gbkQString 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_updateQString 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"); //编码为gbkQString 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_updateQString 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"); //编码为gbkQString 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_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic: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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/300166.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【攻防世界】unseping (反序列化与Linux bash shell)

打开题目环境&#xff1a; 1、进行PHP代码审计&#xff0c;通过审计得知需要用到PHP反序列化。找到输出flag的位置为 ping()函数。通过使用 exec() 函数来执行 $ip 并将结果保存在 $result 中&#xff0c;最终输出 $result。 2、接着寻找给 $ip 传参的位置&#xff0c;发现通过…

stm32中断传输的状态信息

1、gState &#xff08;Tx&#xff09;发送的状态信息 2、RxState &#xff08;Rx&#xff09;接收的状态信息

STM32单片机智能电表交流电压电流程序设计(电流 电压互感器TV1005M+TA1005M)

资料下载地址&#xff1a;STM32单片机智能电表交流电压电流程序设计(电流 电压互感器TV1005MTA1005M) 1、摘要 5、基于STM32F103单片机智能电表交流电压电流设计 本设计由STM32单片机核心板电路交流电压电流检测模块电路WIFI模块电路指示灯电路组成。 1、通过电压互感器TV100…

6. Z 字形变换(Java)

目录 题目描述&#xff1a;输入&#xff1a;输出&#xff1a;代码实现&#xff1a; 题目描述&#xff1a; 将一个给定字符串 s 根据给定的行数 numRows &#xff0c;以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 “PAYPALISHIRING” 行数为 3 时&#xff0c;排列如…

[C语言][数据结构][动态内存空间的开辟]顺序表的实现!

目录 零.必备知识 a.顺序表的底层是数组. b.数组在内存中是连续存放的. c.动态内存空间的开辟(malloc,calloc,realloc). 一.顺序表的定义与实现 1.1 顺序表的定义 1.2 顺序表的初始化 1.3 顺序表的销毁 1.4 顺序表容量的检查与调整(最关键的部分) 1.5 顺序表的尾插 1.…

A First Course in the Finite Element Method【Daryl L.】|PDF电子书

专栏导读 作者简介&#xff1a;工学博士&#xff0c;高级工程师&#xff0c;专注于工业软件算法研究本文已收录于专栏&#xff1a;《有限元编程从入门到精通》本专栏旨在提供 1.以案例的形式讲解各类有限元问题的程序实现&#xff0c;并提供所有案例完整源码&#xff1b;2.单元…

idea的后端环境配置

首先&#xff0c;在你刚打开idea时红色箭头所指的是你进行配置的地方&#xff0c;接下来我把具体步骤说一下 1&#xff0c;直接点击箭头所指的地方就会出现如图界面&#xff0c;然后点击Tomcat server,使其展开点击第一个 第二步取消勾选&#xff0c;第三步选择bin的上一级然后…

用vscode仿制小米官网

html内容: <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><link rel&quo…

牛客NC93 设计LRU缓存结构【hard 链表,Map Java】

题目 题目链接&#xff1a; https://www.nowcoder.com/practice/5dfded165916435d9defb053c63f1e84 思路 双向链表map最新的数据放头结点&#xff0c;尾节点放最老的数据&#xff0c;没次移除尾巴节点本地考察链表的新增&#xff0c;删除&#xff0c;移动节点参考答案Java im…

UNITY实战进阶-BatchRendererGroup+Jobs+Burst+RVO2+GPUAnimation 实现万人团战(一)

研究思路&#xff1a;GPUAnimation把动画放入GPU中处理&#xff0c;BatchRendererGroup进行动态批量渲染处理&#xff0c;JobsBurst进行多线程处理逻辑&#xff08;移动、攻击等&#xff09;&#xff0c;RVO2采用Jobs的寻路导航。 准备工作&#xff1a; Editor > Project S…

PCI总线学习笔记:读写篇

前言 最近在写E1000网卡的驱动&#xff0c;这其中涉及到了PCI总线的相关内容。但是网上大部分关于PCI的文章都只局限在概念上的描述&#xff0c;并没有给出具体的例子来解释。这其实也是情理之中的&#xff0c;因为PCI总线规范就像是一个抽象的接口&#xff0c;其具体怎么实现…

正确使用@Autowired

目录 一、前言二、跟着官方文档&#xff0c;学习正确使用Autowired0、实验环境1、通过构造方法进行注入1.1 问题1&#xff1a;那万一没有这个CustomerPreferenceDao对象&#xff0c;会报错吗&#xff1f; 2、通过setter方法注入3、通过方法注入&#xff08;这个方法可以是任意名…

为什么苹果 Mac 电脑需要使用清理软件?

尽管 Apple Mac 电脑因其卓越的性能、简洁高效的 macOS 操作系统及独特的美学设计备受全球用户青睐&#xff0c;但任何电子设备在长期使用后都难以避免面临系统资源日渐累积的问题。其中一个重要维护需求在于&#xff0c;随着使用时间的增长&#xff0c;Mac电脑可能会由于系统垃…

go库x/text缺陷报告CVE-2022-32149的处理方案

#问题描述 go库 golang.org/x/text &#xff0c;注意这里不是go的源码&#xff0c; 在0.3.8版本之前存在一个缺陷(Vulnerability) 缺陷ID CVE-2022-32149 具体描述 攻击者可以通过制作一个Accept-Language报头来导致拒绝服务。 具体的原因是&#xff0c;在解析这个Accept-L…

数据结构__顺序表和单链表

顺序表的改进 问题&#xff1a; 1. 中间/头部的插入删除&#xff0c;时间复杂度为O(N) 2. 增容需要申请新空间&#xff0c;拷贝数据&#xff0c;释放旧空间。会有不小的消耗。 3. 增容一般是呈2倍的增长&#xff0c;势必会有一定的空间浪费。例如当前容量为100&#xff0c;满了…

C++——位图和布隆过滤器

在C中&#xff0c;哈希这种思想的应用场景有很多&#xff0c;位图就是其中的一种。 位图 位图&#xff1a;位图是一种哈希思想的产物&#xff0c;可以通过它来对数据进行快速的查找的方法&#xff0c;在位图中&#xff0c;有2种状态来表示在或者不在&#xff0c;即1/0。 位图…

大数据系列 | Kafka架构分析及应用

大数据系列 | Kafka架构分析及应用 1. Kafka原理分析2. Kafka架构分析3. Kafka的应用3.1. 安装Zookeeper集群3.2. 安装Kafka集群3.3. 生产者和消费者使用3.3.1. 生产者使用3.3.1. 消费者使用 4. Kafka Controller控制器 1. Kafka原理分析 Kafka是一个高吞吐量、 持久性的分布式…

宏的使用(C语言详解)

在写一个代码生成可执行文件的过程需要经过编译和链接&#xff0c;编译又要经过三部&#xff1a;预处理&#xff0c;编译&#xff0c;汇编。 #define定义的变量和宏就是在预处理阶段会处理的。 一个简单的宏定义&#xff1a; #include<stdio.h>; #define Max(a,b) a>…

CTF之GET和POST

学过php都知道就一个简单传参&#xff0c;构造payload:?whatflag得到 flag{3121064b1e9e27280f9f709144222429} 下面是POST那题 使用firefox浏览器的插件Hackbar勾选POST传入whatflag flag{828a91acc006990d74b0cb0c2f62b8d8}

Web APIs简介 Dom

JS的组成 API API 是一些预先定义的函数&#xff0c;目的是提供应用程序与开发人员基于软件或硬件得以访问一组例程的能力&#xff0c;而又无需访问源码&#xff0c;或理解内部工作机制的细节 简单理解&#xff1a;API是给程序员提供的一种工具&#xff0c;以便能更轻松的实现…