declare global property in QML for other QML files

前端 未结 6 522
孤街浪徒
孤街浪徒 2020-11-27 17:53

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

Style.qml:



        
6条回答
  •  清酒与你
    2020-11-27 17:55

    Use a QML Singleton.

    Please reference "Approach 2" on this page -- 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 Qt5.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).

提交回复
热议问题