我有这样的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',}} <class 'dict'>
file:///.../views/sc_side/Main.qml:6: ReferenceError: ggg is not defined
解决方法
您需要在调用View.setSource之前设置context属性,否则在读取qml文件时,确实没有定义属性ggg.
试试这个:
App = QGuiApplication(sys.argv) View = QQuickView() Context = View.rootContext() GlobalConfig = Config('sc').getGlobalConfig() print (GlobalConfig,GlobalConfig) View.setSource(QUrl('views/sc_side/Main.qml')) View.setResizeMode(QQuickView.SizeRootObjectToView) View.showFullScreen() sys.exit(App.exec_())
免责声明:在不知道Config是什么的情况下,我不能说它是否会在没有任何其他修改的情况下真正起作用.