6

以下是我添加的一个行类。它由代码调用,而不是由表调用,我希望它在添加新行时正确调用 dataChanged,虽然这不起作用,但表没有做任何事情。我究竟做错了什么?

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
}
4

1 回答 1

8

dataChanged仅适用于现有数据,您需要调用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
}

那应该行得通。可能你甚至不需要emit dataChanged

于 2011-05-14T11:08:30.113 回答