QT-天气预报

QT-天气预报

项目概述

  • stylesheet界面美化
  • Json数据解析
  • HTTP通信
  • 自定义控件绘制温度
  • 多控件

页面展示
在这里插入图片描述

鼠标右键退出

menuquit=new QMenu(this);
    QAction *closeAct = new QAction(QIcon(":/res/close.png"), tr("退出"), this);
    menuquit->addAction(closeAct);
    connect(menuquit,&QMenu::triggered,this,[=](){
            this->close();
    });

//右键退出
void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::RightButton)
    {
        //qDebug()<<"Right is clicked";
        menuquit->exec(QCursor::pos());
    }
}

鼠标左键移动

if(event->button()==Qt::LeftButton)
{
    myOffset=event->globalPos()-this->pos();
}
//鼠标左键移动
void Widget::mouseMoveEvent(QMouseEvent *event)
{
     this->move(event->globalPos()-myOffset);
}

天气预报数据接口

第一种

http://t.weather.itboy.net/api/weather/city/101010100

第二种

http://v1.yiketianqi.com/api?
unescape=1&version=v61&appid=26371314&appsecret=qOhoD413

读取天气预报的数据

//由QNetworkAccessManager发起get请求
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QUrl urlItBoy("http://t.weather.itboy.net/api/weather/city/101010100");
QUrl urltianqi("http://v1.yiketianqi.com/api?unescape=1&version=v61&appid=26371314&appsecret=qOhoD413");
//指定请求的url地址
QNetworkRequest res(urlItBoy);
reply=manager->get(res);
//QNetworkRequest网络请求后读取数据
connect(reply,&QNetworkReply::finished,this,&Widget::readHttpReply);
//读取天气预报的数据
void Widget::readHttpReply()
{
    QByteArray   data=reply->readAll();
    qDebug()<<QString::fromUtf8(data);
}

处理网络请求失败

