代码拉取完成,页面将自动刷新
#include "weather.h"
#include "ui_weather.h"
Weather::Weather(QWidget *parent) :
QWidget(parent),
ui(new Ui::Weather)
{
ui->setupUi(this);
weather_api = "https://restapi.amap.com/v3/weather/weatherInfo?key=" + GD_WEATHER_KEY + "&city=" + CITY;
//时间显示
time = new QTimer(this);
connect(time,SIGNAL(timeout()),this,SLOT(show_time()));
time->start(1000);
//http 查询天气链接
Network = new QNetworkAccessManager(this);
connect(Network, SIGNAL(finished(QNetworkReply *)), this, SLOT(readdata(QNetworkReply *)));
Network->get(QNetworkRequest(QUrl(weather_api)));
}
Weather::~Weather()
{
time->stop();
delete time;
delete Network;
delete ui;
qDebug()<<"~Weather"<<endl;
}
void Weather::show_time()
{
ui->Time->setText(QDateTime::currentDateTime().toString("hh:mm ")); //时间
ui->Am->setText(QDateTime::currentDateTime().toString("AP"));
ui->Date->setText(QDateTime::currentDateTime().toString("yyyy年-MM月-dd日 dddd"));//日期
Network->get(QNetworkRequest(QUrl(weather_api)));
}
void Weather::readdata(QNetworkReply *data)
{
QString msg = data->readAll();
qDebug()<<msg<<endl;
QJsonParseError json_error;
//所有JSON数据
QJsonDocument json_doucement = QJsonDocument::fromJson(msg.toUtf8(), &json_error);
//检查json是否有错误
if(json_error.error == QJsonParseError::NoError)
{
if(json_doucement.isObject())
{
//开始解析json对象
QJsonObject obj = json_doucement.object();
//lives
if(obj.contains("lives"))
{
if (obj.value("lives").isArray())
{
qDebug() << "array";
QJsonArray lives_array = obj.value("lives").toArray();
QJsonObject lives_obj = lives_array.at(0).toObject();
//city
if(lives_obj.contains("city"))
{
ui->City->setText(lives_obj.value("city").toString());
}
//weather temperature
if(lives_obj.contains("weather") && lives_obj.contains("temperature"))
{
select_image(lives_obj.value("weather").toString()); //显示天气图片
ui->Wea->setText(lives_obj.value("weather").toString() + " " + lives_obj.value("temperature").toString() + "℃");
}
}
}
}
}
}
void Weather::wea_image(QString image)
{
QString msg = image;
QPixmap pic = msg;
QPixmap temp = pic.scaled(ui->Image->width(),ui->Image->height());
ui->Image->setPixmap(temp);
}
void Weather::select_image(QString type)
{
if(type == "晴"){wea_image(":/weather_image/weathy_01.png");}
else if(type == "多云") {wea_image(":/weather_image/weathy_04.png");}
else if(type == "阴"){wea_image(":/weather_image/weathy_23.png");}
else if(type == "小雨"){wea_image(":/weather_image/weathy_07.png");}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。