标签:
很多QML应需要访问web services。我们可以通过Javascript的方法来解析得到我们所需要的JSON数据,并把它们展示出来。在今天的例子中,我们将展示如何实现它?
我们可以创建一个最基本的“QML App with Simple UI (qmlproject)”,并取名我们的应用为“baidutranslator”。我们将使用的API为:
http://openapi.baidu.com/public/2.0/bmt/translate?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto&to=auto&q=%E4%BD%A0%E5%A5%BD
{"from":"zh","to":"en","trans_result":[{"src":"\u4f60\u597d","dst":"Hello"}]}为了能够解析我们得到的JSON格式,我们创建了一个“jsonparser.js”文件:
var URL = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=2hG67S2yRm5chkr62j2IEmYL&from=auto&to=auto&q=";
function startParse(keyword, callback) {
    var doc = new XMLHttpRequest();
    doc.onreadystatechange = function() {
        if (doc.readyState == XMLHttpRequest.HEADERS_RECEIVED) {
        } else if (doc.readyState === XMLHttpRequest.DONE) {
            if(doc.status != 200) {
                console.log("!!!Network connection failed!")
            }
            else {
                console.log("got some results!");
                if(doc.responseText == null) {
                }
                else {
                    console.log("result: ", doc.responseText)
                    var json = JSON.parse('' + doc.responseText+ '');
                    json["status"] = "OK";
                    callback.update(json);
                }
            }
        }
    }
    doc.open("GET", URL + keyword);
    doc.send();
}
“Main.qml”的设计如下:
import QtQuick 2.0
import Ubuntu.Components 1.1
import "jsonparser.js" as API
/*!
    \brief MainView with a Label and Button elements.
*/
MainView {
    id: root
    // objectName for functional testing purposes (autopilot-qt5)
    objectName: "mainView"
    // Note! applicationName needs to match the "name" field of the click manifest
    applicationName: "baidutranslator.liu-xiao-guo"
    /*
     This property enables the application to change orientation
     when the device is rotated. The default is false.
    */
    //automaticOrientation: true
    // Removes the old toolbar and enables new features of the new header.
    useDeprecatedToolbar: false
    width: units.gu(60)
    height: units.gu(85)
    function update(json) {
        console.log("json: " + JSON.stringify(json));
        mymodel.clear();
        if ( json.trans_result !== undefined && json.trans_result.length !== undefined ) {
            for ( var idx = 0; idx < json.trans_result.length; idx++ ) {
                if ( json.trans_result[ idx ].dst ) {
                    console.log( 'meaning: ' + json.trans_result[ idx ].dst);
                    mymodel.append( {"meaning": json.trans_result[ idx ].dst });
                }
            }
        } else {
            mymodel.clear();
        }
    }
    Page {
        title: i18n.tr("Baidu translator")
        ListModel {
            id: mymodel
        }
        Column {
            spacing: units.gu(1)
            anchors {
                margins: units.gu(2)
                fill: parent
            }
            TextField {
                id: input
                placeholderText: "Please input a word"
                width: parent.width
                text: "你好"
                onTextChanged: {
                    mymodel.clear();
                    var json = API.startParse(input.text, root);
                }
            }
            Button {
                id: doit
                width: parent.width
                text: i18n.tr("Translate")
                onClicked: {
                    var json = API.startParse(input.text, root);
                }
            }
            ListView {
                id: listview
                width: parent.width
                height: parent.height - input.height - doit.height
                model: mymodel
                delegate: Text {
                    text: modelData
                }
            }
        }
    }
}
  
所有项目的源码是在:git clone https://gitcafe.com/ubuntu/baidutranslator.git
标签:
原文地址:http://blog.csdn.net/ubuntutouch/article/details/45392689