Qt World Summit: Submit your Presentation

QTreeView not refresh correctly

  • Hi all,

    In my application, I have a tree hierarchical structure FooTree that contains Foo* objects.
    Each Foo object knows how many children it has and also its index in its parent's children table.

    Now I'd like to display the FooTree in a QTreeView.
    I've reimplemented my own QAbstractItemModel where each QModelIndex owns a Foo* (based on doc from http://doc.qt.io/qt-5/modelview.html)
    For example, rowCount() and index() looks like this :

    int FooModel::rowCount(QModelIndex & parent) int
    	return static_cast<Foo*>(parent.internalPointer())->GetNumberOfChild();
    QModelIndex FooModel::index(int row,int column,const QModelIndex &parent) const
    	Foo* FooParent=NULL;
    		FooParent = m_Root;
    		FooParent = static_cast<Foo*>(parent.internalPointer());
    	Foo* FooChild = NULL;
    	if(FooParent )
    		int nbChildren = FooParent->GetChildrenNumber();
    		if( row >= 0 && row < nbChildren)
    			FooChild = FooParent->GetChild(row);
    		indexToReturn=createIndex( row, column, FooChild);
    	return indexToReturn;

    When I launch my QTreeView, it's ok, the view displays the existing FooTree correctly.

    My problem is when I append Foo* Child to an existing Foo* Parent in my FooTree, I can't have the view to refresh correctly.

    For the moment, once the Foo* has been added I call this method on the model :

    void FooModel::FooHasBeenAdded( Foo* foo)
    	QModelIndex parentIndex = IndexOf( foo->GetParent());	// Custom func to retrieve the index of a Foo*
    	emit dataChanged( parentIndex, parentIndex);

    I would expect that emitting dataChanged(parentIndex, parentIndex) would re-create all the indices under parentIndex (because rowCount(parentIndex) has changed) and then notify the view but it doesn't work.

    Any ideas ? Is there something wrong with my code ?

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You should also call the appropriate beginInsertRows and endInsertRows when you add data to your structure. That will trigger the proper update for the views

  • @SGaist Thanks for your advise, it works like well now.