I wish to create some FreeCAD objects when a new file is created. I only want to do this when a particular workbench is active.
Where in the implementation of a particular workbench could I add code to perform something when a new file is opened.
Code: Select all
class DocObserver(object):
def slotCreatedDocument(self, doc):
doc.addObject("Part::Feature", "Shape")
doc=DocObserver()
App.addDocumentObserver(doc)
Code: Select all
wb=Gui.activeWorkbench()
wb.GetClassName()
So I do that in the workbenches InitGui.py ?wmayer wrote: ↑Thu May 30, 2019 7:39 amUse the C++ class DocumentObserver and override its slotCreatedDocument. But note that the Document is passed as a const reference. So you can try to use const_cast to directly add a new object there which should be safe to do. The only thing you have to take care of is that the Label of the document is not yet defined at that time.
Here is a minimum example in Python only for demonstrating purposes:Code: Select all
class DocObserver(object): def slotCreatedDocument(self, doc): doc.addObject("Part::Feature", "Shape") doc=DocObserver() App.addDocumentObserver(doc)
Code: Select all
name 'DocObserver' is not defined
Traceback (most recent call last):
File "<string>", line 65, in Activated
Code: Select all
import FreeCAD
class DocObserver(object):
def slotCreatedDocument(self, doc):
mySphere = doc.addObject("Part::Sphere", "Globe")
mySphere.Radius = 100
class Astro_Workbench ( Workbench ):
"Astro workbench object"
def __init__(self):
self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/Astro/Resources/icons/AstroWorkbench.svg"
self.__class__.MenuText = "Astro"
self.__class__.ToolTip = "Astro workbench"
def Initialize(self):
def QT_TRANSLATE_NOOP(scope, text):
return text
import AstroCommands
commands=['AddRegionCommand' ]
toolbarcommands=['AddRegionCommand']
self.appendToolbar(QT_TRANSLATE_NOOP('Workbench','AstroTools'),toolbarcommands)
self.appendMenu('Astro',commands)
#FreeCADGui.addIconPath(":/icons")
FreeCADGui.addIconPath(FreeCAD.getResourceDir() + \
"Mod/Astro/Resources/icons")
FreeCADGui.addLanguagePath(":/translations")
#FreeCADGui.addPreferencePage(":/ui/openscadprefs-base.ui","OpenSCAD")
def Activated(self):
"This function is executed when the workbench is activated"
doc=DocObserver()
App.addDocumentObserver(doc)
return
def Deactivated(self):
"This function is executed when the workbench is deactivated"
App.removeDocumentObserver(doc)
return
def GetClassName(self):
"This is executed whenever the user right-clicks on screen"
return "Gui::PythonWorkbench"
"This function is executed when the workbench is deactivated"
return
def ContextMenu(self, recipient):
"This is executed whenever the user right-clicks on screen"
# "recipient" will be either "view" or "tree"
#self.appendContextMenu("My commands",self.list) # add commands to the context menu
Gui.addWorkbench(Astro_Workbench())