Add undo/redo action for dialogEdit
This commit is contained in:
parent
49c09b8d2e
commit
3fa9853a12
39
Undo.h
39
Undo.h
@ -3,6 +3,9 @@
|
||||
|
||||
#include <QUndoCommand>
|
||||
#include <QLineEdit>
|
||||
#include <QPlainTextEdit>
|
||||
#include <QtGlobal>
|
||||
#include "mainwindow.h"
|
||||
|
||||
class LineEditCommand : public QUndoCommand {
|
||||
public:
|
||||
@ -18,4 +21,40 @@ private:
|
||||
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
|
||||
|
||||
@ -65,6 +65,16 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
}
|
||||
});
|
||||
|
||||
connect(ui->dialogEdit, &QPlainTextEdit::textChanged, this, [this]() {
|
||||
static QString previousText = ui->dialogEdit->toPlainText();
|
||||
if (m_handlingUndoRedo) return;
|
||||
QString currentText = ui->dialogEdit->toPlainText();
|
||||
if (currentText != previousText) {
|
||||
undoStack->push(new PlainTextEditCommand(ui->dialogEdit, previousText, currentText, this));
|
||||
previousText = currentText;
|
||||
}
|
||||
});
|
||||
|
||||
connect(ui->actionEditUndo, &QAction::triggered, undoStack, &QUndoStack::undo);
|
||||
connect(ui->actionEditRedo, &QAction::triggered, undoStack, &QUndoStack::redo);
|
||||
currentPath->getStep().append(Step());
|
||||
@ -997,4 +1007,4 @@ void MainWindow::on_actionFont_color_triggered()
|
||||
void MainWindow::on_addStep_clicked()
|
||||
{
|
||||
this->addNewStep();
|
||||
}
|
||||
}
|
||||
|
||||
@ -52,6 +52,7 @@ public:
|
||||
void saveFile();
|
||||
void newPath();
|
||||
void extractDialogue();
|
||||
bool m_handlingUndoRedo = false;
|
||||
|
||||
private slots:
|
||||
void on_pushButton_clicked();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user