title: qt-天氣通軟件
id: 293
categories:
- qt
date: 2015-11-27 12:22:11
tags: qt,json,百度api
綜述
獲取json
這次的數據是利用百度的api獲取的,百度為開發者提供了許多api,
其中地理的api,大數據的api很好,我利用的百度為車聯網提供的天氣api,
在注冊了信息后,就可以免費使用了。
download python
我使用python下載從網上獲取的json數據,代碼如下
#!/bin/env python
import types
import urllib2
import json
import os
import sys
#-*-coding:utf-8 -*-
url0 = "http://api.map.baidu.com/telematics/v3/weather?location="
url1 = "&output=json&ak=ozO9AVLiHTGEltbNzUxVKPCk"
url2 = sys.argv[1]
def registerUrl():
try:
url =url0 + url2 + url1
data = urllib2.urlopen(url).read()
print data
return data
print (url)
#return url
except Exception,e:
print e
f = open('./weathers','w')
f.write(registerUrl())
f.close
開始編程
我的布局
我的思考是做一個類似天氣通的軟件,用戶輸入地點信息后可以將那個地點的天氣狀況
反饋出來,
如上所示
qt解析json
qt有專門處理json數據的class,QjsonDocument,
QString json("{"
"\"encoding\" : \"UTF-8\","
"\"plug-ins\" : ["
"\"python\","
"\"c++\","
"\"ruby\""
"],"
"\"indent\" : { \"length\" : 3, \"use_space\" : true }"
"}");
QJsonParseError error;
QJsonDocument jsonDocument = QJsonDocument::fromJson(json.toUtf8(), &error);
if (error.error == QJsonParseError::NoError) {
if (jsonDocument.isObject()) {
QVariantMap result = jsonDocument.toVariant().toMap();
qDebug() << "encoding:" << result["encoding"].toString();
qDebug() << "plugins:";
foreach (QVariant plugin, result["plug-ins"].toList()) {
qDebug() << "\t-" << plugin.toString();
}
QVariantMap nestedMap = result["indent"].toMap();
qDebug() << "length:" << nestedMap["length"].toInt();
qDebug() << "use_space:" << nestedMap["use_space"].toBool();
}
} else {
qFatal(error.errorString().toUtf8().constData());
exit(1);
}
對照json的數據內容,json鍵值就是一個map,json數組用qlist處理,json對象也是一個map,
但是里面的值需要細分處理,分為list,map。
解析花費了我許多的時間,在利用一個網站json解析,我處理完了json解析操作,
下一步。
多看幫助文檔
我設計的是分三欄,上面是數據的輸入,中間是天氣的顯示,下面是顯示一些tips,關愛大家。
中間是一個QStackWidget,執行分頁的效果,我是利用qt的help做出來的,所以幫助文檔多多看,挺好的。
問題
我使用Qprocess來執行python代碼,
process = new QProcess;
QString processString = "python untitled-1.py "+ linedit->text();
process->start(processString);
我希望多執行幾個腳本,結果報錯了,對于如何解決這個問題,我試圖使用再開一個線程的方法,但是我需要從主線程傳值給
新的線程,我試過new一個對象,或者使用靜態變量傳值,但是都報錯了,
我想這種方法傳值或許有問題,但是新開一個線程是很簡單的。
class WorkerThread : public QThread
{
Q_OBJECT
void run() Q_DECL_OVERRIDE {
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}
signals:
void resultReady(const QString &s);
};
void MyObject::startWorkInAThread()
{
WorkerThread *workerThread = new WorkerThread(this);
connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
workerThread->start();
}
添加一點趣味
我使用QTimer來定時切換,
timer = new QTimer;
connect(timer, SIGNAL(timeout()), this, SLOT(showData()));
我設置了定時器,每隔一定的時間就可以換下一天的天氣信息,
結語
整體我花了3,4天的時間來寫,其中出了很多的問題,幸好我堅持了下來。
代碼鏈接:https://github.com/youngjeff/qt/tree/master/weather