How to set currentIndex of SwipeView to currentIndex of TabBar “by reference” after going to specific page?

早过忘川 提交于 2019-12-05 11:05:07

In order to move to the next or the previous page without breaking the currentIndex bindings, you can call incrementCurrentIndex() or decrementCurrentIndex(), respectively. These methods were introduced in Qt Quick Controls 2.1 in Qt 5.8.

Given that the currentIndex setter aka. QQuickContainer::setCurrentIndex() is a slot, you can also call setCurrentIndex() from QML to jump to an arbitrary page. This will not break the existing bindings either.

Button {
    onClicked: tabBar.setCurrentIndex(1)
}
Jon McClung

You could be looking for Signals. From the Qt documentation:

Property Change Signal Handlers

A signal is automatically emitted when the value of a QML property changes. This type of signal is a property change signal and signal handlers for these signals are written in the form on<Property>Changed where <Property> is the name of the property, with the first letter capitalized.

Thus, for your example:

SwipeView {
    id: swipeView
    ...
    currentIndex: tabBar.currentIndex
    onCurrentIndexChanged: {
        tabBar.currentIndex = currentIndex
    }
...
footer: TabBar {
    id: tabBar
    currentIndex: swipeView.currentIndex
    onCurrentIndexChanged: {
        swipeView.currentIndex = currentIndex
    }
    ...

And that way you can simply set the currentIndex of either and rest assured that they will remain "linked" due to the signal handlers.

Edit:

As pointed out by jpnurmi, you can also use Qt.binding like so:

onClicked: {
    swipeView.currentIndex = 1;
    swipeView.currentIndex = Qt.binding(function() {return tabBar.currentIndex})
}

This will restore the binding after the static value has been assigned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!