我有这样的Main.qml文件:
import QtQuick 2.0 Rectangle { color: ggg.Colors.notificationMouseOverColor width: 1024 height: 768 }
在python文件中,我有这个(我使用形式PyQt5):
App = QGuiApplication(sys.argv) View = QQuickView() View.setSource(QUrl('views/sc_side/Main.qml')) Context = View.rootContext() GlobalConfig = Config('sc').getGlobalConfig() print (GlobalConfig, type(GlobalConfig)) Context.setContextProperty('ggg', GlobalConfig) View.setResizeMode(QQuickView.SizeRootObjectToView) View.showFullScreen() sys.exit(App.exec_())
这个python代码打印这个配置:
{'Colors': {'chatInputBackgroundColor': '#AFAFAF', 'sideButtonSelectedColor': '#4872E8', 'sideButtonTextColor': '#787878', 'sideButtonSelectedTextColor': '#E2EBFC', 'sideButtonMouseOverColor': '#DDDDDD', 'buttonBorderColor': '#818181', 'notificationMouseOverColor': '#383838', }}
当我运行此代码时,我的矩形颜色正确更改,但我有这个错误:
file:///.../views/sc_side/Main.qml:6: ReferenceError: ggg is not defined
但我不知道为什么会发生这种错误,我怎么能解决这个错误?
您需要在调用之前设置context属性View.setSource
,否则在读取qml文件时,ggg
确实未定义该属性.
试试这个:
App = QGuiApplication(sys.argv) View = QQuickView() Context = View.rootContext() GlobalConfig = Config('sc').getGlobalConfig() print (GlobalConfig, type(GlobalConfig)) Context.setContextProperty('ggg', GlobalConfig) View.setSource(QUrl('views/sc_side/Main.qml')) View.setResizeMode(QQuickView.SizeRootObjectToView) View.showFullScreen() sys.exit(App.exec_())
免责声明:不知道是什么Config
,我不能说没有任何其他修改它是否真的有用.
你必须在加载QML文件之前定义上下文属性,它更好,因为它避免了警告和上下文重新加载.
如果您之后真的被迫执行此操作,只需在QML代码中添加一个安全性:
color: (typeof (ggg) !== "undefined" ? ggg.Colors.notificationMouseOverColor : "transparent");
然后,当您设置context属性时,它将重新加载上下文(不推荐),但至少不会发生错误.