How to update a QStringListModel?
QStringListModel
does not allow you to simply add a string (sadly). Simply updating the QStringList
does not work because the model stores a copy of the list.
There are basically two ways to get the desired behavior:
1. Reset:
This is the simple way. You just take the list from the model, add the string and reassign it:
QStringList list = m->stringList();
list.append("someString");
m->setStringList(list);
This method does work, but has one big disadvantage: The view will be reset. Any selections the user may have, sorting or the scroll-position will be lost, because the model gets reset.
2. Using the Model:
The second approach is the proper way of doing, but requires some more work. In this you use the functions of QAbstractItemModel
to first add a row, and then changing it's data:
if(m->insertRow(m->rowCount())) {
QModelIndex index = m->index(m->rowCount() - 1, 0);
m->setData(index, "someString");
}
This one does properly update the view and keeps it's state. However, this one gets more complicated if you want to insert multiple rows, or remove/move them.
My recommendation: Use the 2. Method, because the user experience is much better. Even if you use the list in multiple places, you can get the list after inserting the row using m->stringList()
.
You need to only use the string list provided by the QStringListModel
- don't keep a separate copy, use QStringListModel::stringList()
for reading only. To modify the list, use the model's methods: insertRows
, removeRows
and setData
instead of using QStringList
methods.