PDA

View Full Version : Write the content of a QStringList to a QTextStream



graciano
8th August 2009, 17:14
Hi
In this code i have to write all the items of a QStringList into a text file:

QString fileName = QFileDialog::getSaveFileName(this);
if (fileName.isEmpty()){
//
}else{
QFile file(fileName);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, tr("Application"),
tr("Cannot write file %1:\n%2.")
.arg(fileName)
.arg(file.errorString()));
}else{
QTextStream out(&file);
//here
out << "i want to write the content of the QStringList x here";
file.close();
}
}

I read about using QVariant for this purpose!
Is this the right approach?
Can someone provide me with an example?

Thanks

john_god
8th August 2009, 17:41
I think your aproch is correct just do


out << x;

where x is your QStringList.

graciano
8th August 2009, 18:54
QTextStream out(&file);
//here
QStringList x;
x << "item1" << "item2" << "item3";
out << x;
leads to

/home/torrao/Desktop/qt/passwordCreator/mainwindow.cpp:233: error: no match for ‘operator<<’ in ‘out << x’
Only QString is found for this operator http://doc.trolltech.com/4.5/qtextstream.html
I could use a loop to access all indexes in the list .. but there must be a more sophisticated way ... i think :rolleyes:

graciano
8th August 2009, 19:08
This does it.


QTextStream out(&file);
//here
QStringList x;
x << "item1" << "item2" << "item3";
for ( QStringList::Iterator it = x.begin(); it != x.end(); ++it )
out << *it << "\n";


Now i guess i must do some reading about QVariant :o

john_god
9th August 2009, 01:04
if you use QDataStream instead of QTextStream it will work fine without the loop.
Do you have to use text files or could you use binary ones ?