0

TreeView Shows my data not correctly. What is wrong?

Here is the function of adding a child

bool TreeModel::addChild(const QVariant &data, const QModelIndex &parent)
{
    Task *parentTask;
    if (!parent.isValid()){

        qDebug() << "addChild() - parent is not valid";
        parentTask = rootItem;
    }
    else
        parentTask = static_cast<Task*>(parent.internalPointer());

    Task *childTask = new Task(data, parentTask);
    qDebug() << QString::number((int)childTask);///

    int childCount = childTask->childCount();
    emit beginInsertRows(parent, childCount, childCount);
    parentTask->appendChild(childTask);

    emit endInsertRows();
    //emit dataChanged(parent, parent);

    return true;

}

In some situations calling this function from QML makes a mess with Indexes in QML. It start show wrong items or invalid items, especially when Parent has tasks with children (2 levels tree). What is wrong?

Coaxial
  • 133
  • 1
  • 10

1 Answers1

1

You're indicating the wrong number of children to the model's users.

Instead of int childCount = childTask->childCount();, you should have

int childCount = parentTask->childCount();

Since this is a structural change only, you should never emit the dataChanged signal. The parent's data has not changed. Its structure has. Qt's models discriminate between structural and data changes. The begin.../end... methods indicate structural changes. The only place you should be emitting dataChanged is from a location that has the effects of calling Model::setData on an existing item. See this answer, for example, for details.

Community
  • 1
  • 1
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313