1

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 Components? The only idea I have for now is to write some wrappers for push()/pop()/get() methods and store Components 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?

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
binzo
  • 115
  • 8
  • Why do you need access to the component? – Mitch Sep 17 '15 at 11:50
  • @Mitch More generally, I need an invariant "what is pushed could be poped back, what is poped could be pushed again". Even more generally - I need some way to save/backup StackView, do something with it (clear, pop, push), and then restore it back. – binzo Sep 17 '15 at 11:59

1 Answers1

0
  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
    }
    
  2. Then when pushing to StackView make sure to use destroyOnPop 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.

nfranklin
  • 385
  • 1
  • 8
synacker
  • 1,722
  • 13
  • 32
  • 2
    The `destroyOnPop` is not needed since `StackView` only destroys by default items pushed as components or URLs, here it pushed as an `Item` directly. The push statement could then be rewritten like : `stackView.push(myObjects[componentIndex])` – GrecKo Sep 17 '15 at 14:39