We know that in QML applications, sometimes we need to read and write some files, but in our QML language there is no API interface for us to do (although there are API interfaces to store settings files, etc.). So how do we do this thing? We can do this with the QT C + + method.
1) Create a simple template application
We use the Ubuntu SDK template to create one of the simplest applications:
We chose "
QML App with C + + plugin"Template to do our application.
2) Add file read/write files to the project we add the following C + + "FileIO class to our backend plugin:
#ifndef fileio_h#define fileio_h#include <QObject> #include <QTextCodec> #include <qdebug>class Fileio:public qobject{Q_objectpublic:q_property (QString source READ source WRITE Set Source NOTIFY sourcechanged) Explicit FileIO (Qobject *parent = 0); Q_invokable QString read (); q_invokable bool Write (const qstring& data); QString Source () {return msource;}; Public slots:void SetSource (const qstring& source) {Msource = source;}; Signals:void sourcechanged (const qstring& source); void error (const qstring& msg);P rivate:qstring getenv (const QString envvarname) const;private:qstring Msource; QString DataPath;}; Inline QString Gbk2utf8 (const QString &instr) {qlist<qbytearray> codecs = Qtextcodec::availablecodecs (); for (int i = 0; i < codecs.length (); i + +) {//Qdebug () << "codec:" + qtextcodec::codecformib (1015)-> ; Tounicode (codecs.at (i)); Qdebug () << "codec:" << qstring::fromlocal8bit (codecs.at (i)); } Qtextcodec *GBK = Qtextcodec::codecforname ("GBK"); Qtextcodec::setcodecforlocale (Qtextcodec::codecforlocale ());//Qtextcodec *utf8 = Qtextcodec::codecforname ("UTF-8" ); QString g2u = Gbk->tounicode (Gbk->fromunicode (INSTR)); GBK convert UTF8 return g2u;} #endif//Fileio_h
#include "fileio.h" #include <QFile> #include <QTextStream> #include <QDebug> #include <qfileinfo > #include <qtextcodec>fileio::fileio (qobject *parent): Qobject (parent) {datapath = getenv ("TMPDIR") + "/"; Qdebug () << "DataPath:" + datapath;} QString Fileio::read () {qdebug () << "Reading ....!"; if (Msource.isempty ()) {Emit error ("Source is empty"); return QString (); } QFile file (DataPath + msource); Qfileinfo FileInfo (File.filename ()); Qdebug () << "file path:" << Fileinfo.absolutefilepath (); QString filecontent; if (File.Open (qiodevice::readonly)) {QString line; Qtextcodec *GBK = Qtextcodec::codecforname ("GBK"); Qtextstream T (&file); T.setcodec (GBK); do {line = T.readline (); Filecontent + = line; } while (!line.isnull ()); File.close (); return filecontent; } else {Emit error ("Unable to open the file "); return QString (); }}bool fileio::write (const qstring& data) {qdebug () << "writing ..."; if (Msource.isempty ()) return false; QFile file (DataPath + msource); Qfileinfo FileInfo (File.filename ()); Qdebug () << "file path:" << Fileinfo.absolutefilepath (); if (!file.open (qfile::writeonly | Qfile::truncate)) return false; Qtextstream out (&file); Out << data; File.close (); return true;} QString fileio::getenv (const QString envvarname) const{qbytearray result = Qgetenv (Envvarname.tostdstring (). C_STR ()); QString output = qstring::fromlocal8bit (result); Qdebug () << envvarname << "value is:" << output; return output;}
This class is a file that can be read and written to the file address we specify. Note that we used getenv to get a directory of files that can be read and written. Ubuntu apps are not able to open any file directory for read and write. Refer to the article "Ubuntu OS Application Runtime enviroment" to get more information. In this routine, we specify that the file is encoded as GBK. You can not specify or specify the encoding that you want.
In the CMakeLists.txt of backend, add:
Modules/readfileqml/fileio.cpp
At the same time, add in Backend.cpp:
void Backendplugin::registertypes (const char *uri) { Q_assert (uri = = qlatin1string ("readfileqml")); Qmlregistertype<mytype> (URI, 1, 0, "MyType"); Qmlregistertype<fileio> (URI, 1, 0, "FileIO"); Added line}
This completes the design of our plugin.
3) Call in the application in order to test our plugin, we modify our READFILEQML.QML file as follows:
Import QtQuick 2.0import ubuntu.components 1.1import readfileqml 1.0/*! \brief MainView with Tabs element. First Tab have a single Label and second Tab have a single Toolbaraction.*/mainview {//ObjectName for Functio NAL testing purposes (AUTOPILOT-QT5) ObjectName: "MainView"//note! ApplicationName needs to match the "name" field of the click Manifest ApplicationName: "Readfileqml.liu-xiao-guo"/* The enables the application to change orientation when the device is rotated. The default is False. *///automaticorientation:true//Removes the old toolbar and enables new features of the new header. Usedeprecatedtoolbar:false width:units.gu (height:units.gu) page {title:i18n.tr ("Read File QML" ) Text {id:mytext Anchors.top:parent.top anchors.left:parent.left a Nchors.right:parent.right Anchors.bottom:button.top WrapmodE:text.wrap} Button {Id:button anchors.left:parent.left anchors.right: Parent.right Anchors.bottom:parent.bottom Height:units.gu (5) Text: "Reload file" OnClicked: {console.log ("button is clicked!"); Reload the file Mytext.text = Myfile.read (); }} FileIO {Id:myfile source: "Good.txt" OnError:console.log (msg) } component.oncompleted: {Console.log ("WRITE:" + myfile.write ("This is really cool!"); Console.log ("Source:" + Myfile.source); Mytext.text = Myfile.read (); } }}
Here, we define:
FileIO { id:myfile Source: "Good.txt" onError:console.log (msg) }
We can use it to read and write files to our file "Good.txt". Note the address of the Good.txt file.
All source code at address: Git clone https://gitcafe.com/ubuntu/readfileqml.git
How to read and write files in QML applications