QT版本:Qt Creator 5.7.0
QT获取天气信息一般都是通过调用天气服务器的接口来获取的,而获取天气的接口有很多,大家可以自行在网上查找。
本示例采用的获取天气的服务器接口为: http://wthrcdn.etouch.cn/weather_mini,请求参数名为city,参数内容为要查询天气的城市名称(utf8字符串)。请求方式为GET。
使用QT调用天气接口则需要用到网络类,通过HTTP请求数据。
首先在pro文件中添加:
QT += network
然后添加网络相关头文件:
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
由于从该服务器请求的天气数据是以json的形式回复的,所以需要用到JSON解析相关的头文件。
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
相关变量定义如下:
QNetworkAccessManager *manager; //请求句柄
QString fengli; //风力
QString wendu; //温度
QString weather_type; //天气类型
创建网络请求对象,连接信号与槽:
manager = new QNetworkAccessManager(this); //新建QNetworkAccessManager对象
connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));//关联信号和槽
当收到http请求回复的数据,便会调用replyFinished槽函数。
请求气数据:
void Widget::on_pushButton_clicked() //点击查询请求天气数据
{
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,local_city.toUtf8().data());
quest.setUrl(QUrl(quest_array));
quest.setHeader(QNetworkRequest::UserAgentHeader,"RT-Thread ART");
/*发送get网络请求*/
manager->get(quest);
}
回复数据处理槽函数:
void Widget::replyFinished(QNetworkReply *reply) //天气数据处理槽函数
{
qDebug()<<"recv weather data!!";
QString all = reply->readAll();
ui->textEdit->setText(all); //将接收到的数据显示出来
QJsonParseError err;
QJsonDocument json_recv = QJsonDocument::fromJson(all.toUtf8(),&err);//解析json对象
qDebug() << err.error;
if(!json_recv.isNull())
{
QJsonObject object = json_recv.object();
if(object.contains("data"))
{
QJsonValue value = object.value("data"); // 获取指定 key 对应的 value
if(value.isObject())
{
QJsonObject object_data = value.toObject();
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();
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); //显示风力
}
}
}
}
}else
{
qDebug()<<"json_recv is NULL or is not a object !!";
}
reply->deleteLater(); //销毁请求对象
}
天气请求回复的JSON数据中含有多天的详细天气信息,但在此只解析了当天的天气状态、温度和风力三个参数信息,以供参考,Demo程序演示效果如下。
获取天气demo源码链接:https://download.csdn.net/download/fangye945a/10839157