//读取天气预报的数据
void Widget::readHttpReply()
{
    int  resCode=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    if(reply->error()==QNetworkReply::NoError&&resCode==200)
    {
        QByteArray   data=reply->readAll();
        qDebug()<<QString::fromUtf8(data);
    }
    else
    {
        //qDebug()<<"请求失败"<<reply->errorString();
        QMessageBox  mes;
        mes.setWindowTitle("错误");
        mes.setText("网络请求失败");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}

刷新当天的天气数据

void Widget::parseWeatherJsonData(QByteArray rawData)
{
    QJsonDocument jsonObj=QJsonDocument::fromJson(rawData);
    if(!jsonObj.isNull()&&jsonObj.isObject())
    {
        QJsonObject  objRoot=jsonObj.object();
        //解析日期
        QString date=objRoot["date"].toString();
        QString week=objRoot["week"].toString();
        ui->labelCurrentData->setText(date+" "+week);
        //解析城市名
        ui->labelCity->setText(objRoot["city"].toString()+"市");
        //解析当前温度
        ui->labelTmp->setText(objRoot["tem"].toString());
        ui->labelTempRange->setText(objRoot["tem2"].toString()+"~"+objRoot["tem1"].toString());
        //解析天气类型
        ui->labelWeatherType->setText(objRoot["wea"].toString());
        //解析感冒指数
        ui->labelganmao->setText(objRoot["air_tips"].toString());
        //解析风向
        ui->labelFXType->setText(objRoot["win"].toString());
        //解析风力
        ui->labelFXType_2->setText(objRoot["win_speed"].toString());
        //解析PM2.5
        ui->labelPM25Data->setText(objRoot["air_pm25"].toString());
        //解析湿度
        ui->labelshiduData->setText(objRoot["humidity"].toString());
        //解析空气质量
        ui->labelairData->setText(objRoot["air_level"].toString());
    }
}

支持不同城市天气

QString getCityCodeFromName(QString name)
{
    QFile file(":/citycode.json");
    file.open(QIODevice::ReadOnly);
    QByteArray rawData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(jsonDoc.isArray()){
        QJsonArray citys = jsonDoc.array();
        for( QJsonValue value : citys){
            if( value.isObject()){
                QString cityName = value["city_name"].toString();
                if(cityName == name){
                    return value["city_code"].toString();
                }
            }
        }
        return "";
    }
}
void Widget::on_pushButton_clicked()
{
    QString cityNameFromUser = ui->lineEditCity->text();
    QString cityCode = getCityCodeFromName(cityNameFromUser);
    if(cityCode != NULL){
        strUrl += "&cityid=" + cityCode;
        qDebug() << strUrl;
        manager->get(QNetworkRequest(QUrl(strUrl)));
    }else{
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("请输入正确的城市名");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}

QMap优化天气BUG

codecityuityls.h

#ifndef CODECITYUITLS_H
#define CODECITYUITLS_H

#include <QMap>
#include <QString>



class codeCityUitls
{
public:
    codeCityUitls();
    QMap<QString,QString> cityMap={};

    QString  getCityCodeFromName(QString cityName);
    void initCityMap();
};

#endif // CODECITYUITLS_H

codecityUityls.cpp

#include "codecityuitls.h"

#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>
codeCityUitls::codeCityUitls()
{

}

QString codeCityUitls::getCityCodeFromName(QString cityName)
{

      if(cityMap.isEmpty())
      {
          initCityMap();
      }
      QMap<QString,QString>::iterator it = cityMap.find(cityName);
      if(it==cityMap.end())
      {
          qDebug()<<cityName;
          it = cityMap.find(cityName+"市");
          if(it==cityMap.end())
          {
              it = cityMap.find(cityName+"县");
          }
          if(it==cityMap.end())
          {
              it = cityMap.find(cityName+"区");
          }
          if(it==cityMap.end())
          {
              return  " ";
          }
      }

      return it.value();
}

void codeCityUitls::initCityMap()
{
    QFile file(":/citycode.json");
    file.open(QIODevice::ReadOnly);
    QByteArray rawData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(jsonDoc.isArray()){
        QJsonArray citys = jsonDoc.array();
        for( QJsonValue value : citys){
            if( value.isObject()){
                QString cityName = value["city_name"].toString();
                QString cityCode = value["city_code"].toString();
                cityMap.insert(cityName,cityCode);
            }
        }

    }
}

天气图标刷新

 mTypeMap.insert("暴雪",":/res/type/BaoXue.png");
    mTypeMap.insert("暴雨",":/res/type/BaoYu. png");
    mTypeMap.insert("暴雨到大暴雨",":/res/type/BaoYuDaoDaBaoYu.png");
    mTypeMap.insert("大暴雨",":/res/type/DaBaoYu.png");
    mTypeMap.insert("大暴雨到特大暴雨",":/res/type/DaBaoYuDaoTeDaBaoYu.png");
    mTypeMap.insert("大到暴雪",":/res/type/DaDaoBaoXue.png");
    mTypeMap.insert("大雪",":/res/type/DaXue.png");
    mTypeMap.insert("大雨",":/res/type/DaYu.png");
    mTypeMap.insert("冻雨",":/res/type/DongYu.png");
    mTypeMap.insert("多云",":/res/type/DuoYun.png");
    mTypeMap.insert("浮沉",":/res/type/FuChen.png");
    mTypeMap.insert("雷阵雨",":/res/type/LeiZhenYu.png");
    mTypeMap.insert("雷阵雨伴有冰雹",":/res/type/LeiZhenYuBanYouBingBao.png");
    mTypeMap.insert("霾",":/res/type/Mai.png");
    mTypeMap.insert("强沙尘暴",":/res/type/QiangShaChenBao.png");
    mTypeMap.insert("晴",":/res/type/Qing.png");
    mTypeMap.insert("沙尘暴",":/res/type/ShaChenBao.png");
    mTypeMap.insert("特大暴雨",":/res/type/TeDaBaoYu.png");
    mTypeMap.insert("undefined",":/res/type/undefined.png");
    mTypeMap.insert("雾",":/res/type/Wu.png");
    mTypeMap.insert("小到中雪",":/res/type/XiaoDaoZhongXue.png");
    mTypeMap.insert("小到中雨",":/res/type/XiaoDaoZhongYu.png");
    mTypeMap.insert("小雪",":/res/type/XiaoXue.png");
    mTypeMap.insert("小雨",":/res/type/XiaoYu.png");
    mTypeMap.insert("雪",":/res/type/Xue.png");
    mTypeMap.insert("扬沙",":/res/type/YangSha.png");
    mTypeMap.insert("阴",":/res/type/Yin.png");
    mTypeMap.insert("雨",":/res/type/Yu.png");
    mTypeMap.insert("雨夹雪",":/res/type/YuJiaXue.png");
    mTypeMap.insert("阵雪",":/res/type/ZhenXue.png");
    mTypeMap.insert("阵雨",":/res/type/ZhenYu.png");
    mTypeMap.insert("中到大雪",":/res/type/ZhongDaoDaXue.png");
    mTypeMap.insert("中到大雨",":/res/type/ZhongDaoDaYu.png");
    mTypeMap.insert("中雪",":/res/type/ZhongXue.png");
    mTypeMap.insert("中雨",":/res/type/ZhongYu.png");

更新七天天气数据

void Widget::parseWeatherJsonDataNew(QByteArray rawData)
{
    QJsonDocument jsonDoc=QJsonDocument::fromJson(rawData);
    if(!jsonDoc.isNull()&&jsonDoc.isObject())
    {
        QJsonObject jsonRoot=jsonDoc.object();
        days[0].mCity=jsonRoot["city"].toString();
        days[0].mPm25=jsonRoot["aqi"].toObject()["pm25"].toString();
        if(jsonRoot.contains("data")&&jsonRoot["data"].isArray())
        {
             QJsonArray weathArray=jsonRoot["data"].toArray();
             for(int i=0;i<weathArray.size();i++)
             {
                  QJsonObject obj=weathArray[i].toObject();
                  //qDebug()<<obj["date"].toString()<<obj["wea"].toString();
                  days[i].mDate=obj["date"].toString();
                  days[i].mWeek=obj["week"].toString();
                  days[i].mWeathType=obj["wea"].toString();
                  days[i].mTemp=obj["tem"].toString();
                  days[i].mTempLow=obj["tem2"].toString();
                  days[i].mTempHigh=obj["tem1"].toString();
                  days[i].mFx=obj["win"].toArray()[0].toString();
                  days[i].mFl=obj["win_speed"].toString();
                  days[i].mHu=obj["humidity"].toString();
                  days[i].mTips=obj["air_tips"].toString();
                  days[i].mAirq=obj["air_level"].toString();
             }
        }
    }
    updateUI();
}

void Widget::updateUI()
{
    //解析日期
    ui->labelCurrentDate->setText(days[0].mDate+"  "+days[0].mWeek);
    //解析城市名称
    ui->labelCity->setText(days[0].mCity+"市");
    //解析当前温度
    ui->labelTmp->setText(days[0].mTemp+"℃");
    ui->labelTempRange->setText(days[0].mTempLow+"~"
            +days[0].mTempHigh);
    //解析天气类型
    ui->labelweatherType->setText(days[0].mWeathType);
    ui->labelWeatherIcon->setPixmap(mTypeMap[days[0].mWeathType]);
    //感冒指数
    ui->labelGaomao->setText(days[0].mTips);
    //风向
    ui->labelFXType->setText(days[0].mFx);
    //风力
    ui->labelFXType_2->setText(days[0].mFl);
    //PM2.5
    ui->labelPM25Data->setText(days[0].mPm25);
    //湿度
    ui->labelShiduData->setText(days[0].mHu);
    //空气质量
    ui->labelairData->setText(days[0].mAirq);

    ui->lbweatherTypeDate0->setText(days[0].mWeathType);
    ui->lbweatherTypeDate3->setText(days[3].mWeathType);
}

更新天气UI显示

mWeekList<<ui->labelday0<<ui->labelday1
    <<ui->labelday2<<ui->labelday3
    <<ui->labelday4<<ui->labelday5;

mDateList<<ui->labelDate0<<ui->labelDate1
    <<ui->labelDate2<<ui->labelDate3
    <<ui->labelDate4<<ui->labelDate5;

mIconList<<ui->labelWheatherIcon0<<ui->labelWheatherIcon1
    <<ui->labelWheatherIcon2<<ui->labelWheatherIcon3
    <<ui->labelWheatherIcon4<<ui->labelWheatherIcon5;

mWeatherList<<ui->lbweatherTypeDate0<<ui->lbweatherTypeDate1
    <<ui->lbweatherTypeDate2<<ui->lbweatherTypeDate3
    <<ui->lbweatherTypeDate4<<ui->lbweatherTypeDate5;

mArqList<<ui->labelaiq0<<ui->labelaiq1
    <<ui->labelaiq2<<ui->labelaiq3
    <<ui->labelaiq4<<ui->labelaiq5;

mFxList<<ui->labelFX0<<ui->labelFX1
    <<ui->labelFX2<<ui->labelFX3
    <<ui->labelFX4<<ui->labelFX5;

mFlList<<ui->labelFL0<<ui->labelFL1
    <<ui->labelFL2<<ui->labelFL3
    <<ui->labelFL4<<ui->labelFL5;
for(int i=0;i<6;i++)
{
    mWeekList[i]->setText(days[i].mWeek);
    mWeekList[0]->setText("今天");
    mWeekList[1]->setText("明天");
    mWeekList[2]->setText("后天");
    QStringList dayList=days[i].mDate.split("-");
    mDateList[i]->setText(dayList.at(1)+"-"+dayList.at(2));

    int index = days[i].mWeathType.indexOf("转");
    if(index != -1){
        pixmap = mTypeMap[days[i].mWeathType.left(index)];
    }else{
        pixmap = mTypeMap[days[i].mWeathType];
    }
    pixmap = pixmap.scaled(mIconList[i]->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
    mIconList[i]->setMaximumHeight(50);
    mIconList[i]->setMaximumWidth(ui->widget02->width()/6.5);
    mIconList[i]->setPixmap(pixmap);

    mWeatherList[i]->setText(days[i].mWeathType);

    QString airQ=days[i].mAirq;
    mArqList[i]->setText(days[i].mAirq);
    if(airQ=="优")
    {
        mArqList[i]->setStyleSheet("background-color: rgb(150, 213, 32); border-radius: 7px; color: rgb(230, 230, 230)");
    }
    if(airQ=="良")
    {
        mArqList[i]->setStyleSheet("background-color: rgb(208, 107, 39); border-radius: 7px; color: rgb(230, 230, 230)");
    }
    if(airQ=="轻度")
    {
        mArqList[i]->setStyleSheet("background-color: rgb(255, 199, 199); border-radius: 7px; color: rgb(230, 230, 230)");
    }
    if(airQ=="中度")
    {
        mArqList[i]->setStyleSheet("background-color: rgb(255, 17, 17); border-radius: 7px; color: rgb(230, 230, 230)");
    }
    if(airQ=="重度")
    {
        mArqList[i]->setStyleSheet("background-color: rgb(153, 0, 0); border-radius: 7px; color: rgb(230, 230, 230)");
    }

    mFxList[i]->setText(days[i].mFx);

    index=days[i].mFl.indexOf("转");
    if(index!=-1)
    {
        mFlList[i]->setText(days[i].mFl.left(index));
    }
    else
    {
        mFlList[i]->setText(days[i].mFl);
    }
}

更新高低温曲线

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->widget0404&&event->type()==QEvent::Paint)
    {
        drawTempLineHigh();
        return true;
    }
    if(watched==ui->widget0405&&event->type()==QEvent::Paint)
    {
        drawTempLineLow();
        return true;
    }

    return  QWidget::eventFilter(watched,event);
}
void Widget::drawTempLineHigh()
{
    QPainter painter(ui->widget0404);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(Qt::yellow);
    painter.setPen(Qt::yellow);

    int ave;
    int sum = 0;
    int offSet = 0;
    int middle = ui->widget0404->height()*0.7;
    for(int i = 0; i < 6; i++){
        sum += days[i].mTempHigh.toInt();
    }
    ave = sum / 6;

    //定义出6个点
    QPoint points[6];
    for(int i = 0; i < 6; i++){
        points[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);
        offSet = (days[i].mTempHigh.toInt() - ave)*2;
        points[i].setY(middle - offSet);
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        painter.drawText(points[i].x()-15,points[i].y()-15,days[i].mTempHigh+"°");
    }

    for(int i = 0; i < 5; i++){
         painter.drawLine(points[i],points[i+1]);
    }


}

void Widget::drawTempLineLow()
{
    QPainter painter(ui->widget0405);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(QColor(70, 192, 203));
    painter.setPen(QColor(70, 192, 203));

    int ave;
    int sum = 0;
    int offSet = 0;
    int middle = ui->widget0404->height()*0.7;
    for(int i = 0; i < 6; i++){
        sum += days[i].mTempLow.toInt();
    }
    ave = sum / 6;

    //定义出6个点
    QPoint points[6];
    for(int i = 0; i < 6; i++){
        points[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);
        offSet = (days[i].mTempLow.toInt() - ave)*3;
        points[i].setY(middle - offSet);
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        painter.drawText(points[i].x()-15,points[i].y()-15,days[i].mTempLow+"°");
    }

    for(int i = 0; i < 5; i++){
         painter.drawLine(points[i],points[i+1]);
    }

}

完整代码

codecityUitls.h

#ifndef CODECITYUITLS_H
#define CODECITYUITLS_H

#include <QMap>
#include <QString>



class codeCityUitls
{
public:
    codeCityUitls();
    QMap<QString,QString> cityMap={};

    QString  getCityCodeFromName(QString cityName);
    void initCityMap();
};

#endif // CODECITYUITLS_H

day.h

#ifndef DAY_H
#define DAY_H

#include <QString>



class Day
{
public:
    Day();

    QString mDate;
    QString mWeek;
    QString mCity;
    QString mTemp;
    QString mWeathType;
    QString mTempLow;
    QString mTempHigh;

    QString mTips;
    QString mFx;
    QString mFl;
    QString mPm25;
    QString mHu;
    QString mAirq;
};

#endif // DAY_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QLabel>
#include <QMenu>
#include <QNetworkReply>
#include <QWidget>
#include "codecityuitls.h"
#include "day.h"

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Day days[7];

    QList<QLabel*>  mDateList;
    QList<QLabel*>  mWeekList;
    QList<QLabel*>  mIconList;
    QList<QLabel*>  mWeatherList;
    QList<QLabel*>  mArqList;
    QList<QLabel*>  mFxList;
    QList<QLabel*>  mFlList;

    Widget(QWidget *parent = nullptr);
    ~Widget();

protected:
    void mousePressEvent(QMouseEvent *event)override;
    void mouseMoveEvent(QMouseEvent *event) override;
    bool eventFilter(QObject *watched, QEvent *event);

public slots:

    void readHttpRply(QNetworkReply *reply);

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    QMenu *menuQuit;
    QPoint mOffset;
    QNetworkReply *reply;
    QString strUrl;
    QNetworkAccessManager *manager;
    codeCityUitls codeCityUitls;
    QMap<QString,QString>   mTypeMap;
    void parseWeatherJsonData(QByteArray rawData);
    void parseWeatherJsonDataNew(QByteArray rawData);
    void updateUI();
    void drawTempLineHigh();
    void drawTempLineLow();
};
#endif // WIDGET_H

