StackView: storing components along with their items

馋奶兔 提交于 2019-12-23 03:48:55

问题


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?


回答1:


  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.



来源:https://stackoverflow.com/questions/32626053/stackview-storing-components-along-with-their-items

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!