首页 > 解决方案 > Stacklayout 使用 Item Id 而不是 currentIndex = #num 导航

问题描述

我正在使用StackLayout许多窗口,而不是使用currentIndex = 0例如我想为项目本身使用 id 的示例。这样我就不需要关心在 中实现的 Items 的顺序是什么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
    }
}

标签: qtqmlstacklayout

解决方案


您可以创建一个对 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)
    }
}


推荐阅读