Search code examples
qtqmlqt5qtquick2qt-quick

Create Objects of inner Component of Object of outer Component


Is it possible to do something like this:

import QtQuick 2.7
import QtQuick.Window 2.2

Window{
    id: root_
    visible: true
    width: 300
    height: 300

    Component {
        id:compouter

        Column{
            anchors.fill: parent

            Component {
                id: compinner

                Rectangle {
                    width:parent.width
                    height:parent.height/2
                }
            }
        }
    }

    Component.onCompleted: {

        var c = compouter.createObject(this)
        //var d = c.compinner.createObject(c, {"color": "green"})
        //var e = c.compinner.createObject(c, {"color": "red"})
    }
}

That is, I want to create multiple Objects inside the outer object (after the outer object was created). However this isn't possible, as I get the error: TypeError: Cannot call method 'createObject' of undefined

Is there any workaround for this? Is it maybe only possible to instantiate all inner objects during the instantiation of the outer object?


Solution

  • The ids are out of the scope for your function call.

    You can either add a function to your outer component, that creates your objects:

    Component {
        id:compouter
    
        Column{
            anchors.fill: parent
    
            function createCompinner(arg) { compinner.createObject(this, arg) }
    
            Component {
                id: compinner
    
                Rectangle {
                    width:parent.width
                    height:parent.height/2
                }
            }
        }
    }
    

    or you expose the inner Component as a property:

    Component {
        id:compouter
    
        Column{
            property alias compinner: compinnerComponent
            anchors.fill: parent
    
            Component {
                id: compinnerComponent
    
                Rectangle {
                    width:parent.width
                    height:parent.height/2
                }
            }
        }
    }
    

    and access it like that.