2014-01-13 2 views
1


방금 ​​QML을 작업하기 시작했습니다. C를 정말 좋아하기 때문에 유망 해 보입니다. 실험하면서 Ajax를 사용하여 PHP 서비스에서 ListModel을 업데이트해야하는 시점에 왔습니다 의뢰. 나는 this 링크를 언급했지만, 제대로 작동하지 않는 것 같습니다. 내 코드는 다음과 같습니다.QML ListModel을 업데이트 할 수 없습니다.

try.js :

function load() { 
    listModel.clear(); 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", "http://<url>/service_newsletter.php?method=news", true); 
    xhr.onreadystatechange = function() { 
     if(xhr.readyState == xhr.DONE){ 
      if(xhr.status == 200) { 
       var jsonData = JSON.parse(xhr.responseText); 
       for(var index in jsonData.data.posts) { 
        listModel.append({ 
         "text": jsonData.data.posts[index].text, 
         "description": jsonData.data.posts[index].description}); 
        alert(jsonData.data.posts[index].text); 
       } 
      } 
     } 
    } 
    xhr.send(); 
} 

QML 코드 :

import QtQuick 1.1 
import "try.js" as JS 

Item { 
    id:root 
    width: 360 
    height: 640 

    Component.onCompleted: JS.load() 

    ListModel { 
     id:listModel 
    } 

    ListView { 
     id:view 
     anchors.fill:parent 
     model : listModel 
     delegate: Rectangle { 
      width:parent.width 
      height:80 
      Text { 
       anchors.centerIn:parent 
       text: text 
      } 
     } 
    } 
} 

참고 : 안드로이드에 Qt는 응용 프로그램을 배포하는 Necessitas를 사용!

참고 2 : 내 서버의 JSON 데이터 형식은 위 링크 예와 비슷합니다.

답변

0

나는 거의 성공했다. 유일한 문제는 모델에 이미 1 요소가있는 경우입니다. append에 2 개의 요소가 있지만 1 단계 만 다시 그려집니다. 아마 나는 문서에서 뭔가를 그리워합니다.

닌자, 나는 어쩌면 text: text이 작동하기 때문에 위임 속성의 이름을 지정하지만 모델의 역할 이름에 대한 참조를 기대하는 경우 text: "a"+text에 2 text가 1 text 참조 될로서 역할을 동일한 방식으로 명명 피하기 위해 당신을 추천 할 수 있습니다.

그래서, 더 나은 코드는

main.qml

import QtQuick 2.1 
import "try.js" as JS 

Rectangle { 
    id:root 
    width: 640 
    height: 480 

    ListModel { 
     id:listModel 
     ListElement { title: "a" } 
    } 

    ListView { 
     id:view 
     width: 600 
     height: 500 
     model : listModel 
     orientation: ListView.Vertical 

     delegate: Rectangle { 
      width: 100 
      height: 20 
      color: "yellow" 
      Text { 
       text: title 
       color: "black" 
      } 
      Component.onCompleted: console.log("rectangle created ", title, index); 
     } 
    } 
    Component.onCompleted: JS.load() 
} 

try.js입니다

function load() { 
    listModel.clear(); 
    var xhr = new XMLHttpRequest(); 
    xhr.open("GET", "http://echo.jsontest.com/key/value/otherkey/othervalue", true); 
    xhr.onreadystatechange = function() { 
     if(xhr.readyState == xhr.DONE) { 
      if(xhr.status == 200) { 
       var jsonData = JSON.parse(xhr.responseText); 
       console.log(listModel); 
       listModel.append({ 
         "title": "text1", 
         "description": "desc1" 
       }); 
       console.log("ANswer gotten", jsonData); 
      } 
     } 
    } 
    xhr.send(); 
}