Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Undo Framework Example#

This example shows how to implement undo/redo functionality with the Qt undo framework.

../_images/undoframeworkexample.png

In the Qt undo framework, all actions that the user performs are implemented in classes that inherit QUndoCommand. An undo command class knows how to both redo() - or just do the first time - and undo() an action. For each action the user performs, a command is placed on a QUndoStack. Since the stack contains all commands executed (stacked in chronological order) on the document, it can roll the state of the document backwards and forwards by undoing and redoing its commands. See the overview document for a high-level introduction to the undo framework.

The undo example implements a simple diagram application. It is possible to add and delete items, which are either box or rectangular shaped, and move the items by dragging them with the mouse. The undo stack is shown in a QUndoView , which is a list in which the commands are shown as list items. Undo and redo are available through the edit menu. The user can also select a command from the undo view.

We use the graphics view framework to implement the diagram. We only treat the related code briefly as the framework has examples of its own (e.g., the Diagram Scene Example ).

The example consists of the following classes:

  • MainWindow is the main window and arranges the example’s widgets. It creates the commands based on user input and keeps them on the command stack.

  • AddCommand adds an item to the scene.

  • DeleteCommand deletes an item from the scene.

  • MoveCommand when an item is moved the MoveCommand keeps record of the start and stop positions of the move, and it moves the item according to these when redo() and undo() is called.

  • DiagramScene inherits QGraphicsScene and emits signals for the MoveComands when an item is moved.

  • DiagramItem inherits QGraphicsPolygonItem and represents an item in the diagram.

MainWindow Class Definition#

class MainWindow(QMainWindow):

    Q_OBJECT
# public
    MainWindow()
# public slots
    def itemMoved(movedDiagram, moveStartPosition):
# private slots
    def deleteItem():
    def addBox():
    def addTriangle():
    def about():
    def updateActions():
# private
    def createActions():
    def createMenus():
    def createToolBars():
    def createUndoView():
    deleteAction = None
    addBoxAction = None
    addTriangleAction = None
    undoAction = None
    redoAction = None
    exitAction = None
    aboutAction = None
    fileMenu = None
    editMenu = None
    itemMenu = None
    helpMenu = None
    diagramScene = None
    undoStack = None
    undoView = None

The MainWindow class maintains the undo stack, i.e., it creates QUndoCommands and pushes and pops them from the stack when it receives the triggered() signal from undoAction and redoAction.

MainWindow Class Implementation#

We will start with a look at the constructor:

def __init__(self):

    undoStack = QUndoStack(self)
    diagramScene = DiagramScene()
    pixmapBrush = QBrush(QPixmap(":/icons/cross.png").scaled(30, 30))
    diagramScene.setBackgroundBrush(pixmapBrush)
    diagramScene.setSceneRect(QRect(0, 0, 500, 500))
    createActions()
    createMenus()
    createToolBars()
    createUndoView()
    diagramScene.itemMoved.connect(
            self.itemMoved)
    diagramScene.selectionChanged.connect(
            self.updateActions)
    setWindowTitle("Undo Framework")
    view = QGraphicsView(diagramScene)
    setCentralWidget(view)
    adjustSize()

In the constructor, we set up the DiagramScene and QGraphicsView . We only want deleteAction to be enabled when we have selected an item, so we connect to the selectionChanged() signal of the scene to updateActions() slot.

Here is the createUndoView() function:

def createUndoView(self):

    undoDockWidget = QDockWidget()
    undoDockWidget.setWindowTitle(tr("Command List"))
    undoDockWidget.setWidget(QUndoView(undoStack))
    addDockWidget(Qt.RightDockWidgetArea, undoDockWidget)

The QUndoView is a widget that display the text, which is set with the setText() function, for each QUndoCommand in the undo stack in a list. We put it into a docking widget.

Here is the createActions() function:

def createActions(self):

    deleteAction = QAction(QIcon(":/icons/remove.png"), tr("Delete Item"), self)
    deleteAction.setShortcut(tr("Del"))
    deleteAction.triggered.connect(self.deleteItem)            ...

undoAction = undoStack.createUndoAction(self, tr("Undo"))
undoAction.setIcon(QIcon(":/icons/undo.png"))
undoAction.setShortcuts(QKeySequence.Undo)
redoAction = undoStack.createRedoAction(self, tr("Redo"))
redoAction.setIcon(QIcon(":/icons/redo.png"))
redoAction.setShortcuts(QKeySequence.Redo)

