Qt World Summit: Register Today!

Writing a QString value in a QFile plain-text object

  • I wonder how hard is to write a QString value to a plain-text file using Qt. It should be an easy task, but as far as I have been looking for it isn't.
    All the code I could find is related to const char * strings. By the way, I need to use a QTextStream global variable to save the strings. Any suggestion?

    I really appreciate any example to understand what is the right way to do this.


  • @xtingray

    I honestly haven't tried QFile directly but using QTextStream makes it pretty easy. Here is example code I use to save macro code which comes across as a QString:

    if( fileName.isEmpty()==false )
      QFile scriptFile(fileName);
      if( !scriptFile.open(QIODevice::WriteOnly) )
        QString msg = QString( tr("SaveCurrentMacro - Unable to save current script to file: %1") ).arg(fileName);
        Logger::GetLogger()->WriteToLog( msg );
        QMessageBox::critical(this, tr("Macro Editor"), msg, QMessageBox::Ok );
      // Save the script
      QTextStream outputStream(&scriptFile);
      QString code = m_MacroEditor->toPlainText();
      outputStream << code;
      SetCurrentMacroFile( fileName );
      SetMacroChanged( false );

  • You can open the file for writing and insert write QByteArrays to it via:
    QFile::write(const QByteArray & byteArray)

    Thus pick your favorite:
    QString::toUtf8() or QString::toLocal8bit().

Log in to reply