QML - Share color values and other read-only values across multiple QML files

若如初见. 提交于 2019-12-02 04:35:40
eyllanesc

The solution is to use a singleton, in your case you must import it correctly, assuming that the .qml are in the same qrc you just have to do the following:

.qrc

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        [...]
        <file>style/qmldir</file>
        <file>style/style.qml</file>
    </qresource>
</RCC>

Style.qml

pragma Singleton
import QtQuick 2.0

QtObject {
   readonly  property int padding: 20
   readonly property color textColor: "green"
}

qmldir

singleton Style 1.0 Style.qml

main.qml

import QtQuick 2.0
import "style"

Text {
    font.pixelSize: Style.textSize
    color: Style.textColor
    text: "Hello World"
}

In the following link there is an example

If your object tree is not too deep, it is applicable to simply declare the properties in the root object of main.qml, which will make them resolvable from all qml files thanks to dynamic scoping, as long as you take care not to shadow them by identically named local properties.

If your tree is deep it will be more efficient to use a singleton, which will cut down the lookup time.

You can also chose a closer tree node, it doesn't have to be the root element, it just has to be deep enough so that all objects that need to access it are nested in it, and the properties have to be declared in the root element of the particular qml file in order to get dynamic scoping.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!