问题
Consider the following code:
StackView {
id: stack
}
Component {
id: componentFooBar
FooBar {}
}
...
stack.push({item: componentFooBar})
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()
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()
}
}
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?
回答1:
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 }
Then when pushing to
StackView
make sure to usedestroyOnPop
property:stackView.push({item: myObjects[componentIndex], destroyOnPop: false})
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
.
来源:https://stackoverflow.com/questions/32626053/stackview-storing-components-along-with-their-items