参考链接:https://blog.csdn.net/fangye945a/article/details/84933234
QT获取天气信息一般都是通过调用天气服务器的接口来获取的,而获取天气的接口有很多,大家可以自行在网上查找。
源码找到了,写的随意了点,别建议
链接:https://pan.baidu.com/s/13ALzONHXh0cDEPNhiK6SPw
提取码:s8js
本示例采用的获取天气的服务器接口为: http://wthrcdn.etouch.cn/weather_mini,请求参数名为city,参数内容为要查询天气的城市名称(utf8字符串)。请求方式为GET。
其他API可以阿里云上找一找
使用QT调用天气接口则需要用到网络类,通过HTTP请求数据。
别忘了Pro文件中添加 QT+=network
我的程序示例:比较简单这里没有附上程序代码,但我将程序中的获取天气的类放置文章末尾,代码写的比较随意,参考参考即可
weather.h
/** 天气获取类*/#ifndef WEATHER_H
#define WEATHER_H#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMap>
#include <QMultiMap>class Weather : public QObject
{Q_OBJECT
public:explicit Weather(QObject *parent = nullptr);explicit Weather(QString cityName = "");public:void setCityName(QString cityName); //设置城市名QString getCityName(); //获取城市名QString getDate(); //获取当前日期QString getFengLi(); //获取风向风力QString getWenDu(); //获取温度范围QString getTianQiType(); //获取天气类型QString getCurrentWendu(); //获取当前温度QString getGanMaoInfo(); //获取感冒提示QString getAllInfo(); //获取原始的所有字段bool isGetDataSuccessd(); //是否成功获取数据void refresh(); //刷新QMap<QString, QMap<QString, QString> > getDataMap(bool *ok=nullptr); //获取昨天以及未来5天的天气预测void print_Debug_allinfoMap(); //调试打印所有信息signals:void getDataFinisedSignal();//获取数据结束的信号void getDataSuccessedSignal();//获取数据成功的信号void getDataFailedSignal();//获取数据失败的信号public slots:void replyFinished(QNetworkReply *reply);//刷新的槽private:void queryWeather();//查询private:QString cityName;QNetworkAccessManager *manager; //请求句柄QString allinfo; //所有信息//以下皆是当天,未来几天的数据框通过获取日期的数据列表QString date;//当前日期QString fengli; //风力QString wendu; //温度QString currentwendu;//当前温度QString weather_type; //天气类型QString ganmao;//对于感冒提示bool isGetData=false;//是否成功获取数据QMap<QString,QMap<QString,QString>> dataMap;
};#endif // WEATHER_H
weather.cpp
/** 天气获取类*/
#include "weather.h"Weather::Weather(QObject *parent) : QObject(parent)
{manager = new QNetworkAccessManager(this); //新建QNetworkAccessManager对象connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));//关联信号和槽
}Weather::Weather(QString cityName)
{manager = new QNetworkAccessManager(this); //新建QNetworkAccessManager对象connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));//关联信号和槽this->cityName=cityName;refresh();
}void Weather::setCityName(QString cityName)
{this->cityName=cityName;
}QString Weather::getCityName()
{return this->cityName;
}/** 获取当前日期*/
QString Weather::getDate()
{return this->date;
}QString Weather::getFengLi()
{return this->fengli;
}QString Weather::getWenDu()
{return this->wendu;
}QString Weather::getTianQiType()
{return this->weather_type;
}QString Weather::getCurrentWendu()
{return this->currentwendu;
}QString Weather::getGanMaoInfo()
{return this->ganmao;
}QString Weather::getAllInfo()
{return this->allinfo;
}bool Weather::isGetDataSuccessd()
{return this->isGetData;
}/** 刷新天气*/
void Weather::refresh()
{this->currentwendu.clear();this->wendu.clear();this->ganmao.clear();this->fengli.clear();this->weather_type.clear();this->allinfo.clear();queryWeather();dataMap.clear();//刷新的清空,待获取时在加载
}QMap<QString, QMap<QString, QString> > Weather::getDataMap(bool *ok)
{bool Oktemp;if(ok==nullptr)ok=&Oktemp;if(!this->dataMap.isEmpty()){*ok=true;return this->dataMap;}*ok=false;if(!this->isGetData)return this->dataMap;QJsonParseError err;QJsonDocument json_recv = QJsonDocument::fromJson(allinfo.toUtf8(),&err);//解析json对象qDebug() <<"Json-Error:"<< err.error;if(!json_recv.isNull()){QJsonObject object = json_recv.object();if(object.contains("data")){QJsonValue value = object.value("data"); // 获取指定 key 对应的 valueif(value.isObject()){QJsonObject object_data = value.toObject();if(object_data.contains("yesterday")&&object_data.contains("forecast"))//若存在昨天及预测天气则加载所有数据{QJsonValue value=object_data.value("yesterday");if(value.isObject()){QMap<QString,QString>mapvalue;mapvalue["high"]=value.toObject().value("high").toString();mapvalue["low"]=value.toObject().value("low").toString();mapvalue["fengxiang"]=value.toObject().value("fx").toString();mapvalue["fengli"]=value.toObject().value("fl").toString();mapvalue["type"]=value.toObject().value("type").toString();dataMap[value.toObject().value("date").toString()]=mapvalue;}value = object_data.value("forecast");if(value.isArray()){QJsonArray valueArray=value.toArray();qDebug()<<"WeatherData count:"<<valueArray.count();for(int i=0;i<valueArray.count();i++){QJsonObject object = valueArray.at(i).toObject();QMap<QString,QString>mapvalue;mapvalue["high"]=object.value("high").toString();mapvalue["low"]=object.value("low").toString();mapvalue["fengxiang"]=object.value("fengxiang").toString();mapvalue["fengli"]=object.value("fengli").toString();mapvalue["type"]=object.value("type").toString();dataMap[object.value("date").toString()]=mapvalue;}/* json接收的原字段{"data":{"yesterday":{"date":"17日星期六","high":"高温 32℃","fx":"北风","low":"低温 19℃","fl":"<![CDATA[3-4级]]>","type":"晴"},"city":"北京","forecast":[{"date":"18日星期天","high":"高温 32℃","fengli":"<![CDATA[<3级]]>","low":"低温 21℃","fengxiang":"北风","type":"晴"},{"date":"19日星期一","high":"高温 31℃","fengli":"<![CDATA[<3级]]>","low":"低温 22℃","fengxiang":"南风","type":"多云"},{"date":"20日星期二","high":"高温 25℃","fengli":"<![CDATA[<3级]]>","low":"低温 20℃","fengxiang":"南风","type":"小雨"},{"date":"21日星期三","high":"高温 31℃","fengli":"<![CDATA[<3级]]>","low":"低温 21℃","fengxiang":"北风","type":"多云"},{"date":"22日星期四","high":"高温 30℃","fengli":"<![CDATA[<3级]]>","low":"低温 22℃","fengxiang":"北风","type":"晴"}],"ganmao":"各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。","wendu":"24"},"status":1000,"desc":"OK"}
*/qDebug()<<QString::fromLocal8Bit("获取天气成功");*ok=true;return dataMap;}}}}}else{qDebug()<<"json_recv is NULL or is not a object !!";}return dataMap;
}/** qDebug打印Map数据*/
void Weather::print_Debug_allinfoMap()
{getDataMap();qDebug()<<endl;qDebug()<<"city:"<<this->cityName;qDebug()<<"wendu:"<<this->wendu;qDebug()<<"currentwendu:"<<this->currentwendu;qDebug()<<"fengli:"<<this->fengli;qDebug()<<"weather_type:"<<this->weather_type;qDebug()<<"ganmao:"<<this->ganmao;QString str;foreach (QString key, dataMap.keys()) {str="date"+key+"[";foreach (QString key1, dataMap.value(key).keys()) {
// qDebug()<<key1<<dataMap.value(key).value(key1);str+=key1+':'+dataMap.value(key).value(key1)+' ';}str+=']';qDebug()<<str;}dataMap.clear();
}void Weather::replyFinished(QNetworkReply *reply)
{this->isGetData=false;qDebug()<<"recv weather data!!";allinfo = reply->readAll();
// ui->textEdit->setText(all); //将接收到的数据显示出来QJsonParseError err;QJsonDocument json_recv = QJsonDocument::fromJson(allinfo.toUtf8(),&err);//解析json对象qDebug() <<"Json-Error:"<< err.error;if(!json_recv.isNull()){QJsonObject object = json_recv.object();if(object.contains("data")){QJsonValue value = object.value("data"); // 获取指定 key 对应的 valueif(value.isObject()){QJsonObject object_data = value.toObject();this->cityName=object_data.value("city").toString();this->currentwendu=object_data.value("wendu").toString();this->ganmao=object_data.value("ganmao").toString();if(object_data.contains("forecast")){QJsonValue value = object_data.value("forecast");if(value.isArray()){QJsonObject today_weather = value.toArray().at(0).toObject();weather_type = today_weather.value("type").toString();date = today_weather.value("date").toString();QString low = today_weather.value("low").toString();QString high = today_weather.value("high").toString();wendu = low.mid(low.length()-3,4) +"-"+ high.mid(high.length()-3,4);QString strength = today_weather.value("fengli").toString();strength.remove(0,8);strength.remove(strength.length()-2,2);fengli = today_weather.value("fengxiang").toString() + strength;
// ui->type->setText(weather_type); //显示天气类型
// ui->wendu->setText(wendu); //显示温度
// ui->fengli->setText(fengli); //显示风力this->isGetData=true;}}}}}else{qDebug()<<"json_recv is NULL or is not a object !!";}reply->deleteLater(); //销毁请求对象if(isGetData){qDebug()<<QString::fromLocal8Bit("获取天气成功");emit this->getDataSuccessedSignal();}else{qDebug()<<QString::fromLocal8Bit("获取天气失败");emit this->getDataFailedSignal();}emit this->getDataFinisedSignal();
}/** 查询天气*/
void Weather::queryWeather()
{
// QString local_city = ui->lineEdit->text().trimmed(); //获得需要查询天气的城市名称char quest_array[256]="http://wthrcdn.etouch.cn/weather_mini?city=";QNetworkRequest quest;sprintf(quest_array,"%s%s",quest_array,cityName.toUtf8().data());quest.setUrl(QUrl(quest_array));quest.setHeader(QNetworkRequest::UserAgentHeader,"RT-Thread ART");/*发送get网络请求*/manager->get(quest);
}