ReferenceError: "something" is not defined in QML

2 8 picture 2 8 · Jan 29, 2014 · Viewed 10k times · Source

I have Main.qml file like this:

import QtQuick 2.0    

Rectangle {
    color: ggg.Colors.notificationMouseOverColor
    width: 1024
    height: 768
}

in python file, i have this(i use form 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_())

this python code print this for config:

{'Colors': {'chatInputBackgroundColor': '#AFAFAF', 'sideButtonSelectedColor': '#4872E8', 'sideButtonTextColor': '#787878', 'sideButtonSelectedTextColor': '#E2EBFC', 'sideButtonMouseOverColor': '#DDDDDD', 'buttonBorderColor': '#818181', 'notificationMouseOverColor': '#383838', }} <class 'dict'>

when i run this code, my rectangle color change correctly, but i have this error:

file:///.../views/sc_side/Main.qml:6: ReferenceError: ggg is not defined

but i don't know why this error happend, how i can fix this error?

Answer

mata picture mata · Feb 2, 2014

You need to set the context property before you call View.setSource, otherwise at the moment the qml file is read the property ggg is indeed not defined.

Try this:

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_())

Disclaimer: without knowing what Config is, I can't say if it will really work without any other modification.