创建外部组件对象的内部组件对象

Create Objects of inner Component of Object of outer Component

是否可以这样做:

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"})
    }
}

也就是说,我想在外部对象内部创建多个对象(在创建外部对象之后)。但是这是不可能的,因为我收到错误: TypeError: Cannot call method 'createObject' of undefined

有什么解决方法吗?是否只能在外部对象实例化期间实例化所有内部对象?

id超出了您的函数调用范围。

您可以向外部组件添加一个函数来创建您的对象:

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
            }
        }
    }
}

或者您将内部 Component 公开为 属性:

Component {
    id:compouter

    Column{
        property alias compinner: compinnerComponent
        anchors.fill: parent

        Component {
            id: compinnerComponent

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

并像那样访问它。

好的,我通过向外部对象发送信号找到了解决方法:

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
            signal createRect(var color)

            onCreateRect: {

                compinner.createObject(this, {"color": color})
            }

            Component {
                id: compinner

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

    Component.onCompleted: {

        var c = compouter.createObject(this)
        c.createRect("green")
        c.createRect("red")
    }

它正在工作,但也许有一些更通用的方法可以解决这个问题(请参阅已接受的答案)。正如张贴者所建议的那样,调用函数在语义上比发送信号更干净