2017-07-25 94 views
0

我在QML一个初学者,已经在QTç工作更上StackWidget ++在QML我很困惑使用stackView和已经写下面的代码:如何使用QML StackView?

Window { 
    visible: true 
    width: 640 
    height: 480 
    title: qsTr("Stack view") 

    MainForm { 
     StackView { 
      id: stackView 
      x: 0 
      y: 0 
      width: 360 
      height: 360 

      initialItem: page1 

      Rectangle { 
       id: page1 

       //anchors.fill: parent 
       color: "lightgreen" 
       Button { 
        id: buttonPage1 
        text: "back to 2" 
        anchors.centerIn: parent 
        onClicked: { 
         stackView.pop() //**Is THIS CORRECT** 
         stackView.push(page2) //**Is THIS CORRECT** 

        } 
       } 
       TextEdit { 
        id: te1 
        width: 105 
        height: 40 
        text: "enter" 
       } 
      } 
      Rectangle { 
       id: page2 

       //anchors.fill: parent 
       color: "lightblue" 
       Button { 
        id: buttonPage2 
        text: "back to 1" 
        anchors.centerIn: parent 
        onClicked: { 
         stackView.pop() //**Is THIS CORRECT** 
        } 
       } 
       TextEdit { 
        id: te2 
        width: 109 
        height: 29 
        text: "enter" 
       } 
      } 
     } 
    } 
} 

下面是问题:

  1. 在StackWidget中,我使用setCurrentIndex来设置所需的页面,我知道在QML中我应该使用push和pop。在这种情况下,如何使用push和pop根据一些选择在page1page2之间导航。 ?

  2. 最初,我可以加载所有页面到stackView

  3. 当我从stackView弹出一个项目时如何保存页面中的内容?

+0

这听起来像你想[StackLayout](https://doc.qt.io/qt-5/qml-qtquick-layouts-stacklayout.html),而不是StackView。 – jpnurmi

回答

2

我知道,我也不会精确地回答你关于如何使用StackView问题,那是因为我觉得你不希望有一个StackView按照你的描述。

StackView的使用案例是,当您在页面上按照名称所建议的页面时 - 在堆栈上。如果您只想在不能确定的页面之间进行切换,哪个逻辑上低于另一个页面,则StackView不是您想要的,您可能需要考虑SwipeView

SwipeView页面以并排的方式共存。自Qt 5.9以来,他们有一个interactive财产,您可能会禁用刷卡行为。 在这里,您可以通过设置currentIndex来选择要显示的页面。

但是,SwipeView将根据需要创建其页面,以减少内存和CPU负载(有效禁用未加载页面的绑定)。如果数据未存储在页面本身之外的model中,则可能会导致数据丢失。

如果你想在同一时间加载的所有网页,而您只需要切换可见一个,你可能会用一个简单的自定义组件去:

Item { 
    property int currentIndex 
    Page1 { visible: parent.currentIndex === 0 } 
    Page2 { visible: parent.currentIndex === 1 } 
    Page3 { visible: parent.currentIndex === 2 } 
    ... 
} 

或者你去,如:

MyView.qml

Item { 
    id: root 
    property int currentIndex: 0 
    default property Item newContent 

    onNewContentChanged: { 
     newContent.parent = root 
     newContent.visible = Qt.binding(bindingsClosure(root.children.length - 1)) 
    } 

    function bindingsClosure(index) { return function() { return root.currentIndex === index } } 
} 

main.qml

MyView { 
    Page1 { } 
    Page2 { } 
    Page3 { } 
} 
+0

你的上面的答案几乎匹配我的要求,我会尝试swipeView,然后将其标记为有答案。 – pra7