gpt4 book ai didi

qt - 如何使用 QML StackView?

转载 作者:行者123 更新时间:2023-12-04 13:22:54 25 4
gpt4 key购买 nike

我是 QMl 的初学者,并且在 QT C++ 中的 StackWidget 上做了更多工作。在 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弹出item时如何保存页面内容?

最佳答案

我知道我不会完全回答你关于如何使用 StackView 的问题,那是因为我认为你不希望在你的之后有一个 StackView说明。

StackView 的用例是,当您将页面(顾名思义)放在堆栈上时。如果您只想在页面之间切换,无法确定哪个页面在逻辑上位于另一个页面之下,StackView 不是您想要的,您可能需要考虑 SwipeView.

SwipeView 中,页面以并排方式共存。从 Qt 5.9 开始,它们有一个 interactive 属性,您可以使用它来禁用 swipe 行为。您可以在此处通过设置 currentIndex 选择要显示的页面。

但是,SwipeView 将根据需要创建其页面,以减少内存和 CPU 负载(有效地禁用卸载页面的绑定(bind))。如果数据未存储在页面本身之外的 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 } }
}

主.qml

MyView {
Page1 { }
Page2 { }
Page3 { }
}

关于qt - 如何使用 QML StackView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com