codecityuitls.cpp

#include "codecityuitls.h"

#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>
codeCityUitls::codeCityUitls()
{

}

QString codeCityUitls::getCityCodeFromName(QString cityName)
{

      if(cityMap.isEmpty())
      {
          initCityMap();
      }
      QMap<QString,QString>::iterator it = cityMap.find(cityName);
      if(it==cityMap.end())
      {
          qDebug()<<cityName;
          it = cityMap.find(cityName+"市");
          if(it==cityMap.end())
          {
              it = cityMap.find(cityName+"县");
          }
          if(it==cityMap.end())
          {
              it = cityMap.find(cityName+"区");
          }
          if(it==cityMap.end())
          {
              return  " ";
          }
      }

      return it.value();
}

void codeCityUitls::initCityMap()
{
    QFile file(":/citycode.json");
    file.open(QIODevice::ReadOnly);
    QByteArray rawData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(jsonDoc.isArray()){
        QJsonArray citys = jsonDoc.array();
        for( QJsonValue value : citys){
            if( value.isObject()){
                QString cityName = value["city_name"].toString();
                QString cityCode = value["city_code"].toString();
                cityMap.insert(cityName,cityCode);
            }
        }

    }
}

main.cpp

#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"

#include <QMouseEvent>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QPainter>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
        , ui(new Ui::Widget)
    {
        ui->setupUi(this);
        this->setFont(QFont("Arial",15));
        setFixedSize(507,936);
        setWindowFlag(Qt::FramelessWindowHint);
        //新建一个菜单组件
        menuQuit = new QMenu(this);
        //设置菜单项文字颜色
        menuQuit->setStyleSheet("QMenu::item {color:white}");
        //为菜单组件添加一个动作
        QAction *closeAct = new QAction(QIcon(":/res/close.png"), tr("退出"), this);
        menuQuit->addAction(closeAct);
        //用户选择菜单项并点击后回调函数,退出程序
        connect(menuQuit,&QMenu::triggered,this,[=]{
            this->close();
        });
        //由QNetworkAccessManager发起get请求
        manager = new QNetworkAccessManager(this);
        //strUrl = "http://v1.yiketianqi.com/api?unescape=1&version=v61&appid=26371314&appsecret=qOhoD413";
        strUrl ="http://v1.yiketianqi.com/api?unescape=1&version=v9&appid=56199542&appsecret=b16GDpyO";
        QUrl urlTianQi(strUrl);
        //指定请求的url地址
        QNetworkRequest res(urlTianQi);
        reply =  manager->get(res);
        //QNetworkRequest网络请求后进行数据读取
        connect(manager,&QNetworkAccessManager::finished,this,&Widget::readHttpRply);

        mWeekList<<ui->labelday0<<ui->labelday1
            <<ui->labelday2<<ui->labelday3
            <<ui->labelday4<<ui->labelday5;

        mDateList<<ui->labelDate0<<ui->labelDate1
            <<ui->labelDate2<<ui->labelDate3
            <<ui->labelDate4<<ui->labelDate5;

        mIconList<<ui->labelWheatherIcon0<<ui->labelWheatherIcon1
            <<ui->labelWheatherIcon2<<ui->labelWheatherIcon3
            <<ui->labelWheatherIcon4<<ui->labelWheatherIcon5;

        mWeatherList<<ui->lbweatherTypeDate0<<ui->lbweatherTypeDate1
            <<ui->lbweatherTypeDate2<<ui->lbweatherTypeDate3
            <<ui->lbweatherTypeDate4<<ui->lbweatherTypeDate5;

        mArqList<<ui->labelaiq0<<ui->labelaiq1
            <<ui->labelaiq2<<ui->labelaiq3
            <<ui->labelaiq4<<ui->labelaiq5;

        mFxList<<ui->labelFX0<<ui->labelFX1
            <<ui->labelFX2<<ui->labelFX3
            <<ui->labelFX4<<ui->labelFX5;

        mFlList<<ui->labelFL0<<ui->labelFL1
            <<ui->labelFL2<<ui->labelFL3
            <<ui->labelFL4<<ui->labelFL5;



        mTypeMap.insert("暴雪",":/res/type/BaoXue.png");
        mTypeMap.insert("暴雨",":/res/type/BaoYu. png");
        mTypeMap.insert("暴雨到大暴雨",":/res/type/BaoYuDaoDaBaoYu.png");
        mTypeMap.insert("大暴雨",":/res/type/DaBaoYu.png");
        mTypeMap.insert("大暴雨到特大暴雨",":/res/type/DaBaoYuDaoTeDaBaoYu.png");
        mTypeMap.insert("大到暴雪",":/res/type/DaDaoBaoXue.png");
        mTypeMap.insert("大雪",":/res/type/DaXue.png");
        mTypeMap.insert("大雨",":/res/type/DaYu.png");
        mTypeMap.insert("冻雨",":/res/type/DongYu.png");
        mTypeMap.insert("多云",":/res/type/DuoYun.png");
        mTypeMap.insert("浮沉",":/res/type/FuChen.png");
        mTypeMap.insert("雷阵雨",":/res/type/LeiZhenYu.png");
        mTypeMap.insert("雷阵雨伴有冰雹",":/res/type/LeiZhenYuBanYouBingBao.png");
        mTypeMap.insert("霾",":/res/type/Mai.png");
        mTypeMap.insert("强沙尘暴",":/res/type/QiangShaChenBao.png");
        mTypeMap.insert("晴",":/res/type/Qing.png");
        mTypeMap.insert("沙尘暴",":/res/type/ShaChenBao.png");
        mTypeMap.insert("特大暴雨",":/res/type/TeDaBaoYu.png");
        mTypeMap.insert("undefined",":/res/type/undefined.png");
        mTypeMap.insert("雾",":/res/type/Wu.png");
        mTypeMap.insert("小到中雪",":/res/type/XiaoDaoZhongXue.png");
        mTypeMap.insert("小到中雨",":/res/type/XiaoDaoZhongYu.png");
        mTypeMap.insert("小雪",":/res/type/XiaoXue.png");
        mTypeMap.insert("小雨",":/res/type/XiaoYu.png");
        mTypeMap.insert("雪",":/res/type/Xue.png");
        mTypeMap.insert("扬沙",":/res/type/YangSha.png");
        mTypeMap.insert("阴",":/res/type/Yin.png");
        mTypeMap.insert("雨",":/res/type/Yu.png");
        mTypeMap.insert("雨夹雪",":/res/type/YuJiaXue.png");
        mTypeMap.insert("阵雪",":/res/type/ZhenXue.png");
        mTypeMap.insert("阵雨",":/res/type/ZhenYu.png");
        mTypeMap.insert("中到大雪",":/res/type/ZhongDaoDaXue.png");
        mTypeMap.insert("中到大雨",":/res/type/ZhongDaoDaYu.png");
        mTypeMap.insert("中雪",":/res/type/ZhongXue.png");
        mTypeMap.insert("中雨",":/res/type/ZhongYu.png");

        ui->widget0404->installEventFilter(this);
        ui->widget0405->installEventFilter(this);
    }


