我正在尝试在 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
请告诉我是否有更好的方法来管理变量。我希望它们是全局的,这样它们就可以在多个框架中使用。谢谢
最佳答案
您必须使用单例,为此您必须创建一个文件夹,其中包含顶部带有“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
}
在此link你会找到一个例子。
关于qt - 在 .qml 文件中声明字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53288886/