#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.mzph.cn/news/798473.shtml

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

相关文章

华为海思2024春招数字芯片岗机试题(共9套)

huawei海思2024春招数字芯片岗机试题(共9套&#xff09;&#xff08;WX:didadidadidida313&#xff0c;加我备注&#xff1a;CSDN huawei数字题目&#xff0c;谢绝白嫖哈&#xff09; 题目包含数字集成电路、System Verilog、Verilog2001、半导体制造技术、高级ASIC芯片综合、…

Java实现二叉树(上)

1.树型结构 1.1树型结构的概念 树是一种 非线性 的数据结构&#xff0c;它是由 n &#xff08; n>0 &#xff09;个有限结点组成一个具有层次关系的集合。 把它叫做树是因为它看 起来像一棵倒挂的树&#xff0c;也就是说它是根朝上&#xff0c;而叶朝下的 1.2树型结构的特点…

二 maven构建项目

一 Maven的GAVP Maven工程相对之前的工程&#xff0c;多出一组gavp属性&#xff0c;gav需要我们在创建项目的时指定&#xff0c;p有默认值&#xff0c;后期通过配置文件修改。 GAVP是指 GroupId、ArtifactId、Version、Packaging 等四个属性的缩写&#xff0c;其中前三个是必…

c++的学习之路:14、list(1)

本章讲一下如何使用list&#xff0c;代码在文章末 目录 一、list介绍 二、增 三、删 四、查和改 五、交换 六、代码 一、list介绍 首先还是看一看官方文档的介绍如下图&#xff0c;如下方五点&#xff1a; 1. list是可以在常数范围内在任意位置进行插入和删除的序列式…

element-ui result 组件源码分享

今日简单分享 result 组件的源码实现&#xff0c;主要从以下三个方面&#xff1a; 1、result 组件页面结构 2、result 组件属性 3、result 组件 slot 一、result 组件页面结构 二、result 组件属性 2.1 title 属性&#xff0c;标题&#xff0c;类型 string&#xff0c;无默…

网络基础三——初识IP协议

网络基础三 ​ 数据通过应用层、传输层将数据传输到了网络层&#xff1b; ​ 传输层协议&#xff0c;如&#xff1a;TCP协议提供可靠性策略或者高效性策略&#xff0c;UDP提供实时性策略&#xff0c;保证向下层交付的数据是符合要求的的&#xff1b;而网络层&#xff0c;如&a…

【动态规划-状态压缩dp】【蓝桥杯备考训练】:毕业旅行问题、蒙德里安的梦想、最短Hamilton路径、国际象棋、小国王【已更新完成】

目录 1、毕业旅行问题&#xff08;今日头条2019笔试题&#xff09; 2、蒙德里安的梦想&#xff08;算法竞赛进阶指南&#xff09; 3、最短Hamilton路径&#xff08;《算法竞赛进阶指南》&模板&#xff09; 4、国际象棋&#xff08;第十二届蓝桥杯省赛第二场C A组/B组&#…

Java初始——IDEA-web的启动

Tomcat 文件夹作用 bin 启动 关闭的脚本文件 conf 配置 lib 依赖的jar包 logs 日志 temp 临时文件 webapps 存放的网站 Maven 1.在javaweb中&#xff0c;需要使用大量的jar包&#xff0c;手动导入 2.Maven 架构管理工具 核心&#xff1a;约定大于配置 必须按照规则 web idea-we…

2024.4.7

1. 2列火车 #include<myhead.h>pthread_mutex_t m1; pthread_mutex_t m2;void* run(void* arg) {while(1){pthread_mutex_lock(&m1);printf("火车B进入\n");printf("A请等待\n");pthread_mutex_unlock(&m2);sleep(2);} }int main(in…

开发项目接单报价快速计算,报价量化程序

定制化开发&#xff0c;如何计算项目预算&#xff0c;是程序开发者头疼的一个问题。 项目费用谈得过低&#xff0c;就天天加班累死赚不到钱&#xff1b;谈得过高&#xff0c;会导致顾客流失&#xff0c;信誉受损。 项目费用量化可见是多么重要。 下面是一段量化的程序&#…

跟TED演讲学英文:AI isn‘t the problem — it‘s the solution by Andrew Ng

TED英文文稿 文章目录 TED英文文稿AI isnt the problem — its the solutionIntroductionVocabularyTranscriptSummary 2024年4月6日学习吴恩达的这篇演讲 AI isn’t the problem — it’s the solution Link: AI isn’t the problem — it’s the solution Speaker: Andrew …

C语言进阶课程学习记录-第21课 - 宏定义与使用分析

C语言进阶课程学习记录-第21课 - 宏定义与使用分析 宏定义的本质实验-字面量比较宏定义表达式实验-表达式有效性宏的作用域实验-作用域分析内置宏内置宏演示小结 本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程&#xff0c;图片全部来源于课程PPT&#xff0c;仅用于个人学…

人工智能 - 服务于谁?

人工智能服务于谁&#xff1f; 人工智能服务于生存&#xff0c;其最终就是服务于战争&#xff08;热战、技术战、经济战&#xff09; 反正就是为了活着而战的决策。 既然人工智能所有结果&#xff0c;来自大数据的分挖掘&#xff08;分析&#xff09;也就是数据的应用&#x…

自动驾驶中的交通标志识别原理及应用

自动驾驶中的交通标志识别原理及应用 附赠自动驾驶学习资料和量产经验&#xff1a;链接 概述 道路交通标志和标线时引导道路使用者有秩序使用道路&#xff0c;以促进道路行车安全&#xff0c;而在驾驶辅助系统中对交通标志的识别则可以不间断的为整车控制提供相应的帮助。比如…

Transformer位置编码详解

在处理自然语言时候&#xff0c;因Transformer是基于注意力机制&#xff0c;不像RNN有词位置顺序信息&#xff0c;故需要加入词的位置信息来显示的表明词的上下文关系。具体是将词经过位置编码(positional encoding)&#xff0c;然后与emb词向量求和&#xff0c;作为编码块(Enc…

CAS Server使用Maven构建以及自定义扩展使用

介绍 ​CAS&#xff08;Central Authentication Service&#xff09;中心授权/认证服务&#xff0c;是由耶鲁大学发起的一个开源项目&#xff0c;距今已有20年之久&#xff0c;功能相当丰富&#xff0c;目的在于为Web应用系统提供一种可靠且稳定的单点登录解决方案。 CAS分为…

Open CASCADE学习|在给定的TopoDS_Shape中查找与特定顶点 V 对应的TopoDS_Edge编号

enum TopAbs_ShapeEnum{TopAbs_COMPOUND,TopAbs_COMPSOLID,TopAbs_SOLID,TopAbs_SHELL,TopAbs_FACE,TopAbs_WIRE,TopAbs_EDGE,TopAbs_VERTEX,TopAbs_SHAPE}; 这段代码定义了一个名为 TopAbs_ShapeEnum 的枚举类型&#xff0c;它包含了表示不同几何形状类型的常量。这些常量通常…

目标检测——色素性皮肤病数据集

一、重要性及意义 首先&#xff0c;色素性皮肤病变是一类常见的皮肤疾病&#xff0c;其发病率有逐年增高的趋势。这些病变可能由遗传或环境因素导致黑素细胞生成异常&#xff0c;如黑色素瘤等。黑色素瘤具有极高的恶性率和致死率&#xff0c;而且恶化可能性大&#xff0c;容易…

openplc Linux 地址映射io,读写驱动数据等使用记录

1. 上一篇记录 openplc使用C语言文件读写驱动实现基本流程。 openPLC_Editor C语言编程 在mp157 arm板上调用io等使用记录_openplc c 编程-CSDN博客 2. 下面通过映射地址的方式控制io和读写驱动数据。 在runtime 环境的 hardware 硬件配置中 选择 python on Linux(PSM)&#…

柱状图中最大的矩形-java

题目描述(力扣题库 84): 给定 n 个非负整数&#xff0c;用来表示柱状图中各个柱子的高度。每个柱子彼此相邻&#xff0c;且宽度为 1 。求在该柱状图中&#xff0c;能够勾勒出来的矩形的最大面积。 解题思想: 单调栈: 利用先进后出的思想, 先算出长度更高的柱子所能勾勒…