Widget::~Widget()
{
    delete ui;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton){
        menuQuit->exec(QCursor::pos());
    }
    //鼠标当前位置 event->globalPos();,
    //窗口当前位置 this->pos()窗口新位置event->globalPos() - mOffset
    if(event->button() == Qt::LeftButton){
        mOffset = event->globalPos()-this->pos();
    }
}
//鼠标左键按下后的移动,导致这个事件被调用,设置窗口的新位置
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - mOffset);
}

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->widget0404&&event->type()==QEvent::Paint)
    {
        drawTempLineHigh();
        return true;
    }
    if(watched==ui->widget0405&&event->type()==QEvent::Paint)
    {
        drawTempLineLow();
        return true;
    }

    return  QWidget::eventFilter(watched,event);
}

void Widget::parseWeatherJsonData(QByteArray rawData)
{
    QJsonDocument jsonObj = QJsonDocument::fromJson(rawData);
    if(!jsonObj.isNull() && jsonObj.isObject()){
        QJsonObject objRoot = jsonObj.object();
        //解析日期
        QString date = objRoot["date"].toString();
        QString week = objRoot["week"].toString();
        ui->labelCurrentDate->setText(date+"  "+week);
        //解析城市名称
        QString cityName = objRoot["city"].toString();
        ui->labelCity->setText(cityName+"市");
        //解析当前温度
        QString currentTemp = objRoot["tem"].toString();
        ui->labelTmp->setText(currentTemp+"℃");
        ui->labelTempRange->setText(objRoot["tem2"].toString()+"~"
                                    +objRoot["tem1"].toString());
        //解析天气类型
        ui->labelweatherType->setText(objRoot["wea"].toString());
        ui->labelWeatherIcon->setPixmap(mTypeMap[objRoot["wea"].toString()]);
        //感冒指数
        ui->labelGaomao->setText(objRoot["air_tips"].toString());
        //风向
        ui->labelFXType->setText(objRoot["win"].toString());
        //风力
        ui->labelFXType_2->setText(objRoot["win_speed"].toString());
        //PM2.5
        ui->labelPM25Data->setText(objRoot["air_pm25"].toString());
        //湿度
        ui->labelShiduData->setText(objRoot["humidity"].toString());
        //空气质量
        ui->labelairData->setText(objRoot["air_level"].toString());

    }
}

