我有一个listview
谁的委托有一个转发器,它应该由文本填充。如果转发器的模型属性以这种方式硬编码:
model: ['String 1', 'String 2', 'String 3'];
通过在转发器区域显示3个项目,它可以完美地工作
但是,我想使用ListElement
发送这样的列表,这就是我尝试过的:
ListElement{
shape: "Circle"; colors: ['Red', 'Blue'];
}
不幸的是,这种方法不起作用并引发错误:
ListElement:不能将脚本用于属性值
我实现了多少这个? TIA
答案 0 :(得分:3)
值必须是简单的常量;字符串(引用并且可选地在对QT_TR_NOOP的调用中),布尔值(true,false),数字或枚举值(例如AlignText.AlignHCenter)。
向视图公开数据的最有效方法是创建C++ model。
但是,如果你真的不想使用C ++,你可以将颜色存储在以逗号分隔的字符串中,然后将它们拆分:
import QtQuick 2.6
import QtQuick.Window 2.0
Window {
visible: true
width: 200
height: 200
ListView {
width: 32
height: 64
anchors.centerIn: parent
model: ListModel {
ListElement{
shape: "Circle"
colors: "red, blue"
}
ListElement{
shape: "Square"
colors: "green,yellow"
}
}
delegate: Rectangle {
width: 32
height: 32
radius: shape === "Circle" ? width / 2 : 0
property var colorArray: colors.split(",")
gradient: Gradient {
GradientStop {
position: 0
color: colorArray[0]
}
GradientStop {
position: 1
color: colorArray[1]
}
}
}
}
}
答案 1 :(得分:1)
@ Mitch回答的另一种方法是放弃ListModel
并使用普通的Javascript对象数组作为模型。
使用该解决方案,您将失去ListModel
的动态功能(添加,删除,插入......)。您也无法在视图中使用部分或在此模型上使用代理模型。
import QtQuick 2.6
import QtQuick.Window 2.0
Window {
visible: true
width: 200
height: 200
ListView {
width: 32
height: 64
anchors.centerIn: parent
model: [
{
shape: "Circle",
colors: ["red", "blue"]
},
{
shape: "Square",
colors: ["green", "yellow"]
}
]
delegate: Rectangle {
width: 32
height: 32
radius: modelData.shape === "Circle" ? width / 2 : 0
gradient: Gradient {
GradientStop {
position: 0
color: modelData.colors[0]
}
GradientStop {
position: 1
color: modelData.colors[1]
}
}
}
}
}