/python/pyside_undo.py

https://bitbucket.org/ikeikeikeike/undo-redo
Python | 59 lines | 39 code | 18 blank | 2 comment | 1 complexity | e5632885eb8e19b1a0b77194158e94d7 MD5 | raw file
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from PySide.QtGui import QUndoCommand, QUndoStack
  4. class MyDocument(object):
  5. def __init__(self):
  6. self.document = []
  7. def __repr__(self):
  8. return repr(self.document)
  9. def chop(self):
  10. self.document = self.document[:-1]
  11. def append(self, item):
  12. self.document.append(item)
  13. class MyCommand(QUndoCommand):
  14. def __init__(self, doc, *args, **kwargs):
  15. super(type(self), self).__init__(*args, **kwargs)
  16. self.document = doc
  17. def undo(self):
  18. self.document.chop()
  19. print("undo: {0}, undo-text: {1}".format(self.document, self.text()))
  20. def redo(self):
  21. self.document.append(self.text())
  22. print("redo: {0}, redo-text: {1}".format(self.document, self.text()))
  23. if __name__ == '__main__':
  24. stack1 = QUndoStack()
  25. document1 = MyDocument()
  26. c = MyCommand(document1)
  27. c.setText("comamnd1")
  28. stack1.push(c)
  29. print(stack1.count())
  30. c = MyCommand(document1)
  31. c.setText("comamnd2")
  32. stack1.push(c)
  33. print(stack1.count())
  34. stack1.undo()
  35. stack1.undo()
  36. stack1.redo()
  37. print(stack1.count())
  38. c = MyCommand(document1)
  39. c.setText("comamnd3")
  40. stack1.push(c) # command2 gets deleted
  41. print(stack1.count())