The createActions() function sets up all the examples actions in the manner shown above. The createUndoAction() and createRedoAction() methods help us create actions that are disabled and enabled based on the state of the stack. Also, the text of the action will be updated automatically based on the text() of the undo commands. For the other actions we have implemented slots in the MainWindow class.

    ...

    updateActions()

def updateActions(self):

    deleteAction.setEnabled(not diagramScene.selectedItems().isEmpty())

Once all actions are created we update their state by calling the same function that is connected to the selectionChanged signal of the scene.

The createMenus() and createToolBars() functions add the actions to menus and toolbars:

def createMenus(self):

    fileMenu = menuBar().addMenu(tr("File"))
    fileMenu.addAction(exitAction)
    editMenu = menuBar().addMenu(tr("Edit"))
    editMenu.addAction(undoAction)
    editMenu.addAction(redoAction)
    editMenu.addSeparator()
    editMenu.addAction(deleteAction)            ...

    helpMenu = menuBar().addMenu(tr("About"))
    helpMenu.addAction(aboutAction)

def createToolBars(self):

    editToolBar = QToolBar()
    editToolBar.addAction(undoAction)
    editToolBar.addAction(redoAction)
    editToolBar.addSeparator()
    editToolBar.addAction(deleteAction)            ...

addToolBar(editToolBar)
addToolBar(itemToolBar)

Here is the itemMoved() slot:

def itemMoved(self, movedItem,):
                           QPointF oldPosition)

    undoStack.push(MoveCommand(movedItem, oldPosition))

We simply push a MoveCommand on the stack, which calls redo() on it.

Here is the deleteItem() slot:

def deleteItem(self):

    if diagramScene.selectedItems().isEmpty():
        return
    deleteCommand = DeleteCommand(diagramScene)
    undoStack.push(deleteCommand)

An item must be selected to be deleted. We need to check if it is selected as the deleteAction may be enabled even if an item is not selected. This can happen as we do not catch a signal or event when an item is selected.

Here is the addBox() slot:

def addBox(self):

    addCommand = AddCommand(DiagramItem::Box, diagramScene)
    undoStack.push(addCommand)

The addBox() function creates an AddCommand and pushes it on the undo stack.

Here is the addTriangle() sot:

def addTriangle(self):

    addCommand = AddCommand(DiagramItem::Triangle,()
                                              diagramScene)
    undoStack.push(addCommand)

The addTriangle() function creates an AddCommand and pushes it on the undo stack.

Here is the implementation of about():

def about(self):

    QMessageBox.about(self, tr("About Undo"),
                       tr("The <b>Undo</b> example demonstrates how to "
                          "use Qt's undo framework."))

The about slot is triggered by the aboutAction and displays an about box for the example.

AddCommand Class Definition#

class AddCommand(QUndoCommand):

# public
    AddCommand(DiagramItem.DiagramType addType, QGraphicsScene graphicsScene,
               parent = None)
    ~AddCommand()
    def undo():
    def redo():
# private
    myDiagramItem = DiagramItem()
    myGraphicsScene = QGraphicsScene()
    initialPosition = QPointF()

The AddCommand class adds DiagramItem graphics items to the DiagramScene.

AddCommand Class Implementation#

We start with the constructor:

AddCommand.AddCommand(DiagramItem.DiagramType addType,
                       QGraphicsScene scene, QUndoCommand parent)
    super().__init__(parent)
    self.myGraphicsScene = scene

    itemCount = 0
    myDiagramItem = DiagramItem(addType)
    initialPosition = QPointF((itemCount * 15) % int(scene.width()),
                              (itemCount * 15) % int(scene.height()))
    scene.update()
    itemCount = itemCount + 1
    setText(QObject.tr("Add %1")
        .arg(createCommandString(myDiagramItem, initialPosition)))

We first create the DiagramItem to add to the DiagramScene. The setText() function let us set a QString that describes the command. We use this to get custom messages in the QUndoView and in the menu of the main window.

def undo(self):

    myGraphicsScene.removeItem(myDiagramItem)
    myGraphicsScene.update()

undo() removes the item from the scene.

