Stacklayout navigate using Item Id instead of currentIndex = #num

588 views Asked by At

I am using StackLayout with many windows, instead of using the currentIndex = 0 for example I want to use the id for the Item itself. This way I will not need to care which order are the Items implemented in within the StackLayout, and the code will be easier to read.

I didn't happen to find how to do so or if it's actually possible. Any ideas?

Sample code:

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
    }
}
2

There are 2 answers

1
eyllanesc On BEST ANSWER

You can create a method that does the search on the children of the StackLayout and if it finds it then change the currentIndex to the associated index:

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
Noki On

Since Qt 5.15 you can use the attached property of the StackLayout to access index of a page.

Like so :


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

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