目前我和一些学生正在使用 QtQuick 编写一个小应用程序。
我们有以下 TableView
:
TableView {
model: ListModel {
id: orderListModel
Component.onCompleted: {
var tOrderList = orderController.getOrderList();
for(var i = 0; i < tTicketList.length; ++i){
orderListModel.append(tOrderList[i]);
}
}
}
TableViewColumn {
role: "orderId"
title: "Auftragsnummer"
width: 100
}
TableViewColumn {
role: "customer.name"
title: "Kunde"
width: 100
}
}
getOrderList
返回 QList<Object*>
与所有订单。
Order
类有一个属性 customer
Q_PROPERTY(Customer* customer READ getCustomer NOTIFY customerChanged)
它又拥有一个名为 name
的属性.
我们想在 TableView
中显示后一个属性但不幸的是只有orderId
Order
的属性(property)确实有效。
第二个角色应该有什么值(value)?我们如何访问嵌套对象的数据?
最佳答案
根据documentation你可以使用 QList<QObject*>
直接作为 View 的模型,无需像您那样手动复制数据。特别是:
The QObject* is available as the modelData property. As a convenience, the properties of the object are also made available directly in the delegate's context.
考虑the example在文档中链接我们有 QObject
的属性可以通过以下方式用作角色:
ListView {
width: 100; height: 100
model: myModel // injected QList<QObject*> context property
delegate: Rectangle {
height: 25
width: 100
color: model.modelData.color // without "modelData" it would not work
Text { text: name }
}
}
这同样适用于嵌套属性。如果我们的 QObject
-derived 对象有一个 QObject
属性(property),就像你的情况一样,我们可以通过 modelData
检索它然后访问它的属性。因此,例如 customer
属性(property),我们会在委托(delegate)中有这样的东西:
Text { text: model.modelData.customer.name }
ListView
也是如此et similia 而我不确定它是否可以直接用 TableView
完成.一种可能的解决方法是结合使用 QObject
-派生角色 styleData.value
.您可以在 role
中定义角色的用法属性并访问 styleData.value
中的内部属性.针对您的案例的解决方案如下所示(假设 myModel
是上例中的上下文属性):
TableView {
width: 100; height: 100
model: myModel
TableViewColumn {
role: "customer"
title: "Kunde"
width: 100
delegate: Text {
text: styleData.value.name // accessing the property
}
}
itemDelegate: Item { } // should be set to empty to avoid warnings
}
这种方法的缺点是您应该为每一列实现一个委托(delegate)。
关于qt - Qml TableView - TableViewColumn - ListModel - 访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34278244/