Qt Quick QML窗口中的多种模式?

Qt Quick QML窗口中的多种模式?,qt,qml,qt5,qtquick2,qt-quick,Qt,Qml,Qt5,Qtquick2,Qt Quick,假设我有一个包含一组不同控件的QML窗口: Window { ... TextEdit { ... } CheckBox { ... } Button { ... } etc } 现在,我希望我的窗口在某个事件上更改“模式”,并显示一组完全不同的控件 想象一下它是多屏幕窗体的一部分。当前状态是表单的第一页。当用户单击“下一步”按钮时,将转到表单的第2页。我想添加一组表示第2页的新控件 在QtQuick/QML中组织此操作的正确方法是什么?常用的方法是使用StackView

假设我有一个包含一组不同控件的QML窗口:

Window {
  ...

  TextEdit { ... }
  CheckBox { ... }
  Button { ... }
  etc
}

现在,我希望我的窗口在某个事件上更改“模式”,并显示一组完全不同的控件

想象一下它是多屏幕窗体的一部分。当前状态是表单的第一页。当用户单击“下一步”按钮时,将转到表单的第2页。我想添加一组表示第2页的新控件


在QtQuick/QML中组织此操作的正确方法是什么?

常用的方法是使用StackView。该组织将是这样的:

Window {
    StackView {
        id: stackView
        initialItem: page1
    }
    Item {
        id: footerItem
        // Maybe add other buttons here too
        Button {
            id: nextBtn
            text: "Next"
            onClicked: {
                stackView.push(page2);
            }
        }
    }

    Component {
        id: page1
        Page1 {
             // Define this in separate Page1.qml file
             // This is where your page 1 controls go.
        }
    }
    Component {
        id: page2
        Page2 {
             // Define this in separate Page2.qml file
             // This is where your page 2 controls go.
        }
    }

}

我可能会使用“后退”和“下一步”按钮实现模式更改视图或表单。
StackLayout
类提供了一个项目堆栈,其中一次只有一个项目可见。通过更新
currentIndex
进入下一个或上一个模式

StackLayout {
    id: layout
    anchors.fill: parent
    currentIndex: 1
    Rectangle {
        color: 'teal'
        implicitWidth: 200
        implicitHeight: 200
    }
    Rectangle {
        color: 'plum'
        implicitWidth: 300
        implicitHeight: 200
    }
}