在我的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
}
}
问题是
myObject
只会是根组件中的可见标识符。从该文件之外的其他组件将看不到该文件。只有组件的顶级QML元素的属性在组件范围层次结构中可见有关更多信息,请参见此:https://doc.qt.io/qt-5/qtqml-documents-scope.html#component-scope
您需要确保在代码中设置了这些连接,如下所示:
但是,请注意,不建议以这种方式(通过父组件作用域的隐式访问)访问组件。最好通过显式属性向下传递对象引用
相关问题 更多 >
编程相关推荐