61 lines
1.7 KiB
C++
61 lines
1.7 KiB
C++
#ifndef UNDO_H
|
|
#define UNDO_H
|
|
|
|
#include <QUndoCommand>
|
|
#include <QLineEdit>
|
|
#include <QPlainTextEdit>
|
|
#include <QtGlobal>
|
|
#include "mainwindow.h"
|
|
|
|
class LineEditCommand : public QUndoCommand {
|
|
public:
|
|
LineEditCommand(QLineEdit* edit, const QString& oldText, const QString& newText)
|
|
: m_edit(edit), m_oldText(oldText), m_newText(newText) {}
|
|
|
|
void undo() override { m_edit->setText(m_oldText); }
|
|
void redo() override { m_edit->setText(m_newText); }
|
|
|
|
private:
|
|
QLineEdit* m_edit;
|
|
QString m_oldText;
|
|
QString m_newText;
|
|
};
|
|
|
|
class PlainTextEditCommand : public QUndoCommand {
|
|
public:
|
|
PlainTextEditCommand(QPlainTextEdit* edit, const QString& oldText, const QString& newText, MainWindow* mw)
|
|
: m_edit(edit), m_oldText(oldText), m_newText(newText), m_mainWindow(mw)
|
|
{
|
|
// Sauvegarde la position du curseur actuelle
|
|
m_cursorPosition = edit->textCursor().position();
|
|
}
|
|
|
|
void undo() override {
|
|
m_mainWindow->m_handlingUndoRedo = true;
|
|
m_edit->setPlainText(m_oldText);
|
|
restoreCursor();
|
|
m_mainWindow->m_handlingUndoRedo = false;
|
|
}
|
|
void redo() override {
|
|
m_mainWindow->m_handlingUndoRedo = true;
|
|
m_edit->setPlainText(m_newText);
|
|
restoreCursor();
|
|
m_mainWindow->m_handlingUndoRedo = false;
|
|
}
|
|
private:
|
|
void restoreCursor() {
|
|
QTextCursor cursor = m_edit->textCursor();
|
|
int pos = qMin(m_cursorPosition, m_edit->toPlainText().size());
|
|
cursor.setPosition(pos);
|
|
m_edit->setTextCursor(cursor);
|
|
}
|
|
|
|
QPlainTextEdit* m_edit;
|
|
QString m_oldText;
|
|
QString m_newText;
|
|
MainWindow* m_mainWindow;
|
|
int m_cursorPosition;
|
|
};
|
|
|
|
#endif // UNDO_H
|