动态创建的组件无法访问父属性

2024-07-02 11:00:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的python&;qml项目我有一个页面结构,如下所示

 Window
  |-myObject
  |-Loader
   |-homePage
    |-myComponent

其中MyComponent是我使用以下Python代码动态创建的组件:

root = engine.rootObjects()[0].findChild(QObject, "HomePage")
componentFigure = QQmlComponent(engine)
componentFigure.loadUrl(QUrl("components/MyComponent.qml"))
instanceFigure = componentFigure.create()
instanceFigure.setParentItem(root)

现在我想访问myObject属性,从HomePage它工作正常,从myComponent它不工作(无法读取未定义的属性名

我的组件创建中可能存在一些问题

根页面代码:

Window {
    Settings {
        id: appSettings
        property bool light: true
    }
    QtObject {
        id: myObject
        property color myColor: {appSettings.mySetting ? "#FFFFFF" : "#000000"}
    }
    Rectangle {
        anchors.fill: parent
        Loader {
            anchors.fill: parent
            source: Qt.resolvedUrl("pages/homePage.qml")
        }
    }
}

MyComponent代码:

MyComponent{
    anchors.fill: parent
    Rectangle {
        anchors.fill: parent
        color: myObject.myColor
    }
}

Tags: 代码组件root页面loaderwindowqmlfill
1条回答
网友
1楼 · 发布于 2024-07-02 11:00:43

问题是myObject只会是根组件中的可见标识符。从该文件之外的其他组件将看不到该文件。只有组件的顶级QML元素的属性在组件范围层次结构中可见

有关更多信息,请参见此:https://doc.qt.io/qt-5/qtqml-documents-scope.html#component-scope

您需要确保在代码中设置了这些连接,如下所示:

instanceFigure = componentFigure.create(qmlContext(root))

但是,请注意,不建议以这种方式(通过父组件作用域的隐式访问)访问组件。最好通过显式属性向下传递对象引用

相关问题 更多 >