How d 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 ?
-
Hi and welcome to the forums.
You could do like this using QFile and TextStream
// save QFile file("e:/test.txt"); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { // bind it QTextStream stream(&file); for (int i = 0; i < ui->mylistwidget->count(); i++) { QListWidgetItem *item = ui->mylistwidget->item(i); stream << item->text() << '\n'; } file.close(); } ui->mylistwidget->clear(); // load { QFile file("e:/test.txt"); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { // bind it QTextStream in(&file); while(!in.atEnd()) { QString line = in.readLine(); ui->mylistwidget->addItem(line); } file.close(); } }
-
Yes sure, use class QFileDialog, here is the documentation to it, so you can see all the functions and what they do. I would also really recommend using qt documentation, its a cool thing:)
QFileDialog: https://doc.qt.io/qt-5/qfiledialog.htmlQString fileName = QFileDialog::getOpenFileName(this, "Please, chose a file to open"); QFile file(fileName); // this creates a QFile object of our selected file
This code gets you the name of the file you have chosen in the file dialog.
Now if you want to save the file also via file dialog, then call:
QString fileName = QFileDialog::getSaveFileName(this, "Please, chose where to save the file"); QFile file(fileName); // this creates a QFile object of our selected file
"This is a convenience static function that will return a file name selected by the user. The file does not have to exist." as the qt documentation says.
Hope it will help)
Have fun programming ;)