Tuesday, 19 April 2022

Enhanced GTK+3 TextBuffer

This post shows an enhanced version of GTK+3 TextBuffer which provides Undo(Ctrl-Z) and Redo(Ctrl-Y) functions.


  1. Define a class encTextBuffer based on Gtk.DrawingTextBuffer.
  2. Add the event handler insert-text. This handler will be activated whenever text are added to the buffer.
  3. Add the event handler delete-range. This handler will be activated whenever text are deleted from the buffer.
  4. Define two stacks, UndoStack and RedoStack, to keep the operations and data for undo and redo respectively.
  5. Define two methods, undo and redo, which can be called externally by other classes.
  6. The textview can include this enhanced textbuffer by:
    self.txtBuffer = encTextBuffer()
    self.txtEditor = Gtk.TextView(buffer=self.txtBuffer)
  7. The textview containing this encTextBuffer should add a handler key-press-event that can capture the keys Ctrl-Z and Ctrl-Y for calling the Undo and Redo operations. See the following line:
    self.txtEditor.connect("key-press-event", self.keyCapture)

Source Code




No comments:

Post a Comment