the_learnist
the_learnist

Reputation: 69

How do i load a textfile to QListwidget and also save it back

How do i load a text file into QListWidget , such that each line in the textfile is an item in QListWidget,

and once i populate it, i also want to save all items of listwidget into a text file , such that each item of listwidget is in a line in the text file , to accomplish that i am attempting this

QString temp;
  for(int i=0; i< ui->mylistwidget->count();i++)
{
QListWidgetItem* item = ui->mylistwidget->item(i);
temp += item->text();
}
std::string total_script = temp.toStdString();

i got all the text of listwidget items in a string , what do i do next if i want to save it in a text file? and also how do i load text file and populate my qlistwidget with items ?

Upvotes: 1

Views: 697

Answers (1)

ypnos
ypnos

Reputation: 52317

Qt provides QFile and QSaveFile classes for convenient file input/output operations. QSaveFile is special in as it will only (over)write the destination file when you commit it. For both parsing and writing the file contents, you can use QTextStream, which exposes the file contents as a stream you can read from or write to, including conversion of various variable types.

For importing from file:

  1. Use a QFile to open the file
  2. Construct QTextStream with the file as argument
  3. Use QTextStream::readLine() in a while-loop to read lines and create items

For exporting to file:

  1. Use a QSaveFile, again construct QTextStream on the file
  2. In your loop, use QTextStream::operator<< to append the item text to the stream
  3. Call commit() on the file so it is written

Example without the loop:

QSaveFile fileOut(filename);
QTextStream out(&fileOut);
out << "Qt rocks!" << Qt::endl; // do this for every item
fileOut.commit()

Upvotes: 1

Related Questions