Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'm sure there's a very simple answer, which I just can't seem to find:

I want to add items to a list, for the moment let's say they're strings. I have a QListView: UI->listView, a QStringList, and a QStringListModel:

stringList = new QStringList();
stringList->append("ABC");
stringList->append("123");

listModel = new QStringListModel(*stringList, NULL);
ui->listView->setModel(listModel);

stringList->append("xyz");

This example compiles and disaplys "ABC" and "123" in my list, but not "xyz". Why not? Do I need to repaint the listView somehow? Have I done something wrong with the NULL?

Thanks.

like image 648
Ozzah Avatar asked Apr 27 '11 09:04

Ozzah


2 Answers

If you frequently need to modify the string list and have connected views that need to be updated, you could consider doing away with the QStringList in the first place and solely using the QStringListModel. You can add/remove data there using insertRows/removeRows and setData. This ensures the views always reflect the model in the way you would expect. This could be wrapped to prevent tedious work. Something like (untested):

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;
  }
};
like image 113
Adversus Avatar answered Nov 15 '22 15:11

Adversus


You've modified the QStringList, you need to modify the model:

stringList->append("xyz");
listModel->setStringList(*stringList);
like image 39
Donotalo Avatar answered Nov 15 '22 14:11

Donotalo