How to use QAbstractListModel

From Qt Wiki
Revision as of 22:21, 4 April 2017 by Dridk2 (talk | contribs) (Created page with "The following tutorial explains how to create a custom Qt model and use it inside a QTableView. We want to display a user list. First create a simple User class as follo...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The following tutorial explains how to create a custom Qt model and use it inside a QTableView.

We want to display a user list. First create a simple User class as follow :

class User 
{
  public : 
     User();
     User(const QString& firstname, const QString& lastname, const QDate& birthday);   
  private:
     QString mFirstname; 
     QString mLastName;
     QDate mBirthday;

}

We are now going to create a model based on QAbstractItemModel. A model is an interface between the view and the data. In the following example, data are a list of User.

class UserModel : public QAbstractItemModel 
{
   Q_OBJECT
  public : 
     UserModel(QObject * parent = 0);
     void rowCount(const QModelIndex& parent = QModelIndex()) const;
     void columnCount(const QModelIndex& parent = QModelIndex()) const;
     QVariant data(const QModelIndex &index, int role) const;
     void populate();

  private:
    QList<User> mDatas;

}


     void UserModel::rowCount(const QModelIndex& parent = QModelIndex()) const
    {
       return mDatas.size();
    }

     void UserModel::columnCount(const QModelIndex& parent = QModelIndex()) const
    {
       return 3;
    }

   QVariant UserModel::data(const QModelIndex &index, int role) const
   {
    if (!index.isValid())
        return QVariant();

    if ( role == Qt::DisplayRole)
    {
        if ( index.column() == 0)
            return mDatas[index.row()].firstname();

        if ( index.column() == 1)
            return mDatas[index.row()].lastname();

       if ( index.column() == 2)
            return mDatas[index.row()].birthday();
    }

    return QVariant();

}

   void UserModel::populate()
   {
         beginResetModel();
         mDatas.clear();
         mDatas.append(User("Charles","Darwin", QDate(1812,22,23));
         mDatas.append(User("Lars","Knoll,"QDate(1976,22,12));
         mDatas.append(User("Boby","Lapointe",QDate(1951,21,31));
         endResetModel();
   }

Now use your mode :

QTableView * view = new QTableView;
UserModel * model = new UserModel;
view->setModel(model);
model->populate()