在多个QML文件中共享颜色值和其他只读值

CLi*_*own 1 qt qml qt-quick qt5 qtquick2

例如,我正在寻找一种在多个QML文件之间共享只读值的简单方法。可以说我有一个label元素:

        Label {
            id: titleLabel
            text: listView.currentItem ? listView.currentItem.text : "IDEAL Networks"
            font.pixelSize: 20
            elide: Label.ElideRight
            horizontalAlignment: Qt.AlignLeft
            verticalAlignment: Qt.AlignVCenter
            Layout.fillWidth: true
            color: red;
            padding: {
                left: 14
            }
        }
Run Code Online (Sandbox Code Playgroud)

colorpadding值需要在其他QML文件和同一文件的其他领域使用。

除了重新键入red和在多个位置14之外,还有一种方法可以创建包含这些值的共享库,从而使以后更容易进行全局更新?

*更新*

我已按照此处的说明进行操作:http : //doc.qt.io/qt-5/qtqml-modules-qmldir.html

但是,当导入自定义CustomStyles 1.0模块时,出现错误-未安装模块“ CustomStyles”。

//Style.qml with custom singleton type definition
pragma Singleton
import QtQuick 2.0

QtObject {
    property int textSize: 20
    property color textColor: "green"
}

// qmldir declaring the singleton type
module CustomStyles
singleton Style 1.0 Style.qml

// singleton type in use
import QtQuick 2.0
import CustomStyles 1.0

Text {
    font.pixelSize: Style.textSize
    color: Style.textColor
    text: "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

eyl*_*esc 5

解决方案是使用单例,在这种情况下,您必须正确导入它,并假设.qml位于同一qrc中,您只需执行以下操作:

.qrc

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        [...]
        <file>style/qmldir</file>
        <file>style/style.qml</file>
    </qresource>
</RCC>
Run Code Online (Sandbox Code Playgroud)

样式表

pragma Singleton
import QtQuick 2.0

QtObject {
   readonly  property int padding: 20
   readonly property color textColor: "green"
}
Run Code Online (Sandbox Code Playgroud)

qmldir

singleton Style 1.0 Style.qml
Run Code Online (Sandbox Code Playgroud)

main.qml

import QtQuick 2.0
import "style"

Text {
    font.pixelSize: Style.textSize
    color: Style.textColor
    text: "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

在以下链接中有一个示例