代码之家  ›  专栏  ›  技术社区  ›  CLiown

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

  •  1
  • CLiown  · 技术社区  · 7 年前

    例如,我正在寻找一种跨多个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
                }
            }
    

    这个 color padding 值需要在其他QML文件和同一文件的其他区域中使用。

    而不是重新键入 red 14在多个位置,有没有办法创建一个包含这些值的共享库,以便于以后进行全局更新?

    *更新*

    我遵循了这里的说明: http://doc.qt.io/qt-5/qtqml-modules-qmldir.html

    但是,当我导入自定义 CustomStyles 1.0 模块I出现错误-未安装模块“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"
    }
    
    2 回复  |  直到 5 年前
        1
  •  5
  •   Mohammad Kanan    7 年前

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

    .qrc

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

    风格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
    

    主要的qml公司

    import QtQuick 2.0
    import "style"
    
    Text {
        font.pixelSize: Style.textSize
        color: Style.textColor
        text: "Hello World"
    }
    

    在以下内容中 link 有一个例子

        2
  •  1
  •   dtech    7 年前

    如果对象树不太深,则只需在的根对象中声明属性即可 main.qml ,这将使它们可以通过动态作用域从所有qml文件中解析,只要您注意不要使用同名的本地属性对它们进行阴影。

    如果您的树很深,那么使用单例将更有效,这将缩短查找时间。

    您还可以选择一个更接近的树节点,它不必是根元素,只需足够深,以便所有需要访问它的对象都嵌套在其中,并且必须在特定qml文件的根元素中声明属性,以便获得动态范围。