访问由Loader加载的ListView委托的成员

时间:2017-08-17 17:25:49

标签: qt listview qml loader

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加载的委托成员。

RadioQuestion.qml具有单选按钮,文本只是文本字段。我只想在按下提交按钮后得到所有答案,但我无法弄清楚如何在代表之间进行遍历。

也许我的方法是建立这种结构的错误。因此,我愿意接受更好的解决方案。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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的子项中的一个对象未​​定义。这是列表中的第二个对象,我不知道为什么。

相关问题