How to Add Undo and Redo Functionality to a Qt Widget Application in C++


C++


In this article, we show how to add undo and redo functionality to a Qt widget application in C++.

These are common features seen in word processing software programs such as NotePad, WordPad, and Microsoft Word.

Main window with undo and redo menu items in a Qt widget in C++

Undo allows us to go back to the action previously committed. For example, if you deleted a statement, it will put the text back. If you added text, it will delete the text. It's a standard undo of what was previously done.

Redo does the action that was previously undone. So if you delete something, it will reappear.

We can add these functionalities into a main window program, so that we can utilize undo and redo functionalities.

So how do we add undo and redo functionality into a main window program?

So the first thing is you have to create a program of the QMainWindow class.

You then have to create menu items: Undo and Redo.

When you have these menu items, you can create an optional icon to go with them. For functionality, an icon isn't need, though.

So now for each menu item, click 'Go to Slot' and selected the QAction of 'triggered()'

This will create a function that will run when the menu item is selected.

The following code should be placed into the "mainwindow.cpp" file.



So the code is very basic.

Qt keeps the code very simple.

When the undo menu item is selected, the user's previous action is undone using the undo() function.

When the redo menu item is selected, the user's previous action is redone using the undo() function.

Now when you run this program, you'll see that any text you type into the text editor will be undone or redone according to these menu items selected.

And this is how to add undo and redo functionality in a Qt widget in C++.


Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...