I’m trying to replace a text in my .qml file with a json data.
In my .qml file I have the following:
Text
{
**text: qsTr("J1-25")**
anchors.right: tc1.left
anchors.rightMargin: 20
anchors.verticalCenter: tc1.verticalCenter
color: "white"
font.pointSize: 10
}
I created the .json file with the following info:
{
"pwm":
[
{"id": "1", "pin": "J2-21"},
{"id": "2", "pin": "J2-22"},
{"id": "3", "pin": "J2-23"},
{"id": "4", "pin": "J2-24"},
{"id": "5", "pin": "J2-25"},
{"id": "6", "pin": "J2-26"}
],
"truecurrent":
[
{"id": "1", "pin": "J1-21"},
{"id": "2", "pin": "J1-22"},
{"id": "3", "pin": "J1-23"},
{"id": "4", "pin": "J1-24"},
**{"id": "5", "pin": "J1-25"},**
{"id": "6", "pin": "J1-26"}
]
}
How do I replace the text in my .qml with true current data in .json file (both in bold)?
JsonLoader {
id: jsonLoader
filePath: ":/example.json"
}
Text
{
text: jsonLoader.jsonObject["truecurrent"]["5"] //text: qsTr("J1-25")
anchors.right: tc1.left
anchors.rightMargin: 20
anchors.verticalCenter: tc1.verticalCenter
color: "white"
font.pointSize: 10
}
2
Answers
You can use the JavaScript JSON parser. Here an example with a fixed string. You can load the string from file.
You can use
XMLHttpRequest
to load both HTTP and FILE resources. In the following, if I declaredata.json
and place it in the same folder as my QML source file, I can useXMLHttpRequest
with a relative reference to pick it up. You will be required to set"QML_XHR_ALLOW_FILE_READ" environment variable to "1" since without it, access to local files will be prevented in the latest versions of Qt.
Using this technique, you can create your own
JsonLoader
object as follows:You can Try it Online!