2

Shown below is the my custom table model. I am trying to use that tablemodel together with a QTableView. If the method append of the table model is called I would expect the table view to update its contents. But it doesn't and I don't know why. If however I use that same table model together with a QListView, everything works fine, i.e. the list view does update its contents, when append of the table model gets called. Is there anything special I need to do in case of the QTableView?

class MyModel : public QAbstractTableModel
{
public:

    MyModel(QObject* parent=NULL) : QAbstractTableModel(parent) {}

    int rowCount(const QModelIndex &parent = QModelIndex()) const {
        return mData.size();
    }

    int columnCount(const QModelIndex &parent = QModelIndex()) const {
        return 2;
    }

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {
        if (!index.isValid()) {
            return QVariant();
        }

        if (role == Qt::DisplayRole) {
            if (index.column()==0) {
                return QVariant(QString::fromStdString(getFirst(index.row())));
            }
            if (index.column()==1) {
                return QVariant(QString::fromStdString(getSecond(index.row())));
            }
        }

        return QVariant();
    }

    void append(std::string const& first, std::string const& second) {
        mData.push_back(std::make_pair(first, second));

        emit dataChanged(index(mData.size()-1, 0), index(mData.size()-1, 1));
    }

    std::string const& getFirst(int i) const {
        return mData[i].first;
    }

    std::string const& getSecond(int i) const {
        return mData[i].second;
    }

protected:

    std::vector<std::pair<std::string, std::string> > mData;
};
1
  • call layoutChanged instead Commented Feb 18, 2024 at 12:08

1 Answer 1

4

As you're inserting a new row instead of changing existing data, you should use beginInsertRows and endInsertRows instead:

void append(std::string const& first, std::string const& second) {
    int row = mData.size();
    beginInsertRows( QModelIndex(), row, row );

    mData.push_back(std::make_pair(first, second));

    endInsertRows();
}

See if that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

This helped me. Do you have a link to the documentation where you found this answer?
Usage of beginInsertRows/endInsert rows can be found in the Qt documentation for the QAbstractItemModel class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.