質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top