How to load contents of file from resources for TextArea 'text' property?
-
Hello,
I'd like to read the contents of a file (from application resources) as the
textproperty of aTextArea. What is the best way to do this? I haven't found anything in the docs or by searching that help.I can imagine a couple possible ways...
text: readFile('qrc:/myapp/file.html')Component.onCompleted: { text = readFile('qrc:/myapp/file.html'); }
But how to implement
readFile()? Is there a javascript function to read files from resources? XMLHtttpRequest??- This text is not dynamic, so some way to tell the QML parser to inline the file contents in the QML string would work too.
Is there documentation on what parts of the Javascript/Browser/Etc API are available in QML? I have discovered by trial and error what parts of the DOM/Document/Element/Node APIs are implemented, but it would be nice if there was API documentation. Or maybe a few files in the Qt source code that can be used for reference?
(This TextArea is inside a ScrollView in a Dialog; it's purpose is just to show some documentation/information to the user. Is there another QML component I'm not aware of that is better suited to this?)
Thanks!
-
I'd also like to eventually have translations for my text file as well, if that is a consideration on the best way to do this.
-
OK I did come up with a solution for now, but don't know if it's the best one:
I just added a
QMLUtilC++ class (derived fromQObject) with a methodQ_INVOKABLE QString readFile(const QString& path);. This just usesQFile::readAll()to read the file and return the contents as aQString.I then passed an instance of this to QML engine in
main()with:QMLUtil qmlUtil;
QQmlApplicationEngine.rootContext()->setContextProperty("QMLUtil", &qmlUtil);and can use it in my
TextArea:text: visible ? QMLUtil.readFile(":myapp/file.html") : ""(Note need to use
QFile's file path syntax with:prefix instead ofqrc:/.)Pretty simple (doesn't do much with errors, just throws an exception or returns empty string), and would probably have some issues if the file were very large, but seems to work for now. If there was a pure Javascript solution, that would be better for some of my other QML/JS-only projects however.
Let me know if you have other ideas on how to do this!
Thanks