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.