QT的PathView这个控件使用起来很不错,用起来简单,而且效果也不错。

但是最近发现它里面有个较为“坑”的地方,就是在使用它的onCurrentIndexchanged这个槽的时候。

比如当前的currentIndex为0,count为5,当你把它的currentIndex设置为2,这时候onCurrentIndexchanged这个槽会执行多少次呢?

代码如下:

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
visible: true
width: 180; height: 400

MouseArea {
anchors.fill: parent
onClicked: {
myview.currentIndex = 2
}
}

Rectangle {
width: 180; height: 400

Component {
id: contactDelegate
Item {
width: 180; height: 40
Column {
Text { text: '<b>Name:</b> ' + name }
Text { text: '<b>Number:</b> ' + number }
}
}
}

PathView {
id: myview
anchors.fill: parent
model: ContactModel {}
delegate: contactDelegate
highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
path: Path {
startX: 120; startY: 100
PathQuad { x: 120; y: 25; controlX: 260; controlY: 75 }
PathQuad { x: 120; y: 100; controlX: -20; controlY: 75 }
}
focus: true

onCurrentIndexChanged: console.log(currentIndex)
}
}
}

执行结果:

Qt 之 PathView中currentIndex的“坑”_qml

我们可以看到,它执行了3次槽函数。。。是渐变执行过去。

如果当前currentIndex为0,设置它为3呢,又是什么情况呢?

Qt 之 PathView中currentIndex的“坑”_qt_02

结果不是0,1,2,3,而是0,4,3 。

对PathView的count变得很多的时候,count为400,设置currentIndex为200,情况又如下:

Qt 之 PathView中currentIndex的“坑”_currentIndex_03


原来qt的PathView做了优化,它会去找一个最短路径,但并不是一个一个变化的。而且更为“坑”的是在执行这几个槽函数的时间内,你去设置改变PathView的currentIndex是不生效的。所以使用PathView的onCurrentIndexchanged这个槽函数的时候一定注意。


那么,和它类似的ListView是不是也有这样的一个“坑”呢?下面我们来验证一下:

import QtQuick 2.5
import QtQuick.Window 2.2

Window {
visible: true
width: 180; height: 400

MouseArea {
anchors.fill: parent
onClicked: {
myview.currentIndex = 3
}
}

Rectangle {
width: 180; height: 400

Component {
id: contactDelegate
Item {
width: 180; height: 40
Column {
Text { text: '<b>Name:</b> ' + name }
Text { text: '<b>Number:</b> ' + number }
}
}
}

ListView {
id: myview
anchors.fill: parent
model: ContactModel {}
delegate: contactDelegate
highlight: Rectangle { color: "lightsteelblue"; radius: 5 }
// path: Path {
// startX: 120; startY: 100
// PathQuad { x: 120; y: 25; controlX: 260; controlY: 75 }
// PathQuad { x: 120; y: 100; controlX: -20; controlY: 75 }
// }
focus: true

onCurrentIndexChanged: console.log(currentIndex)
}
}
}


代码基本没变,就是把PathView改成ListView,把path的属性屏蔽掉,下面是测试结果:

Qt 之 PathView中currentIndex的“坑”_qml_04

它和我们的预期是一样的,与PathView不同。


去qt的帮助文档里面,没有找到解释。如果有时间的话去看看源码,也希望有知道的也不吝赐教~~~