【问题标题】:declaring string in .qml files在 .qml 文件中声明字符串
【发布时间】:2018-11-13 20:19:49
【问题描述】:

我正在尝试在 qml 中创建一个变量文件,该文件声明了其他 qml 文件要使用的几个字符串。例如:这将是 Variables.qml

import QtQuick 2.0

Item {
    property var mystring: qsTr("hello world")
}

我想在另一个文件 tab1.ui.qml 中引用它

import QtQuick 2.4
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import "."

Item {
    Rectangle {
        id: rectangle
        color: "#3e1edd"
        anchors.fill: parent
        Text {
                id: text6
                anchors.fill: parent
                font.pixelSize: 12
                text: Variables.mystring
                visible: true
        }
    }
 }

这给出了一个错误:无法将 [undefined] 分配给 QString

请告诉我是否有更好的方法来管理变量。我希望它们是全局的,以便它们可以在多个框架中使用。谢谢

【问题讨论】:

    标签: qt qml qt5


    【解决方案1】:

    您必须使用单例,为此您必须创建一个文件夹,其中包含顶部带有“pragma Singleton”的 .qml 和指示文件的 qmldir:

    Global
     ├── qmldir
     └── Variables.qml
    

    qmldir

    singleton Variables 1.0 Variables.qml
    

    Variables.qml

    pragma Singleton
    import QtQuick 2.0
    
    QtObject {
        property var mystring1: qsTr("hello world1")
        property var mystring2: qsTr("hello world2")
    }
    

    那你必须按如下方式导入和使用:

    // others imports
    import "Global"
    
    // ...
    
        Text{
            // ...
            text: Variables.mystring1
        }
    

    在这个link 你会找到一个例子。

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多