转到特定页面后,如何“通过引用”将SwipeView的currentIndex设置为TabBar的currentIndex?

Jon*_*ung 5 c++ qt qml qtquick2 qtquickcontrols2

我开始使用QtQuick Controls 2.0。我有使用C ++的经验,也有少量使用Qt的经验,但是我以前从未使用过QML。

我有一个TabBarSwipeView彼此关联的。我的意思是,当您在上选择一个页面时TabBar,将SwipeView转到该页面。当您从滑动到页面时SwipeViewTabBar更新本身会反映出来。

作为一项学习练习,我决定创建一个按钮,该按钮会将用户带到第二页。问题在于,我似乎找不到不弄乱the TabBar和the 之间的联系的方法SwipeView

以下代码是我提出的最好的代码。它正确地进入到第二页,当我改变当前页面用TabBarSwipeView还是更新。但是,滑动到新页面将不再更新TabBar。似乎在对冒号进行初始化时,设置tabBar.currentIndexswipeView.currentIndex仅具有通过引用进行设置的效果。用等号设置值。如何在保持不变的情况下移至特定页面swipeView.currentIndex == tabBar.currentIndex

// main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    SwipeView {
        id: swipeView
        anchors.fill: parent
        currentIndex: tabBar.currentIndex

        Page {
            Button {
                text: qsTr("Continue to Page 2")
                onClicked: {
                    tabBar.currentIndex = 1;
                    // this next line merely sets tabBar.currentIndex to 1
                    tabBar.currentIndex = swipeView.currentIndex
                }
                anchors.centerIn: parent
                width: text.implicitWidth
                height: text.implicitHeight
            }
        }

        Page {
            Label {
                text: qsTr("Second page")
                anchors.centerIn: parent
            }
        }
    }

    footer: TabBar {
        id: tabBar
        currentIndex: swipeView.currentIndex
        TabButton {
            text: qsTr("First")
        }
        TabButton {
            text: qsTr( "Second")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

C ++代码只是Qt Creator为我提供的默认代码:

// main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)

jpn*_*rmi 6

为了在不破坏currentIndex绑定的情况下移至下一页或上一页,可以分别调用incrementCurrentIndex()decrementCurrentIndex()。这些方法是在Qt 5.8的Qt Quick Controls 2.1中引入的。

鉴于currentIndex二传手又名。QQuickContainer::setCurrentIndex()是一个插槽,您也可以setCurrentIndex()从QML 调用以跳至任意页面。这也不会破坏现有的绑定。

Button {
    onClicked: tabBar.setCurrentIndex(1)
}
Run Code Online (Sandbox Code Playgroud)