QT4 QstringListModel in QListView

This is my first QT question - I'm generally a C # programmer, so forgive me for asking a stupid question for which I am sure there is a very simple answer that I just cannot find:

I want to add items to the list, for now let them say that these are strings. I have a QListView: UI->listView , QStringList and QStringListModel:

 stringList = new QStringList(); stringList->append("ABC"); stringList->append("123"); listModel = new QStringListModel(*stringList, NULL); ui->listView->setModel(listModel); stringList->append("xyz"); 

In this example, "ABC" and "123" in my list are compiled and deleted, but not "xyz". Why not? Do I need to redraw a ListView somehow? Did I do something wrong with NULL?

Thanks.

+6
source share
2 answers

You have changed the QStringList , you need to change the model:

 stringList->append("xyz"); listModel->setStringList(*stringList); 
+5
source

If you often need to change the list of strings and associate the views that need to be updated, you can consider eliminating the QStringList and first of all use the QStringListModel. You can add / remove data there using insertRows / removeRows and setData. This ensures that the views always reflect the model as you expected. It can be wrapped to prevent tedious work. Something like (unverified):

 class StringList : public QStringListModel { public: void append (const QString& string){ insertRows(rowCount(), 1); setData(index(rowCount()-1), string); } StringList& operator<<(const QString& string){ append(string); return *this; } }; 
+23
source

Source: https://habr.com/ru/post/886782/


All Articles