문제

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