Search code examples
qtqmlqt-quick

Fill TabView from Pages' titles of corresponding SwipeView


Straitforward approach to create a multiple separate visible pages with easy navigation is to use SwipeView and TabBar together:

import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3

Page {
    id: page

    header: TabBar {
        id: tabBar

        currentIndex: swipeView.currentIndex

        TabButton {
            text: qsTr("Page1")
        }
        TabButton {
            text: qsTr("Page2")
        }
    }

    SwipeView {
        id: swipeView

        width: page.width
        height: page.height

        currentIndex: tabBar.currentIndex

        Page {
            width: swipeView.width
            height: swipeView.height

            title: qsTr("Page1")

            Pane {
                anchors.fill: parent
            }
        }
        Page {
            width: swipeView.width
            height: swipeView.height

            title: qsTr("Page2")

            Pane {
                anchors.fill: parent
            }
        } 
    }
}

There is title property in the Page component. It is not visible in the above case, but it is proper place to store the tab title on my mind. Can I generate (say, using Repeater) a contents of TabBar using some properties of SwipeView pages (namely .title) to fill TabButton.text?

I looked through documentation, but can't find a property of SwipeView, which allows me to get access to its pages by means of indices (e.g. pages[index]).


Solution

  • Qt Quick is great! I found the answer really quickly:

    Repeater {
        model: swipeView.count
        TabButton {
            text: swipeView.contentChildren[index].title
        }
    }
    

    or even simplier

    Repeater {
        model: swipeView.contentChildren
        TabButton {
            text: modelData.title
        }
    }