我在许多窗口中使用StackLayout
,而不是使用currentIndex = 0
,例如,我想使用Item本身的id。这样,我就不需要关心在StackLayout
中实现的项的顺序,代码也更容易阅读。
我不知道该怎么做,也不知道这是否真的可行。有什么想法吗?
样本代码:
main.qml
StackLayout {
id: mainStack
width: parent.width - tabbar.width
x: tabbar.width
PageOne {id: pageOne}
PageTwo {id: pageTwo}
PageThree {id: pageThree}
}
Button {
text: "Go to"
onClicked: {
mainStack.currentIndex = 0 // how its done
mainStack.currentIndex = pageOne //what I want: using Item Id
}
}
您可以创建一个方法,在StackLayout的子级上进行搜索,如果找到了,则将currentIndex更改为关联索引:
StackLayout {
id: mainStack
width: parent.width - tabbar.width
x: tabbar.width
function changeTo(item){
for(var i in this.children){
if(this.children[i] === item){
this.currentIndex = i;
return true;
}
}
return false;
}
PageOne {id: pageOne}
PageTwo {id: pageTwo}
PageThree {id: pageThree}
}
Button {
text: "Go to"
onClicked: {
mainStack.changeTo(pageOne)
}
}