我尝试将滑块的值绑定到ListElement的属性值,但是当ListElement的属性改变时,滑块的值并没有相应改变,这意味着绑定不成功
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.15
ApplicationWindow{
width: 1000
height: 480
visible: true
title: qsTr("Hello World")
ListModel{
id: deviceModel
ListElement{value:100}
ListElement{value:100}
ListElement{value:100}
ListElement{value:100}
}
property var temp: deviceModel.get(0);
Slider{
id:slider
from:0
to:10000
value: temp.value //Bind the value of the slider bar to the value attribute of the global object temp
}
Timer{
interval: 1000
running: true
repeat: true
onTriggered:{
temp.value+=100
console.log(temp.value)
console.log(slider.value)
/* Output result: It can be found that the value of Slider does not change with the change of the temp's value atrribute
qml: 1500
qml: 500
qml: 2500
qml: 500
qml: 3500
qml: 500
qml: 4500
qml: 500
*/
}
}
}
因为您正在使用
deviceModel.get(0)
,所以您可以单向访问您的 ListModel
。要恢复值,您应该考虑使用 deviceModel.put(...)
。
但是,QML 已经内置了对模型的双向访问。您应该考虑使用
ListView
(或 Repeater
)。然后,当您需要发布值时,将它们直接写入ListModel
。
ListModel{
id: deviceModel
ListElement{deviceValue:100}
ListElement{deviceValue:100}
ListElement{deviceValue:100}
ListElement{deviceValue:100}
}
ListView {
anchors.fill: parent
model: deviceModel
delegate: Column {
Slider{
id:slider
from:0
to:10000
value: deviceValue
onValueChanged: deviceValue = value
}
Timer{
interval: 1000
running: true
repeat: true
onTriggered:{
deviceValue+=100
console.log(deviceValue)
}
}
}
}
您可以在线尝试!
如果您只想在
ListModel
中显示一个元素,请考虑使用 DelegateModel
。