【问题标题】:Stacklayout navigate using Item Id instead of currentIndex = #numStacklayout 使用 Item Id 而不是 currentIndex = #num 导航
【发布时间】:2021-08-06 00:07:18
【问题描述】:

我在许多窗口中使用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


    【解决方案1】:

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

    【讨论】:

    • 很好的解决方法,效果很好。这将增强代码的可读性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2018-01-18
    相关资源
    最近更新 更多