2017-08-17 32 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 
}