4

I am sub-classing QPlainText edit and I would like to be able to intercept undo / redo commands so that I can implement custom functionality.

I realise that I can disable the undo / redo capability with setUndoRedoEnabled and I can detect Ctrl+Z and Ctrl+Y key presses. However, this doesn't seem like the best cross platform way of doing it.

Any advice?

Alan Spark
  • 8,152
  • 8
  • 56
  • 91
  • 3
    In fact you don't want to intercept literally `Ctrl+Z` -- in your `keyPressEvent` complare your `QKeyEvent` against `QKeySequence::Undo`: `if (event->matches(QKeySequence::Undo)) { ... }`. – peppe Oct 31 '16 at 17:21
  • Thanks, this is just what I was looking for. – Alan Spark Nov 02 '16 at 07:24

2 Answers2

1

You simply need to reimplement the slots :

class MyTestEdit : public QPlainTextEdit {
    Q_OBJECT

public slots:
    void redo() { ... }
    void undo() { ... }

};

Signal and slots are exactly like other c++ methods. If you reimplement them in a subclass, they will be called instead of the the parent's.

BlueMagma
  • 2,392
  • 1
  • 22
  • 46
  • 1
    It's a good idea to get into the habit of adding `Q_DECL_OVERRIDE` so that (with a C++11 compiler), you can get an error if you get the function signature wrong. – Toby Speight Oct 31 '16 at 17:05
  • Sorry, no: `undo` and `redo` are not virtual functions in QPlainTextEdit. `Q_DECL_OVERRIDE` will trigger a compile error. – peppe Oct 31 '16 at 17:13
  • That having been said: this trick *might* actually work (without the `override` keyword, of course) because of the virtuality of slots when using the old connection syntax. But I don't think a signal and slot is used to trigger `undo` in this scenario, rather an "ordinary" key match. – peppe Oct 31 '16 at 17:21
  • @peppe : thank you, that'll teach me to listen to people without making sure – BlueMagma Oct 31 '16 at 18:12
0

I think you can use "QUndoStack" for this.

In you subclass's constructor (constructor is better), call a method that creates Undo and Redo actions to handle for your class.

Prototype:

//Call this function to register undo and redo actions.

Void methodCrteaesUndoandRedoActions()
{

QUndoStack unStack = new QUndoStack (this);

QAction *undoAct = undoStack->createUndoAction(this);
QAction *RedoAct = undoStack->createRedoAction(this);

}

//Implement below functions in your class to handle the business.

void undo()
{



}

void redo()
{



}
Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34