Removing a row from a custom QAbstractItemModel tree model



  • I created a simple custom tree item model. The model has only two levels of hierarchy, so I came up with a trick and implemented the index() and parent() methods as follows (robustness removed and reduced for overview):

    @
    QModelIndex index(int row, int column, const QModelIndex &parent) const {
    if (!parent.isValid())
    return createIndex(row, column, static_cast<quintptr>(-1));
    else
    return createIndex(row, column, static_cast<quintptr>(parent.row()));
    }

    QModelIndex parent(const QModelIndex &child) const
    const int i = static_cast<qintptr>(child.internalId());
    if (i < 0)
    return QModelIndex();
    else
    return createIndex(i, 0, static_cast<quintptr>(-1));
    }
    @

    The idea: For this two-level model I used the internalId() to store either the parent's row for items on the second level or -1 for top level items. This allows a smart and fast implementation of the parent() method.

    This actually works fine, except when it comes to removing rows from the model. When removing rows, the current item selection is destroyed and I get debug messages like:

    @
    QAbstractItemModel::endRemoveRows: Invalid index ( 0 , 0 ) in model TheModel(0xb46c70)
    @

    When I re-implement the model using the more common approach with real pointers for internalPointer() and a parent() implementation that retrieves the actual row via something like indexOf() in the root items list, everything works, including selections.

    I suppose something is clearly broken with the prior idea, and it probably is something related to persistent indices, but I cannot figure out.

    Hope you can help..

    Thank you in advance,
    Kama


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.