How to update QTreeView when reordering siblings in a custom Tree model

  • I have a QTreeView that displays my custom model.
    It works, but now I need to reorder the children of a item in the tree.

    I tried to do this in the modell, but it crashes my program

    In this code, item is the current item that should change order among its siblings

    beginMoveRows(item->parentItem()->index(),  1,   item->parentItem()->childCount(), item->parentItem()->index(), 1);
    // re order the children

    Any advice on how to do this?

    Or is there a way of reloading the entire model?

  • Are you only moving one item? I think it should be

    beginMoveRows(parent's index,  item's curent row, item's current row again, parent's index again, the row item is moving to);

    Take a detail look at beginMoveRows's 3rd and 4th example.

    For reloading, I think that should be beginResetModel() and endResetModel()

  • Yes, only moving one item, but after reading the examples I think it will be trick yo use the beginMoveRows method, since I'm moving one item by calling std::sort on all the siblings (including the moved item, they are in a QList)
    So I don't really know where the item will end up before moving them.

    I can of course try to find the new position before sorting, but that feels like double-work.
    I guess a call to beginResetModel would be the easiest way (but slower?)

    Or is there any better ways of doing this?

  • @OpenGL
    If it is about sorting I think you can take a look at the Qt source code about how its treemodel handles an item's children sorting.

    emit model->layoutAboutToBeChanged({}, QAbstractItemModel::VerticalSortHint);
    // the sorting...update the persistent index list if there's any
    emit model->layoutChanged({}, QAbstractItemModel::VerticalSortHint);

    As I can see it just emit layoutAboutToBeChanged and layoutChanged signals without specifying any index.

  • I solved it by calculating the new position for the item.

Log in to reply