当我尝试更改包含在ListModel中的项的属性值时,以下代码不起作用:
主.qml
import QtQuick 2.0
Item {
anchors.fill: parent
ListModel { id: modelCrayon }
Component.onCompleted: {
for (var i = 0; i < 10; i++)
modelCrayon.append( { _tag: i, _source: "resources/crayon-green.png", _selected: false } )
}
Column {
x: -170
spacing: 0
Repeater {
model: modelCrayon
delegate: Crayon {
tag: _tag
source: _source
selected: _selected
onCrayonSelected: {
for (var i = 0; i < modelCrayon.count; i++) {
if (i == tag) continue;
modelCrayon.setProperty(i, "_selected", false);
}
}
}
}
}
}
蜡笔小新
import QtQuick 2.0
Image {
property bool selected
property int tag
signal crayonSelected()
id: crayon
smooth: true
fillMode: Image.PreserveAspectFit
onSelectedChanged: console.debug(tag, selected)
MouseArea {
anchors.fill: parent
onClicked: {
selected = !selected
if (selected) crayonSelected()
}
}
states: State {
name: "selected"; when: selected == true
PropertyChanges { target: crayon; x: 30 }
}
transitions: Transition {
from: ""; to: "selected"
PropertyAnimation { property: "x"; duration: 500; easing.type: Easing.InOutQuad }
}
}
控制台上不显示任何内容,因此"选定"变量永远不会更改。我确定我错过了一些明显的东西。
顺便问一下,有没有更聪明的方法将ListModel用作OptionBox?我的意思是我一次只想要一个项目必须具有所选属性 == true。或者,换句话说,跟踪所选索引。
这是实现我要求的工作代码。但它没有回答为什么没有设置该属性。
ListView {
id: list
anchors.verticalCenter: parent.verticalCenter
height: parent.height
x: -150
spacing: 0
orientation: ListView.Vertical
focus: true
model: modelCrayon
delegate: Crayon {
id: delegate
source: _source
selected: ListView.isCurrentItem
MouseArea {
anchors.fill: parent
onClicked: list.currentIndex = index
}
}
}
我已经测试了您的示例代码(列版本),它适用于Qt 5.4/Windows 7 64位。
您的运行环境是什么?