I have the following code:
QStringListModel* m=new QStringListModel(gc.get_lista_file());
ui->lista_immagini_listView->setModel(m);
where gc.get_lista_file()
returns a QStringList
object and lista_immagini_listView
is a QListView
.
I need to update my lista_immagini_listView
adding a string when I press a button, but if I add my new string to my QStringList
object it doesn't update my model (I read the QStringList
is passed by copy, so it isn't connected to the model). So, I have to update my QStringListModel
but in this way I have to update 2 object (QStringList
and QStringListModel
) and doesn't seem a good practice.
What is the best way (if exists) to resolve it?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With