Important: Please read the Qt Code of Conduct -

Adding rows to QAbstractTableModel

  • Hello,

    I have created a model such as:

    #include <QObject>
    #include <QAbstractTableModel>
    class ReactiveModelTable : public QAbstractTableModel
        ReactiveModelTable(QObject *parent);
        int rowCount(const QModelIndex &parent)const;
        int columnCount(const QModelIndex &parent)const;
        QVariant data (const QModelIndex &index, int role)const;
        int rows=0;
        int columns=5;


    #include "reactivemodeltable.h"
    ReactiveModelTable::ReactiveModelTable(QObject *parent):QAbstractTableModel (parent)
    int ReactiveModelTable::rowCount(const QModelIndex &parent) const
        return rows;
    int ReactiveModelTable::columnCount(const QModelIndex &parent) const
        return columns;
    QVariant ReactiveModelTable::data(const QModelIndex &index, int role) const
        return QVariant();

    Then in my file I start the model such as:
    modelo = new ReactiveModelTable(this);

    then I have created a button and I want it to add a row, I tried the following code:

    but it doesn't work...

    Any suggestion please?


  • Moderators

    Qt doesn't know the implementation of your model. For this to work you need to implement the virtual insertRows() method to actually insert the new item. In case of this simple model it would just do something like

    bool ReactiveModelTable::insertRows(int row, int count, const QModelIndex &parent)
       beginInsertRows(parent, row, row + count - 1);
       rows += count;
       return true;

  • @Chris-Kawa said in Adding rows to QAbstractTableModel:

    insertRows(int row, int count, const QModelIndex &parent)

    But I can't initialize it on my clicked button, I did the following code:

    void cmyclass::on_add_button_clicked()
        int a = modelo->rowCount(QModelIndex());

    It returns:
    error: non-const lvalue reference to type 'QModelIndex' cannot bind to a temporary of type 'QModelIndex'

  • Moderators

    @jss193 It means you forgot the const qualifier in the insertRows method. Make sure it looks exactly like this

    bool ReactiveModelTable::insertRows(int row, int count, const QModelIndex &parent) override;

    Use the override keyword when you override a virtual method. It will help you catch situations like this, and pay attention to consts. They are important.

Log in to reply