2

I'm trying to implement a model/view architecture in my program but the view isn't updated after changing the model, though I think it automatically should be.

Here's a simplified version of my code:

QStringListModel *model = new QStringListModel;
QListView *view = new QListView;

view->setModel(model);

QStringList list;
list << "a" << "b" << "c";

model->setStringList(list);
model->stringList() << "d";

Problem is, my view only contains a, b and c. But not d. Why? I thought the view would automatically be updated after changing the model, but it doesn't seem to be the case. Dou you have an idea?

RAM
  • 2,257
  • 2
  • 19
  • 41

1 Answers1

2

The problem is the last line. model->stringList() returns a copy of the QStringList used as the model, so you only modify the copy, the one used for the model remains unchanged.

Use something like this:

QStringList list = model->stringList();
list << "d";
model->setStringList(list);

That will work, although setStringList() will cause a complete, potentially expensive model reset. However, there seems to be no way around that with QStringListModel.

Thomas McGuire
  • 5,308
  • 26
  • 45
  • Thanks, it works. But as you said, it's not optimized because of the entire model reset. Isn't there any better alternative? –  Jun 28 '13 at 19:03
  • A better alternative is to not use QStringList, but instead write your own subclass of QAbstractListModel. In there, you can then use beginInsertRows() and endInsertRows() to add new items without a complete model reset. – Thomas McGuire Jun 28 '13 at 19:05
  • 1
    You can also use `QStandardItemModel`. It's simple and efficient enough. – Pavel Strakhov Jun 28 '13 at 19:06