Domanda

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?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top