Qt 撤消框架概述

介绍

Qt 撤消框架是 Command (命令) 模式的实现,用于在应用程序中实现撤消/重做功能。

命令模式基于应用程序中所有编辑都是通过创建命令对象实例来履行的思想。命令对象将改变应用于文档并存储在命令堆栈中。此外,每个命令知道如何撤销其更改,从而使文档回到其先前状态。只要应用程序仅使用命令对象来改变文档状态,通过向下遍历堆栈并在每个命令中依次调用 undo 来撤消一系列命令是可能的。通过向上遍历堆栈并在每个命令中调用 redo 来重做一系列命令也是可能的。

框架由 4 个类组成:

  • QUndoCommand 是存储在撤消堆栈中所有命令的基类。它可以应用 (重做) 或撤销文档中的单个改变。
  • QUndoStack 是列表化的 QUndoCommand 对象。它包含所有文档执行命令,且可以通过撤消 (或重做) 它们以向后 (或向前) 卷动文档状态。
  • QUndoGroup 是撤消堆栈组。它很有用,当应用程序包含多个撤消堆栈时,每个打开文档通常都有一个。 QUndoGroup 为组中所有堆栈提供了一对撤销/重做槽。它把撤消/重做请求转发给活动堆栈,这是目前用户正编辑文档的关联堆栈。
  • QUndoView 是展示撤消堆栈内容的 Widget。点击视图中的命令会向后 (或向前) 卷动文档状态到该命令。

概念

框架支持下列概念:

  • 清理状态: Used to signal when the document enters and leaves a state that has been saved to disk. This is typically used to disable or enable the save actions, and to update the document's title bar.
  • 命令压缩: Used to compress sequences of commands into a single command. For example: In a text editor, the commands that insert individual characters into the document can be compressed into a single command that inserts whole sections of text. These bigger changes are more convenient for the user to undo and redo.
  • 命令宏: A sequence of commands, all of which are undone or redone in one step. These simplify the task of writing an application, since a set of simpler commands can be composed into more complex commands. For example, a command that moves a set of selected objects in a document can be created by combining a set of commands, each of which moves a single object.

QUndoStack 提供方便撤消和重做 QAction objects that can be inserted into a menu or a toolbar. The text properties of these actions always reflect what command will be undone or redone when they are triggered. Similarly, QUndoGroup provides undo and redo actions that always behave like the undo and redo actions of the active stack.