2017-07-25 91 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