Search code examples
qtqtreeviewqabstractitemmodel

How to refresh TreeModel in Qt?


I have a TreeModel which has some data loaded in it. There is a radio button in my application, which when clicked should update the TreeModel with a new data.

I have tried the following things on switching the radio button and none is working:

  • emit layoutChanged

    emit layoutChanged();
    
  • emit dataChanged

    emit dataChanged(QModelIndex(), QModelIndex()); 
    

Referenced from:

What does 'bottomRight' mean when using dataChanged() with a QTreeView in Qt?

  • Recursively visiting each node in the tree and emitting dataChanged

    void TreeView::getLastExpandedState(const QModelIndex& parent)
    {   
        bool isExpand = isExpanded(parent);
        if (!isExpand) {
            return;
        }
        int rows = model()->rowCount(parent);
    
        for (int rowNum = 0; rowNum < rows ; ++rowNum) {
            QModelIndex childIndex = model()->index(rowNum, 0, parent);
            model->emitChange(parent,childIndex);
            getLastExpandedState(childIndex);
        }
    }
    
    void TreeModel::emitChange(const QModelIndex& parent,const QModelIndex& childIndex) {
        emit dataChanged(parent,childIndex);
    }
    

How to solve that?


Solution

  • The answer you reference is at best confusing and probably wrong.

    Your model code needs to emit a dataChanged signal for any rectangle of cells where the data returned by the model data method has changed. See, for example, this question and answer, which goes into some detail.

    Note that the parameters in the dataChanged signal should not be parent and child - they should be "topLeft" and "bottomRight". They need to have the same parent and also to be different. So you don't need to iterate over the rows and emit the signal for each row. You can send a combined signal for all the rows that have changed.

    But you do need to send a signal for each parent (where data has changed) that signals the top left cell and bottom right cell for that parent. So you might end up creating an index for the top left cell for that parent at (0, 0, parent) and another for the bottom right cell at (rows, cols, parent) and then sending the signal for that pair of indices.