2017-08-17 39 views
-1
ListView { 
    id: listView 
    model: someModel {} 
    delegate: Loader { 
     id: delegateLoader 
     source: { 
      var where; 
      if(model.type === 1) { 
       where = "RadioQuestion.qml"; 
      } 
      else 
       where = "TextQuestion.qml"; 
      if(delegateLoader.status == Loader.Ready) { 
       delegateLoader.item.question= model.question; 
      } 

      return Qt.resolvedUrl(where); 
     } 
} 

我用ListView向用戶展示了一些問題。但是我無法訪問Loader加載的委託的成員。訪問由加載程序加載的ListView委託的成員

RadioQuestion.qml有單選按鈕和文本只是文本字段。我只想在按下提交按鈕後得到所有答案,但我無法弄清楚我如何在代表中進行遍歷。

也許我的做法是錯誤的構建這種結構。因此我願意提供更好的解決方案。

回答

0
Button { 
    text: "Submit answers" 
    onClicked: { 
      for(var child in listView.contentItem.children) { 
       var c = listView.contentItem.children[child].item; 
       if(typeof c !== "undefined") 
        console.log(c.answer) 
      } 
    } 
} 

你可以得到這樣的裝載機委託的性質。我們使用「undefined」檢查,因爲contentItem的子對象中的一個對象未​​定義。這是列表中的第二個對象,我不知道爲什麼。

1

question已經通過模型暴露出來,所以您的代表應直接綁定到它,所以假設question是模型的屬性:

// from inside the delegate 
question: delegateRootId.ListView.view.model.question 

或假設的問題是一個列表元素的作用:

// from inside the delegate 
question: model.question 

而且如果你仔細不夠命名委託question裏面的屬性從而遮蔽了表率作用,你可以簡單地:

// from inside the delegate 
questionSource: question 

更何況,如果你的模型「方案」之稱,它是給定的,你將有一個question作用,這種作用將顯示在委託,你甚至不需要任何額外屬性委託,首先,你可以在實際項目直接綁定到的問題,例如:

// from inside the delegate 
Text { text: question } 

而這一切,真正需要的。

或者,您可以使用BindingConnections元素或簡單信號處理程序來延遲操作,直到加載程序實際完成加載。例如:

delegate: Loader { 
     source: Qt.resolvedUrl(model.type === 1 ? "RadioQuestion.qml" : "TextQuestion.qml") 
     onStatusChanged: if (status === Loader.Ready) if (item) item.question= model.question 
}