Important: Please read the Qt Code of Conduct -

QTreeWidget and QUndoStack?

  • Hej,

    I have subclassed a QTreeWidget for showing a structure to the user.
    The user is also able to drag items in that tree around (only Qt::MoveAction). Works fine.

    Now, I also have a QUndoStack to provide the option to undo things.

    Question is now: How can I offer undo for the (automatic) move actions in the QTreeWidget?


  • I would recommend to use model - view idea when undo is needed. Implement basics actions - add/remove/move/change of your model, then subclass the model to "gui" class and reimplement these actions to wrap them with undo commands - you will have well structured, easy to modify and easy to change behavior if needed

  • I was afraid that I need to do that!

    After playing around for days trying to solve that issues in a nice way, I think I need to find the courage and subclass a QAbstractItemView.

    To bad, QTreeWidget is fine ... except the missing undo functionality!


  • You should only need to subclass "QAbstractItemModel": "QStandardItemModel": is also worth a look.

  • Hej,

    Me again, just wanted to know if my current solution for this is okay ;)

    I now have subclassed QTreeView and QAbstractItemView.
    To get the undo function to work I now intercept QDropEvents in overwriting QTreeView::dropEvent(). That way I just push a new QUndoCommand to the undo stack (that performs the reparenting in the tree) and set the QDropEvent::dropAction to IgnoreAction before calling QTreeView::dropEvent() of my super class.

    Is that the right way to do it?


  • Looks okay for now - main issue for you to get it working :)

  • Have you solved the problem? I want to implement redo/undo for QTableWidget. Could I see you solution? Thanks.

  • Hej,

    Yes I solved the problem. But I had to go from the QTreeWidget to the QTreeView because the QTreeWidget did a lot of things automatically I didn't want and I couldn't intercept!

    So I created a subclass from QAbstractItemModel to represent my hierarchical structure and show this using my own subclass of QTreeView. In that subclass of QTreeView I overwrote the dropEvent method to intercept what ever the QTreeView is doing and instead doing the reparenting myself by creating a QUndoCommand (subclass) and put it in the QUndoStack!

Log in to reply