ReferenceError: "something" is not defined in QML

13,540

Solution 1

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.

Solution 2

You have to define the context property before loading QML file, it's better because it avoids warnings and context reloading.

If you are REALLY forced to do it after, just add a security in your QML code :

color: (typeof (ggg) !== "undefined" ? ggg.Colors.notificationMouseOverColor : "transparent");

Then when you will set the context property it will reload the context (not recommanded) but at least no error will happen.

Share:
13,540
Vahid Kharazi
Author by

Vahid Kharazi

Updated on June 08, 2022

Comments

  • Vahid Kharazi
    Vahid Kharazi about 2 years

    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?