PDA

View Full Version : How to save and load listView row data?



twentynineteen
25th July 2019, 05:48
I made a listView with add and remove row functions by following this tutorial https://www.bogotobogo.com/Qt/Qt5_QListView_QStringListModel_ModelView_MVC.php but without the QComboBox.

I binded the QStringListModel with an empty QStringList from another .cpp file.

Whenever I close the app after adding rows, the listView empties. How can I save the ListView rows so that they load when I open the app again?

d_stranz
26th July 2019, 00:46
You could try using QSettings or you could invent your own format to store the list in a file in a known location. You could load it in the constructor for your main window or for your list window, and you can choose to save it any time the list changes or only when the app closes.

twentynineteen
26th July 2019, 05:48
After some research, I tried the following to save the listView into a text file:


QTextStream stream(&file);
for (int i = 0; i < stringList.size(); ++i)
stream << stringList.at(i) << '\n';

None of the rows were saved.
According to this https://stackoverflow.com/questions/37412712/how-to-update-a-qstringlistmodel , apparently it's because QStringListModel only stores a copy of the stringList.

anda_skoa
26th July 2019, 08:14
None of the rows were saved.

Was the loop executed as many times as you expected?



According to this https://stackoverflow.com/questions/37412712/how-to-update-a-qstringlistmodel , apparently it's because QStringListModel only stores a copy of the stringList.

What do you mean with "only". A copy is obviously independent of anything else, so once the model gets the data it will hold on to it.
So even if you modify the original list variable, it will still have all the data you added to it.

Cheers,
_

d_stranz
26th July 2019, 17:44
None of the rows were saved.

Further to anda_skoa's reply, where is the "stringList" variable you are trying to save defined? Is it the same one you use to load the QStringListModel? Did you retrieve it from the model (using QStringListModel::stringList()) prior to executing this code?

I suspect that if your file is empty, it is because you are serializing an empty string list and not the one held by your model.