# 本地文件

也可以使用XMLHttpRequest加载本地XML/JSON文件。 例如,可以使用以下方式加载名为colors.json的本地文件:

xhr.open("GET", "colors.json")

使用它来读取颜色表并将其显示为网格。 无法从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

默认情况下,QML引擎禁用对本地文件使用GET。 要解除此限制,可以将环境变量QML_XHR_ALLOW_FILE_READ设置为1

QML_XHR_ALLOW_FILE_READ=1 qml localfiles.qml

问题在于,当允许QML应用程序通过XMLHttpRequest(即XHR)读取本地文件时,这会打开整个文件系统进行读取,这是一个潜在的安全问题。 只有设置了环境变量,Qt才允许读取本地文件,因此这是一个特意的决定。

除了使用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' }
    }
}

使用XmlListModel只能读取XML文件而不能读取JSON文件。

最后更新: 1/20/2022, 6:26:40 PM