StackView:存储组件及其项目 [英] StackView: storing components along with their items
问题描述
考虑以下代码:
StackView {
id: stack
}
Component {
id: componentFooBar
FooBar {}
}
...
stack.push({item: componentFooBar})
在上面的例子中,根据 Qt 源代码和文档,在 componentFooBar
被压入堆栈后,它的内部项 (FooBar
) 被加载并压入栈顶内部堆栈.如果我想访问堆栈头(通过 pop()
或 get(0)
),我将获得 FooBar
实例,而不是它的 Component
.所以对于 Qml StackView
没有像
In the example above, according to the Qt source and documentation, after componentFooBar
is pushed to the stack its inner item (FooBar
) is loaded and pushed to the top of the inner stack. And if I want to access stack head (either by pop()
or get(0)
), I'll get FooBar
instance, not its Component
. So for Qml StackView
there's no invariant like
stack.push(X)
X === stack.pop()
有没有办法访问推送的Component
?我现在唯一的想法是为 push()
/pop()
/get()
方法编写一些包装器并存储 Component
s 在一些单独的堆栈中:
Is there any way to access pushed Component
s? The only idea I have for now is to write some wrappers for push()
/pop()
/get()
methods and store Component
s in some separate stack:
StackView {
property var componentStack: []
function _push (x) {
push(x)
componentStack.push(x)
}
function _pop (x) {
pop(x)
return componentStack.pop()
}
}
但对我来说它看起来像一个黑客,而且我有很多使用默认 push()
/pop()
方法的代码.还有其他解决办法吗?
But for me it looks like an hack, also I have a lot of code using default push()
/pop()
methods. Is there any other solution?
推荐答案
创建一个组件数组,例如这里:
Create an array of your components, such as here:
StackView {
id: stackView
}
property variant myObjects: [component1.createObject(), component2.createObject(), component3.createObject()]
Component {
id: component1
}
Component {
id: component2
}
Component {
id: component3
}
然后在推送到 StackView
时确保使用 destroyOnPop
属性:
Then when pushing to StackView
make sure to use destroyOnPop
property:
stackView.push({item: myObjects[componentIndex], destroyOnPop: false})
通过执行这两个步骤,StackView
不会获得您的对象的所有权.因此,您可以直接处理对象,并且仍然可以多次推送/弹出 StackView
.
By following these two steps, StackView
does not take ownership by your objects. Therefore, you can work with objects directly and still push/pop many times to StackView
.
这篇关于StackView:存储组件及其项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!