Local files
本地文件
Is it also possible to load local (XML/JSON) files using the XMLHttpRequest. For example a local file named “colors.json” can be loaded using:
也可以使用XMLHttpRequest加载本地(XML/JSON)文件。例如,可以使用以下方法加载名为“colors.json”的本地文件:
xhr.open("GET", "colors.json")
We use this to read a color table and display it as a grid. It is not possible to modify the file from the Qt Quick side. To store data back to the source we would need a small REST based HTTP server or a native Qt Quick extension for file access.
我们使用它来读取颜色表并将其显示为网格。无法从Qt Quick端修改文件。为了将数据存储回源,我们需要一个小型的基于REST的HTTP服务器或用于文件访问的本地Qt Quick扩展。
import QtQuick
Rectangle {
width: 360
height: 360
color: '#000'
GridView {
id: view
anchors.fill: parent
cellWidth: width / 4
cellHeight: cellWidth
delegate: Rectangle {
required property var modelData
width: view.cellWidth
height: view.cellHeight
color: modelData.value
}
}
function request() {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
print('HEADERS_RECEIVED')
} else if(xhr.readyState === XMLHttpRequest.DONE) {
print('DONE')
const response = JSON.parse(xhr.responseText.toString())
view.model = response.colors
}
}
xhr.open("GET", "colors.json")
xhr.send()
}
Component.onCompleted: {
request()
}
}
TIP
注
By default, using GET on a local file is disabled by the QML engine. To overcome this limitation, you can set the
QML_XHR_ALLOW_FILE_READ
environment variable to1
:默认情况下,QML引擎禁用对本地文件使用GET。要克服此限制,可以将QML_XHR_ALLOW_FILE_READ环境变量设置为1:
QML_XHR_ALLOW_FILE_READ=1 qml localfiles.qml
The issue is when allowing a QML application to read local files through an
XMLHttpRequest
, henceXHR
, this opens up the entire file system for reading, which is a potential security issue. Qt will allow you to read local files only if the environment variable is set, so that this is a concious decision.问题是,当允许QML应用程序通过XMLHttpRequest读取本地文件时,这会打开整个文件系统进行读取,这是一个潜在的安全问题。Qt将允许您仅在设置了环境变量的情况下读取本地文件,因此这是一个简洁的决定。
Instead of using the XMLHttpRequest
it is also possible to use the XmlListModel to access local files.
除了使用XMLHttpRequest,还可以使用XmlListModel访问本地文件。
import QtQuick
import QtQml.XmlListModel
Rectangle {
width: 360
height: 360
color: '#000'
GridView {
id: view
anchors.fill: parent
cellWidth: width / 4
cellHeight: cellWidth
model: xmlModel
delegate: Rectangle {
id: delegate
required property var model
width: view.cellWidth
height: view.cellHeight
color: model.value
Text {
anchors.centerIn: parent
text: delegate.model.name
}
}
}
XmlListModel {
id: xmlModel
source: "colors.xml"
query: "/colors/color"
XmlListModelRole { name: 'name'; elementName: 'name' }
XmlListModelRole { name: 'value'; elementName: 'value' }
}
}
With the XmlListModel it is only possible to read XML files and not JSON files.
使用XmlListModel,只能读取XML文件,而不能读取JSON文件。
示例源码下载