Hello,

In Qt examples, there are examples that usually go beyond my simple test program. I have a QListView in main windo. I don't use designer or Qt quick.

Why do I loose the itemName value? My program crashes after I add a new item to my model and thanks to debugging I see that I indeed have 3 items in my vector but there is a blank string rather than expected value for last item (the one I created by clicking on the button).

Thank you for pointing my learning coding errors.

Here is some shortened source code, I attach the whole source code to this post.

MyModel.h:
Qt Code:
  1. class MyModel : public QAbstractTableModel
  2. {
  3. Q_OBJECT
  4. public:
  5. MyModel(QObject *parent = 0);
  6. int rowCount(const QModelIndex &parent = QModelIndex()) const ;
  7. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  8. QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
  9.  
  10. void addItem(TestItem item);
  11. private:
  12. std::vector<TestItem*> m_items;
  13. public slots:
  14. void onButtonClicked();
  15. };
To copy to clipboard, switch view to plain text mode 

TestItem.h:
Qt Code:
  1. class TestItem {
  2.  
  3. public:
  4. TestItem();
  5. TestItem(QString itemName);
  6. QString getName() const;
  7. void setName(QString itemName);
  8.  
  9.  
  10. private :
  11. QString m_itemName;
  12. };
To copy to clipboard, switch view to plain text mode 

MyModel.cpp:
Qt Code:
  1. QVariant MyModel::data(const QModelIndex &index, int role) const
  2. {
  3. int row = index.row();
  4. int col = index.column();
  5. // generate a log message when this method gets called
  6. qDebug() << QString("row %1, col%2, role %3")
  7. .arg(row).arg(col).arg(role);
  8.  
  9.  
  10. if(role == Qt::DisplayRole){
  11. if (col == 0) return (*m_items[row]).getName();
  12.  
  13. return QString("Row%1, Column%2")
  14. .arg(row + 1)
  15. .arg(col +1);
  16. }
  17.  
  18. return QVariant();
  19. }
  20.  
  21. void MyModel::addItem(TestItem item)
  22. {
  23. int nbRows = m_items.size();
  24. beginInsertRows(QModelIndex(), nbRows, nbRows);
  25. m_items.push_back(&item);
  26. endInsertRows();
  27. }
  28.  
  29. void MyModel::onButtonClicked(){
  30. TestItem newItem("new element");
  31. addItem(newItem);
  32. }
To copy to clipboard, switch view to plain text mode 

QtListViewDemoQt4.zip