Steve
Steve

Reputation: 4107

Setting Text from QRC in QML TextArea

I have a Qt Quick QML file with a TextArea that I would like have display text from a QRC resource. Other controls with images have a source member that can be set to load directly from a QRC QURL (see here) but TextArea must set the text directly. What is the most concise way in Qt 5.x to set the text value from a QRC resource? I would like

        TextArea
        {
            text: LoadResource("qrc://messages.txt")
        }

Another question here alludes to a simple process but the code is gone and now only shows how to use do it in C++.

Upvotes: 0

Views: 516

Answers (1)

Stephen Quan
Stephen Quan

Reputation: 26379

You can use XMLHttpRequest to access local file and embedded resources but it requires QML_XHR_ALLOW_FILE_READ environment variable set to 1, e.g.

    // in main.cpp
    qputenv("QML_XHR_ALLOW_FILE_READ", QString("1").toUtf8());
    // in qml
        let xhr = new XMLHttpRequest();
        xhr.open("GET", "messages.txt"); 
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== 4) return;
            if (xhr.status !== 0 && (xhr.status < 200 || xhr.status >= 400)) return;
            // handle xhr.responseText;
        }
        xhr.send();

In the following example I've refactored the XMLHttpRequest as a TextLoader component:

import QtQuick
import QtQuick.Controls
Page {
    Frame { 
        width: parent.width
        TextArea {
            width: parent.width
            wrapMode: Text.WrapAtWordBoundaryOrAnywhere
            TextLoader {
                url: "messages.txt"
            }
        }
    }
}

// TextLoader.qml
import QtQuick
Item {
    id: textLoader
    property var target: parent
    property string property: "text"
    property string url
    onUrlChanged: Qt.callLater(load)
    function load() {
        if (!url) return;
        let xhr = new XMLHttpRequest();
        xhr.open("GET", url); 
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== 4) return;
            if (xhr.status !== 0 && (xhr.status < 200 || xhr.status >= 400)) return;
            target[property] = xhr.responseText;
        }
        xhr.send();
    }
    Component.onCompleted: Qt.callLater(load)
}

// messages.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris scelerisque augue non magna consectetur pretium quis lobortis mi. Sed fermentum, turpis at molestie imperdiet, odio magna elementum libero, quis posuere lorem risus in libero. Nunc ullamcorper massa eget condimentum venenatis. Donec eget tempus leo, id gravida sem. Duis eget libero id lorem fringilla accumsan dictum sed purus. Pellentesque tristique velit at quam pharetra, in porta tortor hendrerit. In tristique imperdiet velit, ac hendrerit metus sagittis a. Fusce suscipit tellus volutpat, accumsan metus non, tempus sem.

You can Try it Online!

Upvotes: 2

Related Questions