我从API返回了几个不同的对象列表,用于定义ListView中的项目。如何保留用户交互所做的任何更改?如何保存启用的颜色以及强度是多少?
为了简洁起见,我已经删除了一些代码,但基本上,这应该显示一系列垂直滑块,一次只能启用其中一个。滑块的高度表示所选颜色的强度,这将影响系统的其他部分。我已经从已删除的代码中重构了这一点,该代码将ListView
中的演示数据直接作为带有ListModel
项的ListElement
。
我不确定getData-loop-append例程是最好的选择,我对使用数据填充ListView的其他方法持开放态度,也许还有其他形成数据的方法。但是,非常需要Color对象。
com.example.datamodels.Data.qml
QtObject {
id: color
readonly property string name
readonly property color displayColor
property bool enabled = false
property int intensity = 100
}
property variant dataListA: [
Color.white,
Color.blue,
Color.red
]
property variant dataListB: [
Color.green,
Color.purple,
Color.orange
]
function getData() {
if (something === enumA) {
return dataListA;
} else if (something === enumB) {
return dataListB;
}
}
Layout.qml
import com.example.datamodels
ListView {
id: _list
model: dataModel
ListModel {
id: dataModel
dynamicRoles: true
Component.onCompleted: {
var colors = Data.get();
for (var i=0; i < colors.length; i++) {
append(colors[i]);
}
}
}
delegate: Widget {
onStateChanged: {
if (state === "enabled") {
var items = _list.model;
// disable any currently enabled
for (var i = 0; i < items.count; i++) {
if (i !== index) {
var item = items.get(i);
if (item.enabled) {
item.enabled = false;
}
}
}
}
}
}
}
Widget.qml
Item {
id: _obj
height: _bar.height + _grabHandle.height
width: _grabHandle.width
property string colorName: model.name
property bool enabled: model.enabled
property int intensity: model.intensity
property color glowColor: model.displayColor
states: [
State {
name: "enabled"
when: _obj.enabled
PropertyChanges {
target: _dragMouseArea.drag
minimumY: 0
maximumY: _bar.height;
}
},
State {
name: "disabled"
when: !_obj.enabled
PropertyChanges {
target: _dragMouseArea.drag
minimumY: _bar.height / 2
maximumY: _bar.height / 2
}
}
]
Item {
id: _grabHandle
height: 100
width: 30
x: 0
y: _bar.height/2
Drag.active: _dragMouseArea.drag.active
RectangularGlow {
id: _glow
height: parent.height - 20
width: parent.width - 20
anchors.centerIn: parent
color: _obj.glowColor
cornerRadius: 0.0
property real adjustedVal: 1.0 - (_grabHandle.y / _bar.height)
glowRadius: adjustedVal * 20 + 20
spread: 0.0
opacity: 1.0
}
Text {
id: _colorTitle
text: _obj.colorName
color: "#FFFFFF"
anchors.topMargin: 0
font.pixelSize: 22
}
MouseArea {
id: _dragMouseArea
enabled: true
anchors.fill: parent
anchors.centerIn: parent
drag.target: parent
drag.axis: Drag.YAxis
drag.minimumY: _bar.height/2
drag.maximumY: _bar.height/2
drag.smoothed: false
onReleased: {
if (_obj.enabled) {
_obj.intensity = getIntensityFromHeight();
}
}
onClicked: {
_obj.enabled = !_obj.enabled
}
}
}
}