void Widget::parseWeatherJsonDataNew(QByteArray rawData)
{
    QJsonDocument jsonDoc=QJsonDocument::fromJson(rawData);
    if(!jsonDoc.isNull()&&jsonDoc.isObject())
    {
        QJsonObject jsonRoot=jsonDoc.object();
        days[0].mCity=jsonRoot["city"].toString();
        days[0].mPm25=jsonRoot["aqi"].toObject()["pm25"].toString();
        if(jsonRoot.contains("data")&&jsonRoot["data"].isArray())
        {
            QJsonArray weathArray=jsonRoot["data"].toArray();
            for(int i=0;i<weathArray.size();i++)
            {
                QJsonObject obj=weathArray[i].toObject();
                //qDebug()<<obj["date"].toString()<<obj["wea"].toString();
                days[i].mDate=obj["date"].toString();
                days[i].mWeek=obj["week"].toString();
                days[i].mWeathType=obj["wea"].toString();
                days[i].mTemp=obj["tem"].toString();
                days[i].mTempLow=obj["tem2"].toString();
                days[i].mTempHigh=obj["tem1"].toString();
                days[i].mFx=obj["win"].toArray()[0].toString();
                days[i].mFl=obj["win_speed"].toString();
                days[i].mHu=obj["humidity"].toString();
                days[i].mTips=obj["air_tips"].toString();
                days[i].mAirq=obj["air_level"].toString();
            }
        }
    }
    updateUI();
}

