QML在Component中使用createObject填充ColumnLayout

问题描述 投票:0回答:1

我想在TabView / Tab中动态地向ComponentLayout添加一个Component。但我没有找到这样做的可能性。问题是我对我的ColumnLayout没有对createObject调用的正确父引用。因为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
        }
    }
}

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

qt tabs qml components tabview
1个回答
0
投票

好的,我自己找到了解决方案。而不是将ColumnLayout包含到Component中,我已将其拉出并创建了一个别名属性来发布它。有了这个,可以将对象添加到我的ColumnLayout。但是ColumnLayout得到了错误的父(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
        }
© www.soinside.com 2019 - 2024. All rights reserved.