QML ListView 的不同代表 [英] Different delegates for QML ListView
问题描述
我想知道是否可以为 QML ListView
使用(几个)不同的代表.
I would like to know if it's possible to use (several) different delegates for a QML ListView
.
根据 ListView
模型中的单个对象,我想可视化具有不同委托的对象.
Depending on the individual object in the ListView
model, I would like to visualize the objects with different delegates.
这段代码解释了我想要实现的目标:
This piece of code explains what I want to achieve:
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(我想用作委托的一个可能的组件)
Employee.qml (One possible Component which I would like to use as a delegate)
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(我想用作代理的其他组件)
Manager.qml (other Component I would like to use as a delegate)
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
}
}
我将不胜感激!谢谢!
推荐答案
我遇到了同样的问题,Qt 文档提供了一个很好的答案:http://doc.qt.io/qt-5/qml-qtquick-loader.html#using-a-loader-within-a-view-delegate
I've had the same problem, the Qt documentation is providing a pretty good answer: http://doc.qt.io/qt-5/qml-qtquick-loader.html#using-a-loader-within-a-view-delegate
最简单的解决方案是使用内联 Component
和 Loader
来设置 source
文件:
The easiest solution is an inline Component
with a Loader
to set a source
file:
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: Component {
Loader {
source: switch(position) {
case "Engineer": return "Employee.qml"
case "Manager": return "Manager.qml"
}
}
}
}
任何使用 Loader.srcComponent
的尝试都会导致模型中的任何变量(包括 index
)丢失.变量存在的唯一方法是子Component
在主Component
中,但这样只能存在一个,所以没用.
Any attempt to use Loader.srcComponent
will result in missing any variable from the model (including index
). The only way for the variables to be present is the children Component
to be inside the main Component
, but then only one can be present, so it is useless.
这篇关于QML ListView 的不同代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!