在.qml文件中声明字符串



我正试图在qml中创建一个varables文件,该文件声明了其他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

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

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

Global
 ├── qmldir
 └── Variables.qml

qmldir

singleton Variables 1.0 Variables.qml

变量.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
    }

在这个链接中,你会发现一个例子。

最新更新