void Widget::updateUI()
{
    QPixmap pixmap;
    //解析日期
    ui->labelCurrentDate->setText(days[0].mDate+"  "+days[0].mWeek);
    //解析城市名称
    ui->labelCity->setText(days[0].mCity+"市");
    //解析当前温度
    ui->labelTmp->setText(days[0].mTemp+"℃");
    ui->labelTempRange->setText(days[0].mTempLow+"℃"+"~"
                                +days[0].mTempHigh+"℃");
    //解析天气类型
    ui->labelweatherType->setText(days[0].mWeathType);
    ui->labelWeatherIcon->setPixmap(mTypeMap[days[0].mWeathType]);
    //感冒指数
    ui->labelGaomao->setText(days[0].mTips);
    //风向
    ui->labelFXType->setText(days[0].mFx);
    //风力
    ui->labelFXType_2->setText(days[0].mFl);
    //PM2.5
    ui->labelPM25Data->setText(days[0].mPm25);
    //湿度
    ui->labelShiduData->setText(days[0].mHu);
    //空气质量
    ui->labelairData->setText(days[0].mAirq);

    ui->lbweatherTypeDate0->setText(days[0].mWeathType);
    ui->lbweatherTypeDate3->setText(days[3].mWeathType);

    for(int i=0;i<6;i++)
    {
        mWeekList[i]->setText(days[i].mWeek);
        mWeekList[0]->setText("今天");
        mWeekList[1]->setText("明天");
        mWeekList[2]->setText("后天");
        QStringList dayList=days[i].mDate.split("-");
        mDateList[i]->setText(dayList.at(1)+"-"+dayList.at(2));

        int index = days[i].mWeathType.indexOf("转");
        if(index != -1){
            pixmap = mTypeMap[days[i].mWeathType.left(index)];
        }else{
            pixmap = mTypeMap[days[i].mWeathType];
        }
        pixmap = pixmap.scaled(mIconList[i]->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
        mIconList[i]->setMaximumHeight(50);
        mIconList[i]->setMaximumWidth(ui->widget02->width()/6.5);
        mIconList[i]->setPixmap(pixmap);

        mWeatherList[i]->setText(days[i].mWeathType);

        QString airQ=days[i].mAirq;
        mArqList[i]->setText(days[i].mAirq);
        if(airQ=="优")
        {
            mArqList[i]->setStyleSheet("background-color: rgb(150, 213, 32); border-radius: 7px; color: rgb(230, 230, 230)");
        }
        if(airQ=="良")
        {
            mArqList[i]->setStyleSheet("background-color: rgb(208, 107, 39); border-radius: 7px; color: rgb(230, 230, 230)");
        }
        if(airQ=="轻度")
        {
            mArqList[i]->setStyleSheet("background-color: rgb(255, 199, 199); border-radius: 7px; color: rgb(230, 230, 230)");
        }
        if(airQ=="中度")
        {
            mArqList[i]->setStyleSheet("background-color: rgb(255, 17, 17); border-radius: 7px; color: rgb(230, 230, 230)");
        }
        if(airQ=="重度")
        {
            mArqList[i]->setStyleSheet("background-color: rgb(153, 0, 0); border-radius: 7px; color: rgb(230, 230, 230)");
        }

        mFxList[i]->setText(days[i].mFx);

        index=days[i].mFl.indexOf("转");
        if(index!=-1)
        {
            mFlList[i]->setText(days[i].mFl.left(index));
        }
        else
        {
            mFlList[i]->setText(days[i].mFl);
        }
    }
}

void Widget::drawTempLineHigh()
{
    /*
    QPainter painter(ui->widget0404);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(Qt::yellow);
    painter.setPen(Qt::yellow);

    int ave;
    int sum=0;
    int offSet=0;
    int middle=ui->widget0404->height()/2;
    //计算平均温度
    for(int i=0;i<6;i++)
    {
        sum+=days[i].mTempHigh.toInt();
    }
    ave=sum/6;

    //定义出6个点
    QPoint points[6];

    for(int i=0;i<6;i++)
    {
        points[i].setX(mArqList[i]->x()+mArqList[i]->width()/2);
        offSet=(days[i].mTempHigh.toInt()-ave)*2;
        points[i].setY(middle-offSet);
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        //painter.drawText(points[i].x()-15,points[i].y()-15,days[i].mTempHigh+"°");
         painter.drawText(points[i].x(),points[i].y()-1,days[i].mTempHigh);
    }


    for(int i=0;i<5;i++)
    {
        painter.drawLine(points[i],points[i+1]);
    }
    */
    QPainter painter(ui->widget0404);
    painter.setRenderHint(QPainter::Antialiasing,true);
    painter.setBrush(Qt::yellow);
    painter.setPen(Qt::yellow);

    int ave;
    int sum = 0;
    int offSet = 0;
    int middle = ui->widget0404->height()*0.7;
    for(int i = 0; i < 6; i++){
        sum += days[i].mTempHigh.toInt();
    }
    ave = sum / 6;

    //定义出6个点
    QPoint points[6];
    for(int i = 0; i < 6; i++){
        points[i].setX(mArqList[i]->x() + mArqList[i]->width()/2);
        offSet = (days[i].mTempHigh.toInt() - ave)*2;
        points[i].setY(middle - offSet);
        //画出6个点
        painter.drawEllipse(QPoint(points[i]),3,3);
        //画出当天温度
        painter.drawText(points[i].x()-15,points[i].y()-15,days[i].mTempHigh+"°");
    }

    for(int i = 0; i < 5; i++){
        painter.drawLine(points[i],points[i+1]);
    }
}

void Widget::drawTempLineLow()
{

}

void Widget::readHttpRply(QNetworkReply *reply)
{
    int resCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    qDebug() << resCode;
    if( reply->error() == QNetworkReply::NoError && resCode == 200){
        //大多数服务器返回的字符编码格式是utf-8
        QByteArray data = reply->readAll();
        parseWeatherJsonDataNew(data);
        //parseWeatherJsonData(data);
        //qDebug() << QString::fromUtf8(data);
    }else{
        // QMessageBox::warning(this,"错误","网络请求失败",QMessageBox::Ok);
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("网络请求失败");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}


void Widget::on_pushButton_clicked()
{
    QString cityNameFromUser = ui->lineEditCity->text();
    QString cityCode = codeCityUitls.getCityCodeFromName(cityNameFromUser);
    if(cityCode != NULL){
        strUrl += "&cityid=" + cityCode;
        qDebug() << strUrl;
        manager->get(QNetworkRequest(QUrl(strUrl)));
    }else{
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("请输入正确的城市名");
        mes.setStyleSheet("QPushButton {color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值