Qt天气预报系统获取天气数据
1、获取天气数据1.1添加天气类头文件
鼠标放到项目上, 右键选择Add New... https://i-blog.csdnimg.cn/direct/6ec9eb3e73f34379800107bc66dcafd2.png
选择C++,选择C++Header File https://i-blog.csdnimg.cn/direct/0383046ed3a744deb18c6eaf19ee9b76.png
起名为weatherData https://i-blog.csdnimg.cn/direct/b5a89909c6964edd9b587c2e7997b3d0.png
1.2定义本日和未来几每天气数据类
//今天的数据类
class Today{
public:
Today()
{
city ="广州"; //城市
date ="2025-1-10";//日期
weatherType ="多云"; //天气类型
highTem = 30; //最高温
lowTem = 18; //最低温
ganMao ="感冒指数"; //感冒指数
Temperature = 0; //温度
Humidity = "0%"; //湿度
PM25 = 0; //PM2.5
windType ="南风"; //风的类型
windPower ="2级"; //风力
airQuality ="无数据"; //空气质量
}
QString city;
QString date;
int Temperature;
QString weatherType;
int highTem;
int lowTem;
QString ganMao;
QString Humidity;
int PM25;
QString windType;
QString windPower;
QString airQuality;
};
//未来几天的数据类
class Day{
public:
Day()
{
week ="周五"; //星期
date ="2023-7-29"; //日期
weatherType ="多云"; //天气类型
airQuality = 0; //空气指数,优 //空气质量
highTem = 0; //最高温
lowTem = 0; //最低温
windType ="南风"; //风的类型
windPower ="2级"; //风力
}
QString week;
QString date;
QString weatherType;
int airQuality;
int highTem;
int lowTem;
QString windType;
QString windPower;
};
1.3定义一个解析JSON数据的函数
void parseJson(QByteArray& byteArray); //解析JSON数据
1.4在mainwindow中添加weatherData.h
#include "weatherData.h"
1.5创建今每天气数据和未来几每天气数据对象
Today today; //定义一个今天天气数据对象
Day day; //定义未来几天天气数据对象
1.6添加parseJson定义
https://i-blog.csdnimg.cn/direct/0192ffc75a584675b9d989aa98a85b2c.png
1.7把解析JSON数据添加进去
void MainWindow::readHttpReply(QNetworkReply *reply)
{
int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); //状态码
//请求错误
if(reply->error() != QNetworkReply::NoError || status_code != 200)
{
qDebug() << reply->errorString().toLatin1().data(); //打印错误信息
QMessageBox::warning(this,"天气","请求数据失败", QMessageBox::Ok); //弹出警告信息框
}
//请求成功
else
{
QByteArray byteArray = reply->readAll(); //读取服务器数据
qDebug() << "read all:"<< byteArray.data(); //打印接收到的数据
parseJson(byteArray); //解析JSON数据
}
reply->deleteLater(); //释放对象
}
1.8添加错误
//解析JSON格式天气数据
void MainWindow::parseJson(QByteArray &byteArray)
{
//错误
QJsonParseError err;
}
鼠标放到QJsonParseError上, ALT+Enter选择添加头文件,背面的也雷同,使用一个
新类的时候,记得添加头文件 https://i-blog.csdnimg.cn/direct/fdd87e0a94ea4b07ba6c1e48d230ea97.png
1.9解析整个天气数据
//解析JSON格式天气数据
void MainWindow::parseJson(QByteArray &byteArray)
{
//错误
QJsonParseError err; //创建一个错误对象
QJsonDocument doc = QJsonDocument::fromJson(byteArray, &err); //将JSON格式解析为QJsonDocument对象
//如果错误
if(err.error != QJsonParseError::NoError)
{
return; //返回
}
QJsonObject rootObj = doc.object(); //创建一个QJsonObject对象返回文档
// qDebug() << rootObj.value("message").toString();
//1.解析城市和日期
today.city = rootObj.value("cityInfo").toObject().value("city").toString(); //城市
today.date = rootObj.value("date").toString(); //日期
//2.解析昨天yesterday数据
QJsonObject objData = rootObj.value("data").toObject(); //获取data对象
QJsonObject objYesterday = objData.value("yesterday").toObject(); //昨天
day.week = objYesterday.value("week").toString(); //星期
day.date = objYesterday.value("date").toString(); //日期
day.weatherType = objYesterday.value("type").toString(); //天气类型
QString highT; //最高温
highT = objYesterday.value("high").toString().split(" ").at(1); //空格分割,取分割后第二个数据,1是第二个,0是第一个
day.highTem = highT.left(highT.length() - 1).toInt(); //把℃减掉,只剩数字
QString lowT; //最低温
lowT = objYesterday.value("low").toString().split(" ").at(1);
day.lowTem = lowT.left(lowT.length() - 1).toInt();
//风的类型,风力
day.windType = objYesterday.value("fx").toString(); //风的类型
day.windPower = objYesterday.value("fl").toString(); //风力
//空气指数
day.airQuality =objYesterday.value("aqi").toDouble(); //空气质量
//3.解析未来几天的天气数据
QJsonArray forecastArray = objData.value("forecast").toArray(); //获取forecast数组
//遍历未来几天天气数据
for(int i=0 ; i<6 ; i++)
{
QJsonObject forecastObj = forecastArray.toObject(); //获取JSON对象
day.week = forecastObj.value("week").toString(); //星期
day.date = forecastObj.value("ymd").toString(); //日期
day.weatherType = forecastObj.value("type").toString(); //天气类型
//空气指数
day.airQuality =forecastObj.value("aqi").toDouble(); //空气质量
QString highT; //最高温
highT = forecastObj.value("high").toString().split(" ").at(1); //空格分割,取分割后第二个数据,1是第二个,0是第一个
day.highTem = highT.left(highT.length() - 1).toInt(); //把℃减掉,只剩数字
QString lowS; //最低温
lowS = forecastObj.value("low").toString().split(" ").at(1);
day.lowTem = lowS.left(lowS.length() - 1).toInt();
//风的类型,风力
day.windType = forecastObj.value("fx").toString(); //风的类型
day.windPower = forecastObj.value("fl").toString(); //风力
//4、解析今天的数据
today.Temperature =objData.value("wendu").toInt(); //温度
today.ganMao =objData.value("ganmao").toString(); //感冒指数
today.Humidity = objData.value("shidu").toString(); //湿度
today.PM25 = objData.value("pm25").toDouble(); //PM2.5
today.airQuality = objData.value("quality").toString(); //空气质量
//forecast里面也有今天的数据
today.weatherType = day.weatherType; //天气类型
today.highTem = day.highTem; //最高温
today.lowTem = day.lowTem; //最低温
today.windType = day.windType; //风的类型
today.windPower = day.windPower; //风力
}
}
2、.h文件和.cpp文件
2.1 mainwindow.h文件
#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include <QMenu>#include <QMessageBox>#include <QNetworkAccessManager>#include <QNetworkReply>#include "weatherData.h"
QT_BEGIN_NAMESPACEnamespace Ui { class MainWindow; }QT_END_NAMESPACEclass MainWindow : public QMainWindow{ Q_OBJECTpublic: MainWindow(QWidget *parent = nullptr); ~MainWindow();protected: void mousePressEvent(QMouseEvent *event) override; //重写鼠标点击事件函数 void mouseMoveEvent(QMouseEvent *event) override; //重写鼠标移动事件函数 void getWeatherInfo(QString citycode); //获取天气数据 void parseJson(QByteArray& byteArray); //解析JSON数据
private slots: void on_pushButton_quit_clicked(); //关闭UI界面 void onQuitActTriggered(); //菜单被点击后的处理public slots: void readHttpReply(QNetworkReply *reply); //新建一个网络请求获取的槽函数private: Ui::MainWindow *ui; QMenu *quitMenu; //创建一个菜单指针 QAction *quitAct; //定义一个动作 QPoint moffset; //窗口移动时,鼠标与窗口左上角的偏移值 QNetworkAccessManager *NetAccessManger; //声明一个网络请求对象 bool closePOPWindow(); //关闭窗口的弹窗 Today today; //定义一个今每天气数据对象 Day day; //定义未来几每天气数据对象};#endif // MAINWINDOW_H 2.2weatherData.h文件
#ifndef WEATHERDATA_H
#define WEATHERDATA_H
#include <QString>
//今天的数据类
class Today{
public:
Today()
{
city ="广州"; //城市
date ="2025-1-10";//日期
weatherType ="多云"; //天气类型
highTem = 30; //最高温
lowTem = 18; //最低温
ganMao ="感冒指数"; //感冒指数
Temperature = 0; //温度
Humidity = "0%"; //湿度
PM25 = 0; //PM2.5
windType ="南风"; //风的类型
windPower ="2级"; //风力
airQuality ="无数据"; //空气质量
}
QString city;
QString date;
int Temperature;
QString weatherType;
int highTem;
int lowTem;
QString ganMao;
QString Humidity;
int PM25;
QString windType;
QString windPower;
QString airQuality;
};
//未来几天的数据类
class Day{
public:
Day()
{
week ="周五"; //星期
date ="2023-7-29"; //日期
weatherType ="多云"; //天气类型
airQuality = 0; //空气指数,优 //空气质量
highTem = 0; //最高温
lowTem = 0; //最低温
windType ="南风"; //风的类型
windPower ="2级"; //风力
}
QString week;
QString date;
QString weatherType;
int airQuality;
int highTem;
int lowTem;
QString windType;
QString windPower;
};
#endif // WEATHERDATA_H
2.3 .cpp文件
#include "mainwindow.h"#include "ui_mainwindow.h"#include <QJsonArray>#include <QJsonObject>#include <QJsonParseError>#include <QMouseEvent>#include "weatherData.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow){ ui->setupUi(this); setWindowFlag(Qt::FramelessWindowHint); // this->setLayout(ui->gridLayoutGlobal); //让界面随着窗口变幻巨细 quitMenu = new QMenu(this); //创建一个QMenu对象 quitAct = new QAction(QIcon(":/widget/quit.png"), tr("退出"), this); //定义一个退出动作 quitMenu->addAction(quitAct); //添加动作 // connect(quitMenu,&QMenu::triggered,this,[=]{ // this->close(); // }); //毗连信号与槽 connect(quitMenu,&QMenu::triggered,this,&MainWindow::onQuitActTriggered); //毗连菜单被触发的信号与槽 NetAccessManger = new QNetworkAccessManager(this); //实例化一个网络请求对象 connect(NetAccessManger,&QNetworkAccessManager::finished,this,&MainWindow::readHttpReply);//毗连网络请求获取的信号与槽 //101010100是北京的都会编码 getWeatherInfo("101010100");}MainWindow::~MainWindow(){ delete ui;}//鼠标点击void MainWindow::mousePressEvent(QMouseEvent *event){ //如果右键被按下 if(event->button() == Qt::RightButton) { quitMenu->exec(QCursor::pos()); //在当前鼠标位置表现菜单 } //当前鼠标位置 event->globalPos() //当前窗口位置 this->pos() if(event->button() == Qt::LeftButton) { moffset = event->globalPos() - this->pos(); }}//鼠标移动void MainWindow::mouseMoveEvent(QMouseEvent *event){ this->move(event->globalPos() - moffset); //移动窗口}//弹窗bool MainWindow::closePOPWindow(){ // 创建一个消息框询问用户是否真的要退出 QMessageBox mes; mes.setWindowTitle("关闭窗口"); //mes.setWindowFlags(Qt::Drawer); //把标题栏去掉 mes.setIcon(QMessageBox::Warning); //设置一个告诫图片 mes.setText("是否关闭窗口?"); //弹窗文本 mes.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); //设置两个按钮 mes.setWindowIcon(QIcon(":/widget/dog.png")); // 设置窗口图标 mes.setButtonText(QMessageBox::Ok, tr("确定")); //ok改为确认 mes.setButtonText(QMessageBox::Cancel, tr("取消")); //Cancel改为取消 // 表现消息框并期待用户交互 int result = mes.exec(); // 根据用户的选择执行相应的操作 if (result == QMessageBox::Ok) { // 用户选择了确定,关闭主窗口 this->close(); return true; } // 用户选择了取消,不关闭主窗口 else { return false; // 窗口关闭操作失败 }}//右上角退出void MainWindow::on_pushButton_quit_clicked(){ closePOPWindow();}//鼠标右键退出void MainWindow::onQuitActTriggered(){ closePOPWindow();}//获取天气数据void MainWindow::getWeatherInfo(QString citycode){ QUrl url("http://t.weather.itboy.net/api/weather/city/" + citycode); //天气数据接口和都会编码 NetAccessManger->get(QNetworkRequest(url)); //发送GET请求,获取数据}//解析JSON格式天气数据void MainWindow::parseJson(QByteArray &byteArray){ //错误 QJsonParseError err; //创建一个错误对象 QJsonDocument doc = QJsonDocument::fromJson(byteArray, &err); //将JSON格式解析为QJsonDocument对象 //如果错误 if(err.error != QJsonParseError::NoError) { return; //返回 } QJsonObject rootObj = doc.object(); //创建一个QJsonObject对象返回文档 // qDebug() << rootObj.value("message").toString(); //1.解析都会和日期 today.city = rootObj.value("cityInfo").toObject().value("city").toString(); //都会 today.date = rootObj.value("date").toString(); //日期 //2.解析昨天yesterday数据 QJsonObject objData = rootObj.value("data").toObject(); //获取data对象 QJsonObject objYesterday = objData.value("yesterday").toObject(); //昨天 day.week = objYesterday.value("week").toString(); //星期 day.date = objYesterday.value("date").toString(); //日期 day.weatherType = objYesterday.value("type").toString(); //天气类型 QString highT; //最高温 highT = objYesterday.value("high").toString().split(" ").at(1); //空格分割,取分割后第二个数据,1是第二个,0是第一个 day.highTem = highT.left(highT.length() - 1).toInt(); //把℃减掉,只剩数字 QString lowT; //最低温 lowT = objYesterday.value("low").toString().split(" ").at(1); day.lowTem = lowT.left(lowT.length() - 1).toInt(); //风的类型,风力 day.windType = objYesterday.value("fx").toString(); //风的类型 day.windPower = objYesterday.value("fl").toString(); //风力 //空气指数 day.airQuality =objYesterday.value("aqi").toDouble(); //空气质量 //3.解析未来几天的天气数据 QJsonArray forecastArray = objData.value("forecast").toArray(); //获取forecast数组 //遍历未来几每天气数据 for(int i=0 ; i<6 ; i++) { QJsonObject forecastObj = forecastArray.toObject(); //获取JSON对象 day.week = forecastObj.value("week").toString(); //星期 day.date = forecastObj.value("ymd").toString(); //日期 day.weatherType = forecastObj.value("type").toString(); //天气类型 //空气指数 day.airQuality =forecastObj.value("aqi").toDouble(); //空气质量 QString highT; //最高温 highT = forecastObj.value("high").toString().split(" ").at(1); //空格分割,取分割后第二个数据,1是第二个,0是第一个 day.highTem = highT.left(highT.length() - 1).toInt(); //把℃减掉,只剩数字 QString lowS; //最低温 lowS = forecastObj.value("low").toString().split(" ").at(1); day.lowTem = lowS.left(lowS.length() - 1).toInt(); //风的类型,风力 day.windType = forecastObj.value("fx").toString(); //风的类型 day.windPower = forecastObj.value("fl").toString(); //风力 //4、解析本日的数据 today.Temperature =objData.value("wendu").toInt(); //温度 today.ganMao =objData.value("ganmao").toString(); //感冒指数 today.Humidity = objData.value("shidu").toString(); //湿度 today.PM25 = objData.value("pm25").toDouble(); //PM2.5 today.airQuality = objData.value("quality").toString(); //空气质量 //forecast里面也有本日的数据 today.weatherType = day.weatherType; //天气类型 today.highTem = day.highTem; //最高温 today.lowTem = day.lowTem; //最低温 today.windType = day.windType; //风的类型 today.windPower = day.windPower; //风力 }}//网络请求获取void MainWindow::readHttpReply(QNetworkReply *reply)
{
int status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); //状态码
//请求错误
if(reply->error() != QNetworkReply::NoError || status_code != 200)
{
qDebug() << reply->errorString().toLatin1().data(); //打印错误信息
QMessageBox::warning(this,"天气","请求数据失败", QMessageBox::Ok); //弹出警告信息框
}
//请求成功
else
{
QByteArray byteArray = reply->readAll(); //读取服务器数据
qDebug() << "read all:"<< byteArray.data(); //打印接收到的数据
parseJson(byteArray); //解析JSON数据
}
reply->deleteLater(); //释放对象
}
获取天气数据完成!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]