Save and load txt file
-
Hi, I'm writing a simple program with Qt 5.0 and I'd be interested, via a button, to save the written text of a text in a .Txt file in the same folder where there are all the program files.
Then, again using a button, I'd be interested to open a file manager window and choose here another text file which is opened in the text.
Sorry for the various repetition of the word text; cordial greetings.
This is the code:
@import QtQuick 2.0
import Ubuntu.Components 0.1
Rectangle {
width: 300
height: 300
color: "lightgray"TextArea { id:testo width: units.gu(37) height: units.gu(6) contentWidth: units.gu(30) contentHeight: units.gu(60) activeFocusOnPress : true } Column{ anchors.centerIn: parent spacing: parent.width/6 Button{ id: exitButton text: "load" } Button{ id:savebutton text:"save" onClicked:??????? } } }@
-
There is a pretty simple example here:
http://www.developer.nokia.com/Community/Wiki/Reading_and_writing_files_in_QML
It is Qt Quick 1 though so it will require a bit of adaptation.
-
Here is a quick and basic example for QtQuick2 - paths are hardcoded, since it is just an example:
The FileHelper custom QML element:
@class FileHelper : public QObject {
Q_OBJECT
public:
explicit FileHelper(QObject *parent = 0) : QObject(parent) {}public slots:
void writeFile(const QString &text) {
QFile file("h:/test.txt");
if (!file.open(QFile::WriteOnly | QFile::Text)) return;
QTextStream out(&file);
out << text;
file.close();
}QString readFile() { QFile file("h:/test.txt"); if (!file.open(QFile::ReadOnly | QFile::Text)) return ""; QTextStream in(&file); QString temp = in.readAll(); file.close(); return temp; }
};@
Register the element to the engine in main.cpp:
@#include <QtQuick>
int main(int argc, char *argv[]) {
...
qmlRegisterType<FileHelper>("FileHelpers", 1, 0, "FileHelper");
...
}@And last - the QML:
@import QtQuick 2.0
import FileHelpers 1.0Rectangle {
width: 360
height: 360FileHelper { id: helper } TextEdit { id: myText anchors.fill: parent text: "test" } Button { name: "Read file" anchors.left: parent.left anchors.bottom: parent.bottom onClicked: myText.text = helper.readFile() } Button { name: "Write file" anchors.right: parent.right anchors.bottom: parent.bottom onClicked: helper.writeFile(myText.text) }
}@