Model/View Example

Model-View Patterns with Qt | | QML Model-View Example


In this example we are going to write a simple model interface.

For simplicity we assume that our model is a list of names, which is stored in a std::vector<QString> container. Then the model is setup by deriving from the abstract base class QAbstractListModel (which is a convenience class derived from QAbstractItemModel) and implementing its pure virtual (= abstract) methods rowCount, columnCount and data:

class Model: public QAbstractListModel


   // ctor
   Model(QObject *parent=NULL): QAbstractListModel(parent) {}

   // virtual functions of the abstract model to be implemented:

   int rowCount(const QModelIndex &parent = QModelIndex()) const {return(data_.size());}
   int columnCount(const QModelIndex &parent = QModelIndex()) const {return(1);}

   QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
      if (role == Qt::DisplayRole)
      else if (role == Qt::BackgroundRole)



   std::vector<QString> data_;

Whenever the underlying data changes (as by the accessors of the model class), any view that uses the model needs to be notified about that. This is done via the signal dataChanged with two parameters, the left-top and right-bottom index of the item range:

   // accessors of the data model:

   void add(QString s)

      QModelIndex index = createIndex(data_.size()-1, 0);
      emit dataChanged(index, index);

Now we create a view and assign a model to it:

   Model m;
   QListView v;


For a model that is able to be edited, we also need to override the setData method

bool Model::setData(const QModelIndex &index, const QVariant &value, int role)
   if (role == Qt::EditRole)
      data_[index.row()] = value.toString();
      emit dataChanged(index, index);


and specify which items are editable via the flags method:

   Qt::ItemFlags flags(const QModelIndex &index) const
      return(Qt::ItemIsEnabled | Qt::ItemIsEditable);

Full source code:

svn co svn://schorsch.efi.fh-nuernberg.de/qt-android/modelview

Model-View Patterns with Qt | | QML Model-View Example