Qt實現簡易天氣預報(解析的是json資料)
阿新 • • 發佈:2019-02-14
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QScriptEngine> #include <QtScript> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QJsonDocument> #include <QScriptValue> #include <QVariantMap> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; QNetworkAccessManager *manager; void analyseJson(); QByteArray weather; private slots: void GetWebJsonData(QNetworkReply *); }; #endif // MAINWINDOW_H
</pre><pre name="code" class="cpp">
<pre name="code" class="cpp">#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); manager = new QNetworkAccessManager(this);//http://www.weather.com.cn/data/cityinfo/101190901.html connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(GetWebJsonData(QNetworkReply *))); manager->get(QNetworkRequest(QUrl("http://www.weather.com.cn/data/sk/101190401.html"))); } void MainWindow::GetWebJsonData(QNetworkReply *reply) { weather=reply->readAll(); //qDebug()<<weather; analyseJson(); } void MainWindow::analyseJson() { QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson(weather,&err); QJsonObject obj= doc.object().value("weatherinfo").toObject();//object()獲得json最外面一層 ui->cityEdit->setText(doc.object().value("weatherinfo").toObject().take("city").toString()); ui->tempEdit->setText(doc.object().value("weatherinfo").toObject().take("temp").toString()+"℃"); ui->windEdit->setText(doc.object().value("weatherinfo").toObject().take("WD").toString()+doc.object().value("weatherinfo").toObject().take("WS").toString()); QVariantMap QVM= obj.toVariantMap(); QVariantMap::iterator it = QVM.begin(); while(it!=QVM.end()) { ui->textEdit->append(it.key()+" "+it.value().toString()); it++; qDebug()<<it.key(); } } MainWindow::~MainWindow() { delete ui; }
</pre><pre name="code" class="cpp">