QML 在组件中用 createObject 填充 ColumnLayout

QML fill ColumnLayout with createObject in a Component

我想将组件动态添加到 TabView/Tab 中的 ColumnLayout。但我还没有找到这样做的可能性。问题是我没有对 createObject 调用的 ColumnLayout 的正确父引用。 因为Tab是动态加载Component的,所以我把ColumnLayout封装在了Component中。

在 QML 调试器中,我可以解决以下路径:objForm.tabView.tabStatus.tabStatusLoader.colLayout,但我不能将其用作正确的父项。

好像不在范围内

TypeError: Cannot read property 'tabStatus' of undefined

ObjForm.ui.qml

Item {
    id: item1
    width: 400
    height: 400

    property QtObject object

    property Component compLayout

    TabView {
        id: tabView
        anchors.fill: parent
        Tab {
            id: tabStatus
            title: "status"
            Loader {
                id: tabStatusLoader
                sourceComponent: compLayout
            }
        }
    }
}

ObjForm.qml

ObjectViewForm {
    id: objForm
    anchors.fill: parent
    object: someObj

    compLayout: Component {
        id: layoutComp
        ColumnLayout {
            id: colLayout
            spacing: 2
        }
    }

    onObjectChanged: {
        // Here i want to add the someLabel Component to the ColumnLayout
        someLabel.createObject(*PARENT*)
    }

Component {
    id: someLabel

    Row {
        property string text
        property string label

        spacing: 5

        Label {
            text: parent.label
        }

        Label {
            text: parent.text
        }
    }
}

有谁知道如何解决这个问题或者可以提出更好的建议吗?

好的,我自己找到了解决办法。为了将 ColumnLayout 包含到组件中,我将其拉出并制作了一个别名 属性 来发布它。这样就可以将对象添加到我的 ColumnLayout 中。但是 ColumnLayout 得到了错误的 parent(objForm) 而不是 Component。

组件不能作为父组件,因为需要 QQuickItem* 而不是 QObject*,并且除了 'id' 之外,其他组件不能包含属性。因此需要一个虚拟物品。

要重新设置 ColumnLayout 的父级,Item 需要一个 Component.onCompleted 函数来设置父级。

ObjectViewForm {
        id: objForm
        anchors.fill: parent
        object: someObj

        property alias componentLayout: colLayout

        compLayout: Component {
            id: layoutComp
            Item {
                id: dummy
                Component.onCompleted:  {
                    colLayout.parent = dummy
                }
            }
        }

        ColumnLayout {
            id: colLayout
            spacing: 2
        }