def redo(self):

    myGraphicsScene.addItem(myDiagramItem)
    myDiagramItem.setPos(initialPosition)
    myGraphicsScene.clearSelection()
    myGraphicsScene.update()

We set the position of the item as we do not do this in the constructor.

DeleteCommand Class Definition#

class DeleteCommand(QUndoCommand):

# public
    DeleteCommand = explicit(QGraphicsScene graphicsScene, QUndoCommand parent = None)
    def undo():
    def redo():
# private
    myDiagramItem = DiagramItem()
    myGraphicsScene = QGraphicsScene()

The DeleteCommand class implements the functionality to remove an item from the scene.

DeleteCommand Class Implementation#

def __init__(self, scene, parent):
    super().__init__(parent)
    self.myGraphicsScene = scene

    > list = myGraphicsScene.selectedItems()
    list.first().setSelected(False)
    myDiagramItem = DiagramItem(list.first())
    setText(QObject.tr("Delete %1")
        .arg(createCommandString(myDiagramItem, myDiagramItem.pos())))

We know that there must be one selected item as it is not possible to create a DeleteCommand unless the item to be deleted is selected and that only one item can be selected at any time. The item must be unselected if it is inserted back into the scene.

def undo(self):

    myGraphicsScene.addItem(myDiagramItem)
    myGraphicsScene.update()

The item is simply reinserted into the scene.

def redo(self):

    myGraphicsScene.removeItem(myDiagramItem)

The item is removed from the scene.

MoveCommand Class Definition#

class MoveCommand(QUndoCommand):

# public
    enum { Id = 1234 }
    MoveCommand(DiagramItem diagramItem, QPointF oldPos,
                parent = None)
    def undo():
    def redo():
    bool mergeWith(QUndoCommand command) override
    int id() override { return Id; }
# private
    myDiagramItem = DiagramItem()
    myOldPos = QPointF()
    newPos = QPointF()

The mergeWith() is reimplemented to make consecutive moves of an item one MoveCommand, i.e, the item will be moved back to the start position of the first move.

MoveCommand Class Implementation#

The constructor of MoveCommand looks like this:

MoveCommand.MoveCommand(DiagramItem diagramItem, QPointF oldPos,
                         QUndoCommand parent)
    super().__init__(parent)
    self.myDiagramItem = diagramItem
    , myOldPos(oldPos), newPos(diagramItem.pos())

We save both the old and new positions for undo and redo respectively.

def undo(self):

    myDiagramItem.setPos(myOldPos)
    myDiagramItem.scene().update()
    setText(QObject.tr("Move %1")
        .arg(createCommandString(myDiagramItem, newPos)))

We simply set the items old position and update the scene.

def redo(self):

    myDiagramItem.setPos(newPos)
    setText(QObject.tr("Move %1")
        .arg(createCommandString(myDiagramItem, newPos)))

We set the item to its new position.

def mergeWith(self, QUndoCommand command):

    moveCommand = MoveCommand(command)
    item = moveCommand.myDiagramItem
    if myDiagramItem != item:
        return False
    newPos = item.pos()
    setText(QObject.tr("Move %1")
        .arg(createCommandString(myDiagramItem, newPos)))
    return True

Whenever a MoveCommand is created, this function is called to check if it should be merged with the previous command. It is the previous command object that is kept on the stack. The function returns true if the command is merged; otherwise false.

We first check whether it is the same item that has been moved twice, in which case we merge the commands. We update the position of the item so that it will take the last position in the move sequence when undone.

DiagramScene Class Definition#

class DiagramScene(QGraphicsScene):

    Q_OBJECT
# public
    DiagramScene(QObject parent = None)
# signals
    def itemMoved(movedItem, movedFromPosition):
# protected
    def mousePressEvent(event):
    def mouseReleaseEvent(event):
# private
    movingItem = None
    oldPos = QPointF()

The DiagramScene implements the functionality to move a DiagramItem with the mouse. It emits a signal when a move is completed. This is caught by the MainWindow, which makes MoveCommands. We do not examine the implementation of DiagramScene as it only deals with graphics framework issues.

The `` main()``

Function#

The main() function of the program looks like this:

if __name__ == "__main__":

    app = QApplication(argv, args)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec())

We draw a grid in the background of the DiagramScene, so we use a resource file. The rest of the function creates the MainWindow and shows it as a top level window.

Example project @ code.qt.io