1、概述
QUndoView
是 Qt 框架中用于显示 QUndoStack
(撤销堆栈)内容的视图类。它通常与 QUndoStack
一起使用,为用户提供了一个可视化的界面来查看和操作撤销/重做历史。QUndoView
可以显示堆栈中的每个命令,并允许用户通过界面进行撤销或重做操作。
2、重要方法
QUndoStack *stack() const
:返回此视图所显示的QUndoStack
。void setStack(QUndoStack *stack)
:设置此视图要显示的QUndoStack
。void setCleanIcon(const QIcon &icon)
和QIcon cleanIcon() const
:设置和获取表示堆栈为干净状态时的图标。void setUndoIcon(const QIcon &icon)
和QIcon undoIcon() const
:设置和获取表示撤销操作的图标。void setRedoIcon(const QIcon &icon)
和QIcon redoIcon() const
:设置和获取表示重做操作的图标。- void setGroup(QUndoGroup *group):设置视图显示的撤销组。
- QUndoGroup *group():返回当前视图显示的撤销组。
此外,QUndoView
还继承了 QAbstractItemView
的许多方法,这些方法允许你进一步定制视图的外观和行为。
MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow),undoGroup(new QUndoGroup(this)),tabWidget(new QTabWidget(this)),undoView(new QUndoView(undoGroup, this))
{ui->setupUi(this);setCentralWidget(tabWidget);QMenu *fileMenu = menuBar()->addMenu(tr("&File"));QAction *newAction = fileMenu->addAction(tr("&New Document"), this, &MainWindow::newDocument);fileMenu->addAction(tr("do"), this, [&]{handleTextChanged();});QMenu *editMenu = menuBar()->addMenu(tr("&Edit"));QAction *undoAction = undoGroup->createUndoAction(this, tr("&Undo"));QAction *redoAction = undoGroup->createRedoAction(this, tr("&Redo"));editMenu->addAction(undoAction);editMenu->addAction(redoAction);QDockWidget *dockWidget = new QDockWidget(("Undo History"), this);dockWidget->setWidget(undoView);// 添加撤销视图到主窗口addDockWidget(Qt::RightDockWidgetArea, dockWidget);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::newDocument()
{QTextEdit *textEdit = new QTextEdit(this);QUndoStack *undoStack = new QUndoStack(this);undoGroup->addStack(undoStack);undoGroup->setActiveStack(undoStack);int tabIndex = tabWidget->addTab(textEdit, tr("Document %1").arg(tabWidget->count() + 1));tabWidget->setCurrentIndex(tabIndex);connect(undoStack, &QUndoStack::indexChanged, [=](int idx) {textEdit->setWindowTitle(tr("Document %1 (modified)").arg(tabIndex + 1));});
}void MainWindow::handleTextChanged()
{QTextEdit *textEdit = qobject_cast<QTextEdit *>(tabWidget->currentWidget());if (textEdit){QString text = textEdit->toPlainText();QUndoStack *undoStack = undoGroup->stacks().at(tabWidget->currentIndex());if(undoStack){qDebug() << "undoStack";undoStack->push(new TextEditCommand(textEdit, text));}}
}TextEditCommand::TextEditCommand(QTextEdit *textEdit, const QString &text): m_textEdit(textEdit), m_text(text)
{setText(text);
}void TextEditCommand::undo()
{qDebug() << "undo";m_textEdit->setText(m_text);
}void TextEditCommand::redo()
{qDebug() << "redo";m_textEdit->setText(m_text);
}
觉得有帮助的话,打赏一下呗。。