我无法实现带有部分的 ListView 。我已经成功地重复了 Qt 文档中的示例,但是使用了 ListModel 可以正常工作,但不是 var。
如何使用示例:
ListView {
width: 100
height: 100
id: listview
model: ListModel {
id: animalsModel
ListElement { name: "Ant"; size: "Tiny" }
ListElement { name: "Flea"; size: "Tiny" }
ListElement { name: "Parrot"; size: "Small" }
ListElement { name: "Guinea pig"; size: "Small" }
ListElement { name: "Rat"; size: "Small" }
ListElement { name: "Butterfly"; size: "Small" }
ListElement { name: "Dog"; size: "Medium" }
ListElement { name: "Cat"; size: "Medium" }
ListElement { name: "Pony"; size: "Medium" }
ListElement { name: "Koala"; size: "Medium" }
ListElement { name: "Horse"; size: "Large" }
ListElement { name: "Tiger"; size: "Large" }
ListElement { name: "Giraffe"; size: "Large" }
ListElement { name: "Elephant"; size: "Huge" }
ListElement { name: "Whale"; size: "Huge" }
}
delegate: Text { text: name; font.pixelSize: 18 }
section.property: "size"
section.criteria: ViewSection.FullString
section.delegate: Component {
id: sectionHeading
Rectangle {
width: container.width
height: childrenRect.height
color: "lightsteelblue"
Text {
text: section
font.bold: true
font.pixelSize: 20
}
}
}
}
但是当我尝试使用代码中的某些模型时(在我的例子中它是来自 PyQt5 的 QVariant)它根本不起作用:
ListView {
width: 100
height: 100
id: listview
property var m: [
{
name: "Animal",
size: "Big"
},
{
name: "Dog",
size: "Small"
},
{
name: "Cat",
size: "Small"
}
]
model: m
delegate: Text { text: modelData.name; font.pixelSize: 18 }
section.property: "modelData.size"
section.criteria: ViewSection.FullString
section.delegate: Component {
id: sectionHeading
Rectangle {
width: container.width
height: childrenRect.height
color: "lightsteelblue"
Text {
text: section
font.bold: true
font.pixelSize: 20
}
}
}
}
我在这里选择 var 的原因是因为没有任何其他方法可以从 Python 接收模型,所以任何 list 或 map python 需要包装成QVariant。
请您参考如下方法:
来自 Qt 文档:
模型 : 模型
此属性保存为列表提供数据的模型。 该模型提供了用于在 View 中创建项目的数据集。模型可以使用 ListModel、XmlListModel 或 VisualItemModel 直接在 QML 中创建,或者由 C++ 模型类提供。如果使用 C++ 模型类,它必须是 QAbstractItemModel 的子类或简单列表。
所以你不能提供一个数组作为模型,它应该是上面的对象之一。 您可以创建这样的模型并从 Python 代码访问它以添加/删除项目。
ListView {
width: 100
height: 100
id: listview
delegate: Text { text: name; font.pixelSize: 18 }
model: ListModel { id: listModel }
section.property: "size"
section.criteria: ViewSection.FullString
section.delegate: Component {
id: sectionHeading
Rectangle {
width: container.width
height: childrenRect.height
color: "lightsteelblue"
Text {
text: section
font.bold: true
font.pixelSize: 20
}
}
}
function callFromPython {
listModel.append({name: "Animal",size: "Big"});
listModel.append({name: "Dog",size: "Small"});
listModel.append({name: "Cat",size: "Small"});
}
}
