Code snippets

From FreeCAD Documentation
Jump to navigation Jump to search

This page contains examples, pieces, chunks of FreeCAD python code collected from users experiences and discussions on the forums. Read and use it as a start for your own scripts...

A typical file

Every module must contain, besides your main module file, an file, responsible for inserting the module in the main Gui. This is an example of a simple one.

class ScriptWorkbench (Workbench): MenuText = "Scripts" def Initialize(self): import Scripts # assuming is your module list = ["Script_Cmd"] # That list must contain command names, that can be defined in self.appendToolbar("My Scripts",list)


A typical module file

This is an example of a main module file, containing everything your module does. It is the file invoked by the previous example. You can have all your custom commands here.

import FreeCAD, FreeCADGui

class ScriptCmd: def Activated(self): # Here your write what your ScriptCmd does... FreeCAD.Console.PrintMessage("Hello, World!\n") def GetResources(self): return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'}

FreeCADGui.addCommand('Script_Cmd', ScriptCmd())

Import a new filetype

Making an importer for a new filetype in FreeCAD is easy. FreeCAD doesn't consider that you import data in an opened document, but rather that you simply can directly open the new filetype. So what you need to do is to add the new file extension to FreeCAD's list of known extensions, and write the code that will read the file and create the FreeCAD objects you want:

This line must be added to the file to add the new file extension to the list:

  1. Assumes is the file that has the code for opening and reading .ext files

FreeCAD.EndingAdd("Your new File Type (*.ext)","Import_Ext")

Then in the file:

def open(filename): doc=App.newDocument() # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects doc.recompute()

Adding a line

A line simply has 2 points.

import Part,PartGui doc=App.activeDocument()

  1. add a line element to the document and set its points

l=Part.line() l.setStartPoint((0.0,0.0,0.0)) l.setEndPoint((1.0,1.0,1.0)) doc.addObject("Part::Line","Line").Line_=l doc.recompute()

Adding a polygon

A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.

import Part,PartGui doc=App.activeDocument() n=list()

  1. create a 3D vector, set its coordinates and add it to the list

v=App.Vector(0,0,0) n.append(v) v=App.Vector(10,0,0) n.append(v)

  1. ... repeat for all nodes
  2. Create a polygon object and set its nodes

p=doc.addObject("Part::Polygon","Polygon") p.Nodes=n doc.recompute()

Adding and removing an object to a group

doc=App.activeDocument() grp=doc.addObject("App::DocumentObjectGroup", "Group") lin=doc.addObject("Part::Line", "Line") grp.addObject(lin) # adds the lin object to the group grp grp.removeObject(lin) # removes the lin object from the group grp

Note: You can even add other groups to a group...

Adding a Mesh

import Mesh doc=App.activeDocument()

  1. create a new empty mesh

m = Mesh.Mesh()

  1. build up box out of 12 facets

m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0) m.addFacet(0.0,0.0,0.0, 0.0,1.0,1.0, 0.0,1.0,0.0) m.addFacet(0.0,0.0,0.0, 1.0,0.0,0.0, 1.0,0.0,1.0) m.addFacet(0.0,0.0,0.0, 1.0,0.0,1.0, 0.0,0.0,1.0) m.addFacet(0.0,0.0,0.0, 0.0,1.0,0.0, 1.0,1.0,0.0) m.addFacet(0.0,0.0,0.0, 1.0,1.0,0.0, 1.0,0.0,0.0) m.addFacet(0.0,1.0,0.0, 0.0,1.0,1.0, 1.0,1.0,1.0) m.addFacet(0.0,1.0,0.0, 1.0,1.0,1.0, 1.0,1.0,0.0) m.addFacet(0.0,1.0,1.0, 0.0,0.0,1.0, 1.0,0.0,1.0) m.addFacet(0.0,1.0,1.0, 1.0,0.0,1.0, 1.0,1.0,1.0) m.addFacet(1.0,1.0,0.0, 1.0,1.0,1.0, 1.0,0.0,1.0) m.addFacet(1.0,1.0,0.0, 1.0,0.0,1.0, 1.0,0.0,0.0)

  1. scale to a edge langth of 100


  1. add the mesh to the active document

me=doc.addObject("Mesh::Feature","Cube") me.Mesh=m

Adding an arc or a circle

import Part doc = App.activeDocument() c = # create a circle object with undefined radius c.setRadius(10) f = doc.addObject("Part::Circle", "Circle") # create a document with a circle feature f.Circ = c # Assign the circle object to the Circ property doc.recompute()

Accessing and changing representation of an object

Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how the object appear, like color, linewidth, etc...

gad=Gui.activeDocument()   # access the active document containing all 
                           # view representations of the features in the
                           # corresponding App document 

v=gad.getObject("Cube")    # access the view representation to the Mesh feature 'Cube' 
v.ShapeColor               # prints the color to the console 
v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white

Observing mouse events in the 3D viewer via Python

The Inventor framework allows to add one or more callback nodes to the scenegraph of the viewer. By default in FreeCAD one callback node is installed per viewer which allows to add global or static C++ functions. In the appropriate Python binding some methods are provided to make use of this technique from within Python code.


#This class logs any mouse button events. As the registered callback function fires twice for 'down' and
#'up' events we need a boolean flag to handle this.
class ViewObserver:
	def logPosition(self, info):
		down = (info["State"] == "DOWN")
		pos = info["Position"]
		if (down):
			FreeCAD.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[0])+")\n")

o = ViewObserver()
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)

Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call


The following event types are supported

  • SoEvent -- all kind of events
  • SoButtonEvent -- all mouse button and key events
  • SoLocation2Event -- 2D movement events (normally mouse movements)
  • SoMotion3Event -- 3D movement events (normally spaceball)
  • SoKeyboradEvent -- key down and up events
  • SoMouseButtonEvent -- mouse button down and up events
  • SoSpaceballButtonEvent -- spaceball button down and up events

The Python function that can be registered with addEventCallback() expects a dictionary. Depending on the watched event the dictionary can contain different keys.

For all events it has the keys:

  • Type -- the name of the event type i.e. SoMouseEvent, SoLocation2Event, ...
  • Time -- the current time as string
  • Position -- a tuple of two integers, mouse position
  • ShiftDown -- a boolean, true if Shift was pressed otherwise false
  • CtrlDown -- a boolean, true if Ctrl was pressed otherwise false
  • AltDown -- a boolean, true if Alt was pressed otherwise false

For all button events, i.e. keyboard, mouse or spaceball events

  • State -- A string 'UP' if the button was up, 'DOWN' if it was down or 'UNKNOWN' for all other cases

For keyboard events:

  • Key -- a character of the pressed key

For mouse button event

  • Button -- The pressed button, could be BUTTON1, ..., BUTTON5 or ANY

For spaceball events:

  • Button -- The pressed button, could be BUTTON1, ..., BUTTON7 or ANY

And finally motion events:

  • Translation -- a tuple of three floats
  • Rotation -- a quaternion for the rotation, i.e. a tuple of four floats

Manipulate the scenegraph in Python

It is also possible to get and change the scenegraph in Python. Therefore you have to have the 'pivy' module -- a Python binding for Coin.

from pivy.coin import *                # load the pivy module
view = Gui.ActiveDocument.ActiveView   # get the active viewer
root = view.getSceneGraph()            # the root is an SoSeparator node

The Python API of pivy is created by using the tool SWIG. As we use in FreeCAD some self-written nodes you cannot create them directly in Python. However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with

type = SoType.fromName("SoFCSelection")
node = type.createInstance()