【发布时间】:2015-11-06 06:54:25
【问题描述】:
我想知道是否可以为 QML ListView 使用(多个)不同的代表。
根据ListView 模型中的单个对象,我想用不同的委托来可视化对象。
这段代码解释了我想要实现的目标:
main.qml
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
ListModel {
id: contactsModel
ListElement {
name: "Bill Smith"
position: "Engineer"
}
ListElement {
name: "John Brown"
position: "Engineer"
}
ListElement {
name: "Sam Wise"
position: "Manager"
}
}
ListView {
id: contactsView
anchors.left: parent.left
anchors.top: parent.top
width: parent.width
height: parent.height
orientation: Qt.Vertical
spacing: 10
model: contactsModel
delegate: {
if (position == "Engineer") return Employee; //<--- depending on condition, load Contact{}
else if (position == "Manager") return Manager; //<--- depending on condition, load Person{}
}
}
}
Employee.qml(我想用作委托的一个可能的组件)
import QtQuick 2.4
Rectangle{
width: 200
height: 50
color: ListView.isCurrentItem ? "#003366" : "#585858"
border.color: "gray"
border.width: 1
Text{
anchors.centerIn: parent
color: "white"
text: name
}
}
Manager.qml(我想用作委托的其他组件)
import QtQuick 2.4
Rectangle{
width: 200
height: 50
color: "red"
border.color: "blue"
border.width: 1
Text{
anchors.centerIn: parent
color: "white"
text: name
}
}
我将不胜感激任何建议! 谢谢!
【问题讨论】:
-
在这种情况下,您还可以考虑创建一个唯一的
delegate,它在绑定中使用position来更改其外观。否则,您可以使用Loader,但您必须将一些信息转发给内部item,即真正的代表。 Folibis 解决方案也可以工作,但我认为在这种情况下不会,因为position本身就是一个角色。 -
为什么不简单地定义一个包含
Rectangles 的delegate并在每个position基础上设置它们的visible字段?