How do I call dataChanged

Will03uk picture Will03uk · May 14, 2011 · Viewed 7.8k times · Source

The following is my add a row class. It is called by the code, not the table and I want it to properly call dataChanged when a new row is added, although this isn't working, the table doesn't do anything. What am I doing wrong?

void MyModel::add(const Person& p)
{
    people.push_back(p);

    QModelIndex top = createIndex(people.count() - 1, 0, 0);
    QModelIndex bottom = createIndex(people.count() - 1, 3, 0);

    emit dataChanged(top, bottom); // emit layoutChanged() if headers changed
}

Answer

pure cuteness picture pure cuteness · May 14, 2011

dataChanged works only on existing data, you need to call beginInsertRows() / endInsertRows()

void MyModel::add(const Person& p)
{
    beginInsertRows(QModelIndex(), people.count(), people.count());
    people.push_back(p);
    endInsertRows();

    QModelIndex top = createIndex(people.count() - 1, 0, 0);
    QModelIndex bottom = createIndex(people.count() - 1, 3, 0);

    emit dataChanged(top, bottom); // emit layoutChanged() if headers changed
}

That should work. May be you don't even need to emit dataChanged