File stream



  • How to write text in a file as user input? I want this in form system.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Do you mean write in a QFile the content of e.g. a QTextEdit ?



  • Yes, exactly.



  • When should the content be saved to a file?

    • When a "Save" button is pressed?
    • Always when the text is changed?
    • automatically every X seconds?


  • Regardless of how your save is kicked off you can use this code to save the contents. Then if you want different kick off triggers you can have those call the function.

    bool save(const QTextEdit *te, const QString &filename)
    {
        QFile f(filename);
    
        // open the file .. WARNING: this will overwrite any existing
        // file.  Be careful here!
        if (!f.open(filename, QIODevice::WriteOnly | QIODevice::Text))
            return false;
    
        // write the plain text data from the control, use toHtml() if
        // you want HTML data
        f.write(te->toPlainText(), te->toPlainText().size());
    
        // close the file
        f.close();
    
        return true;
    }
    

    Typed out of my head so may have issues, should be easy to fix when compiled if there are any typos/wrong function usage. :)

    Edit: as a better way you could change the function to take a const QString &data instead of the textedit. That is how I would do it. Then you can call it with something like save(myTextEdit->toPlainText(), "filename");.

    So you would need to change the function to look like this if you want that method:

    bool save(const QString &data, const QString &filename)
    {
        QFile f(filename);
    
        // open the file .. WARNING: this will overwrite any existing
        // file.  Be careful here!
        if (!f.open(QIODevice::WriteOnly | QIODevice::Text))
            return false;
    
        // write the plain text data from the control, use toHtml() if
        // you want HTML data
        f.write(data, data.size());
    
        // close the file
        f.close();
    
        return true;
    }
    


  • Thankyou i will try


Log in to reply
 

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