Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Undo an edit and reload the document

Group an edit into a named transaction, undo and redo it, then save the document, close it, open it again, and read the values back.

Generated page. tools/userdocs.py writes it from tools/workflows/03_undo_and_persistence.py. Edit the workflow, not this page; python3 tools/userdocs.py --check fails when the two disagree.

Requires: the FreeCAD facade; a writable temporary directory.

1. Build a document

import tempfile
doc = FreeCAD.newDocument("Undoable")

part = doc.addObject("App::FeaturePython", "Part")
part.addProperty("App::PropertyLength", "Length", "Base", "Overall length")
part.addProperty("App::PropertyEnumeration", "Finish", "Base", "Surface finish")
part.Finish = ["As machined", "Anodised"]
part.Length = "10 mm"
doc.recompute()
Read backValue
part.Length10 mm

2. One transaction, one undo

Everything between openTransaction and commitTransaction is one undoable step. A workbench wraps each command in exactly this, which is why undo never lands in the middle of a command.

doc.openTransaction("Resize")
part.Length = "25 mm"
part.Finish = "Anodised"
doc.commitTransaction()
doc.recompute()
Read backValue
part.Length after the edit25 mm
part.Finish after the editAnodised
doc.undo(); doc.recompute()
Read backValue
part.Length after undo10 mm
part.Finish after undoAs machined
doc.redo(); doc.recompute()
Read backValue
part.Length after redo25 mm

3. Save and reload

saveAs writes the document format; open reads it into a new document with the same names and property values. The path is a temporary file, so it is not shown.

import os
path = os.path.join(tempfile.mkdtemp(prefix="ferrocad-userdocs-"), "undoable.ferrocad")
doc.saveAs(path)
doc_name = doc.Name
FreeCAD.closeDocument(doc_name)
Read backValue
Open documents after close[]
reopened = FreeCAD.open(path)
reloaded = reopened.getObject("Part")
Read backValue
Reloaded namePart
Reloaded Length25 mm
Reloaded FinishAnodised

4. Clean up

import shutil
FreeCAD.closeDocument(reopened.Name)
shutil.rmtree(os.path.dirname(path))
Read backValue
Open documents[]