QUndo 是什么?
就是Qt 提供给你用于撤销 重做实现的一种更方便的工具类
怎么理解?(怎么用)
QUndoStack 类用于管理你的一步一步操作
QUndoCommand 用于告诉QUndoStack类怎么管理。例如这一步操作是移动了?是删除了?
QUndoStack:
上手就三个函数:push,redo,undo
push:提交一次操作
redo: 撤销一次操作
undo:反撤销一次操作
QUndoCommand:
任何定义的一种操作都需要继承这个类,然后实现 redo 和 undo
其中构造函数应当传入这次操作需要的 对象和数据(往哪个对象上做什么?)
//在字符串后添加内容
void redo()override
{
m_baseStr->append(m_str);
}
// undo即为撤销,撤销就是把添加的内容删掉
void undo()override
{
m_baseStr->remove(((m_baseStr->length()) - (m_str.length())), m_str.length());
}
如何使用?
第一步:新建QUndoStack 类
QUndoStack *m_stack = new QUndoStack;
第二步:往类中提交操作
(注意,提交一次操作就应该有一个QUndoCommand 的子类指针被生成后传入)
m_stack->push(new UndoandRedo(str, QString(" >>and_you")));
第三步:撤销 / 重做
m_stack->undo();
m_stack->redo();
现在贴出全部代码,供参考(新手向,只在了解最基础的使用方法)
// 直接复制进 Qt 源文件即可运行
#include <QtCore/QCoreApplication>
#include <QString>
#include <QDebug>
/*
主要类: QUndoStack 操作记录堆管理类 一个
QUndoCommand 管理项基类,所有需要管理的项目都需要继承于这个对象
操作:向前:redo 撤销 :undo
在执行 push时即为创建出当期对象后执行一次 redo
*/
//undoAndRedo.h 单cpp文件
#ifndef UNDOANDREDO
#define UNDOANFREDO
#include <QUndoCommand>
#include <QString>
class UndoandRedo :public QUndoCommand
{
public:
UndoandRedo(QString* baseStr, const QString& str)
{
m_baseStr = baseStr;
m_str = str;
}
void redo()override
{
m_baseStr->append(m_str);
}
void undo()override
{
m_baseStr->remove(((m_baseStr->length()) - (m_str.length())), m_str.length());
}
private:
QString* m_baseStr;
QString m_str;
};
#endif //UNDOANFREDO
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString* str = new QString("hello_world");
QUndoStack *m_stack = new QUndoStack;
m_stack->push(new UndoandRedo(str, QString(" >>and_you")));
m_stack->push(new UndoandRedo(str, QString(" >>and_me")));
qDebug() <<"1: " << *str;
//撤销
m_stack->undo();
qDebug() <<"2: " << *str;
/* push会覆盖 */ //建议删除和添加都单独定义新的类去完成
m_stack->push(new UndoandRedo(str, QString(" >>and_he")));
qDebug() <<"3: " << *str;
m_stack->undo();
qDebug() <<"4: " << *str; //undo 和 redo 都有防越界判定,无需过度担心撤销过度。
m_stack->undo();
qDebug() << "5: " << *str;
qDebug() <<endl<< "*****************" << endl;
//反撤销 :一般译为“重做”
m_stack->redo();
qDebug() << "6: " << *str;
m_stack->redo();
qDebug() << "7: " << *str;
m_stack->redo();
qDebug() << "8: " << *str;
return a.exec();
}
运行结果:
1: "hello_world >>and_you >>and_me"
2: "hello_world >>and_you"
3: "hello_world >>and_you >>and_he"
4: "hello_world >>and_you"
5: "hello_world"
*****************
6: "hello_world >>and_you"
7: "hello_world >>and_you >>and_he"
8: "hello_world >>and_you >>and_he"