Search code examples
qtvariablesscopeqmlglobal-variables

Declare a global property in QML for other QML files


I want to declare a global property in a config file and use it in other files. For example, declare mainbg in:

Style.qml:

property color mainbg: 'red'

and use it in other QML files (like view.qml and main.qml).

How can I do that?


Solution

  • Use a QML Singleton.

    Please reference Qt Wiki — Qml Styling — Approach 2: Style Singleton -- The ugly QTBUG-34418 comments are mine.

    These are the pieces you need:

    Style.qml:

    pragma Singleton
    import QtQuick 2.0
    QtObject {
        property color mainbg: 'red'
    }
    

    qmldir:

    This file must be in the same folder as the singleton .qml file (Style.qml in our example) or you must give a relative path to it. qmldir may also need to be included by the .qrc resource file. More information about qmldir files can be found here.

    # qmldir
    singleton Style Style.qml
    

    How to Reference:

    import QtQuick 2.0
    import "."  // this is needed when referencing singleton object from same folder
    Rectangle {
        color: Style.mainbg  // <- there it is!!!
        width: 240; height 160
    }
    

    This approach is available since Qt 5.0. You need a folder import statement, even if referencing the QML singleton in the same folder. If is the same folder, use: import ".". This is the bug that I documented on the qt-project page (see QTBUG-34418, singletons require explicit import to load qmldir file).