Stacklayout 使用 Item Id 而不是 currentIndex = #num

问题描述 投票:0回答:2

我在许多窗口中使用

StackLayout
,而不是使用
currentIndex = 0
,例如我想使用项目本身的 id。这样我就不需要关心
StackLayout
中实现的 Items 的顺序,并且代码将更易于阅读。

我没有碰巧找到如何做到这一点或者是否确实可行。有什么想法吗?

示例代码:

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
    }
}
qt qml stacklayout
2个回答
3
投票

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


0
投票

从 Qt 5.15 开始,您可以使用 StackLayout 的附加属性来访问页面的索引。

就像这样:


StackLayout {
     Item { id: pageOne }
     Item { id: pageTwo }
     Item { id: pageThree }
}

Button {
    text: "Go to"
    onClicked: {
        mainStack.currentIndex = pageOne.StackLayout.index
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.