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 {
                activeFocusOnPress : true
           anchors.centerIn: parent
           spacing: parent.width/6
               id: exitButton
               text: "load"

  • Just create a QObject derived class, add a read and write slot and implement using QFile, register the class to QML, instantiate it in QML and connect it to the signals of your buttons.

  • Thanks for your reply can you give me an example, please

  • There is a pretty simple example here:

    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 {
    explicit FileHelper(QObject *parent = 0) : QObject(parent) {}

    public slots:
    void writeFile(const QString &text) {
    QFile file("h:/test.txt");
    if (! | QFile::Text)) return;
    QTextStream out(&file);
    out << text;

    QString readFile&#40;&#41; {
        QFile file("h:/test.txt"&#41;;
        if (! | QFile::Text&#41;&#41; return "";
        QTextStream in(&file);
        QString temp = in.readAll();
        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.0

    Rectangle {
    width: 360
    height: 360

    FileHelper {
        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(&#41;
    Button {
        name: "Write file"
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        onClicked: helper.writeFile(myText.text&#41;


  • Thank you very much for the answer.
    When i start my program the terminal gives me this error:
    @2 module "FileHelpers" is not installed@

    How can I fix?

  • Did you register the class, i.e. the second step of my example?

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.