qt - 在 .qml 文件中声明字符串

标签 qt qml qt5

我正在尝试在 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/

相关文章:

c++ - 如何使用正则表达式从QT C++中的字符串中获取子字符串值

c++ - QAbstractSpinBox - indexChanged 信号

qt - qml支持面向对象编程吗

c++ - 放大 QGraphicsView 时如何保持 QPen 像素宽度相同

c++ - 如何用QtCharts绘制非连续的时间序列轴?

c++ - 如何以位字节序将数字转换为字节数组

c++ - QT实时摄像机显示由于内存不足而崩溃

android - 当设备的(android)键盘处于 Activity 状态时移动弹出窗口

qt - 我如何更改 QML TextField 中的 placeholderText 颜色

webview - 从 webviews Javascript 调用 C++ 方法