Viadeo Twitter Google Bookmarks ! Facebook Digg MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Undo Framework Example



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

The Undo Diagram Example

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 : public QMainWindow


 public slots:
     void itemMoved(DiagramItem *movedDiagram, const QPointF &moveStartPosition);

 private slots:
     void deleteItem();
     void addBox();
     void addTriangle();
     void about();
     void itemMenuAboutToShow();
     void itemMenuAboutToHide();

     void createActions();
     void createMenus();
     void createUndoView();

     QAction *deleteAction;
     QAction *addBoxAction;
     QAction *addTriangleAction;
     QAction *undoAction;
     QAction *redoAction;
     QAction *exitAction;
     QAction *aboutAction;

     QMenu *fileMenu;
     QMenu *editMenu;
     QMenu *itemMenu;
     QMenu *helpMenu;

     DiagramScene *diagramScene;
     QUndoStack *undoStack;
     QUndoView *undoView;

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:

     undoStack = new QUndoStack();



     diagramScene = new DiagramScene();
     QBrush pixmapBrush(QPixmap(":/images/cross.png").scaled(30, 30));
     diagramScene->setSceneRect(QRect(0, 0, 500, 500));

     connect(diagramScene, SIGNAL(itemMoved(DiagramItem*,QPointF)),
             this, SLOT(itemMoved(DiagramItem*,QPointF)));

     setWindowTitle("Undo Framework");
     QGraphicsView *view = new QGraphicsView(diagramScene);
     resize(700, 500);

In the constructor, we set up the DiagramScene and QGraphicsView.

Here is the createUndoView() function:

 void MainWindow::createUndoView()
     undoView = new QUndoView(undoStack);
     undoView->setWindowTitle(tr("Command List"));
     undoView->setAttribute(Qt::WA_QuitOnClose, false);

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.

Here is the createActions() function:

 void MainWindow::createActions()
     deleteAction = new QAction(tr("&Delete Item"), this);
     connect(deleteAction, SIGNAL(triggered()), this, SLOT(deleteItem()));

     undoAction = undoStack->createUndoAction(this, tr("&Undo"));

     redoAction = undoStack->createRedoAction(this, tr("&Redo"));

The createActions() function sets up all the examples actions in the manner shown above. The createUndoAction() and createRedoAction() helps us crate 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.

Here is the createMenus() function:

 void MainWindow::createMenus()
     editMenu = menuBar()->addMenu(tr("&Edit"));
     connect(editMenu, SIGNAL(aboutToShow()),
             this, SLOT(itemMenuAboutToShow()));
     connect(editMenu, SIGNAL(aboutToHide()),
             this, SLOT(itemMenuAboutToHide()));


We have to use the QMenu aboutToShow() and aboutToHide() signals since we only want deleteAction to be enabled when we have selected an item.

Here is the itemMoved() slot:

 void MainWindow::itemMoved(DiagramItem *movedItem,
                            const QPointF &oldPosition)
     undoStack->push(new MoveCommand(movedItem, oldPosition));

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

Here is the deleteItem() slot:

 void MainWindow::deleteItem()
     if (diagramScene->selectedItems().isEmpty())

     QUndoCommand *deleteCommand = new DeleteCommand(diagramScene);

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 itemMenuAboutToShow() and itemMenuAboutToHide() slots:

 void MainWindow::itemMenuAboutToHide()

 void MainWindow::itemMenuAboutToShow()

We implement itemMenuAboutToShow() and itemMenuAboutToHide() to get a dynamic item menu. These slots are connected to the aboutToShow() and aboutToHide() signals. We need this to disable or enable the deleteAction.

Here is the addBox() slot:

 void MainWindow::addBox()
     QUndoCommand *addCommand = new AddCommand(DiagramItem::Box, diagramScene);

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

Here is the addTriangle() sot:

 void MainWindow::addTriangle()
     QUndoCommand *addCommand = new AddCommand(DiagramItem::Triangle,

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

Here is the implementation of about():

 void MainWindow::about()
     QMessageBox::about(this, 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 : public QUndoCommand
     AddCommand(DiagramItem::DiagramType addType, QGraphicsScene *graphicsScene,
                QUndoCommand *parent = 0);

     void undo();
     void redo();

     DiagramItem *myDiagramItem;
     QGraphicsScene *myGraphicsScene;
     QPointF initialPosition;

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)
     : QUndoCommand(parent)
     static int itemCount = 0;

     myGraphicsScene = scene;
     myDiagramItem = new DiagramItem(addType);
     initialPosition = QPointF((itemCount * 15) % int(scene->width()),
                               (itemCount * 15) % int(scene->height()));
     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.

 void AddCommand::undo()

undo() removes the item from the scene. We need to update the scene as ...(ask Andreas)

 void AddCommand::redo()

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

DeleteCommand Class Definition

 class DeleteCommand : public QUndoCommand
     DeleteCommand(QGraphicsScene *graphicsScene, QUndoCommand *parent = 0);

     void undo();
     void redo();

     DiagramItem *myDiagramItem;
     QGraphicsScene *myGraphicsScene;

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

DeleteCommand Class Implementation

 DeleteCommand::DeleteCommand(QGraphicsScene *scene, QUndoCommand *parent)
     : QUndoCommand(parent)
     myGraphicsScene = scene;
     QList<QGraphicsItem *> list = myGraphicsScene->selectedItems();
     myDiagramItem = static_cast<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.

 void DeleteCommand::undo()

The item is simply reinserted into the scene.

 void DeleteCommand::redo()

The item is removed from the scene.

MoveCommand Class Definition

 class MoveCommand : public QUndoCommand
     enum { Id = 1234 };

     MoveCommand(DiagramItem *diagramItem, const QPointF &oldPos,
                 QUndoCommand *parent = 0);

     void undo();
     void redo();
     bool mergeWith(const QUndoCommand *command);
     int id() const { return Id; }

     DiagramItem *myDiagramItem;
     QPointF myOldPos;
     QPointF newPos;

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, const QPointF &oldPos,
                  QUndoCommand *parent)
     : QUndoCommand(parent)
     myDiagramItem = diagramItem;
     newPos = diagramItem->pos();
     myOldPos = oldPos;

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

 void MoveCommand::undo()
     setText(QObject::tr("Move %1")
         .arg(createCommandString(myDiagramItem, newPos)));

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

 void MoveCommand::redo()
     setText(QObject::tr("Move %1")
         .arg(createCommandString(myDiagramItem, newPos)));

We set the item to its new position.

 bool MoveCommand::mergeWith(const QUndoCommand *command)
     const MoveCommand *moveCommand = static_cast<const MoveCommand *>(command);
     DiagramItem *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 : public QGraphicsScene

     DiagramScene(QObject *parent = 0);

     void itemMoved(DiagramItem *movedItem, const QPointF &movedFromPosition);

     void mousePressEvent(QGraphicsSceneMouseEvent *event);
     void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);

     QGraphicsItem *movingItem;
     QPointF oldPos;

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:

 int main(int argv, char *args[])

     QApplication app(argv, args);

     MainWindow mainWindow;;

     return 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.


Best Of

Actualités les plus lues

  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 8
Page suivante

Le Qt Developer Network au hasard


Installation de PySide : binaires et compilation

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. Lire l'article.



Liens utiles


  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.6
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !

Hébergement Web