当我手动更改currentIndex
的{{1}}时,ListView
在设置为给定值之前设置为0。
主要问题是currentIndex
被触发2次:值为0,然后值为2.
请参阅以下代码:
onCurrentIndexChanged
我获得的日志:
import QtQuick 2.8
import QtQuick.Controls 2.1
ApplicationWindow {
visible: true
width: 100
height: 100
ListView {
id: list
anchors.fill: parent
currentIndex: -1
model: ListModel {}
delegate: Text {
text: model.name
}
Component.onCompleted: {
model.append({"name": "plip"})
model.append({"name": "plop"})
model.append({"name": "ploup"})
currentIndex = 2
}
onCurrentIndexChanged: {
console.log("currentIndex", currentIndex)
}
}
}
我发现避免此问题的唯一解决方案是拥有另一个属性qml: currentIndex 0
qml: currentIndex 2
并将indexToBeSet
与实际indexToBeSet
进行比较:
currentIndex
日志:
import QtQuick 2.8
import QtQuick.Controls 2.1
ApplicationWindow {
visible: true
width: 100
height: 100
ListView {
id: list
property int indexToBeSet: -1
anchors.fill: parent
currentIndex: -1
model: ListModel {}
delegate: Text {
text: model.name
}
Component.onCompleted: {
model.append({"name": "plip"})
model.append({"name": "plop"})
model.append({"name": "ploup"})
setCurrentIndex(2)
}
onCurrentIndexChanged: {
console.log("currentIndex", currentIndex)
if (currentIndex === indexToBeSet) {
console.log("=> do some stuff")
}
}
function setCurrentIndex(index) {
indexToBeSet = index
currentIndex = index
}
}
}
但我认为这是一个非常讨厌的解决方案。
为什么会这样?这是一个错误还是预期的行为? 有没有更好的方法来避免这个问题?
更多详情:
看起来问题只发生在我在前一个qml: currentIndex 0
qml: currentIndex 2
qml: => do some stuff
等于currentIndex
时添加元素后更改currentIndex
时。
请参阅以下代码:
-1
以及相应的日志:
Component.onCompleted: {
model.append({"name": ""})
model.append({"name": ""})
model.append({"name": ""})
currentIndex = 1 // WILL BE SET TO 0 BEFORE 1
model.append({"name": ""})
currentIndex = 2 // no problem because currentIndex was not -1
currentIndex = -1 // no problem
currentIndex = 2 // no problem because we did not add new elements after setting to -1
currentIndex = -1 // no problem
model.append({"name": ""})
currentIndex = 1 // WILL BE SET TO 0 BEFORE 1
}