Code snippets/id

Introduction
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 InitGui.py file
Every module must contain, besides your main module file, an InitGui.py file, responsible for inserting the module in the main Gui. This is an example of a simple one.

top

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

top

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 InitGui.py file to add the new file extension to the list:

Then in the Import_Ext.py file:

To export your document to some new filetype works the same way, except that you use: FreeCAD.addExportType("Your new File Type (*.ext)","Export_Ext")

top

Add a line
A line simply has 2 points.

top

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

top

Add and remove an object to/from a group
Note: You can even add other groups to a group...

top

Add a Mesh
top

Add an arc or a circle
top

Access and change the representation of an object
Each object in a FreeCAD document has an associated view representation object that stores all the parameters that define how that object appears: i.e. color, linewidth, etc... See also List the components of an object snippet below

top

Replace the form of mouse with one image
top

Replace the form of mouse with one image (cross) include
The image is created by Gimp exported in a .XPM file. Copy and use the code between the bracket "{" code to copy  "}"

top

Observe 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.

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)
 * SoKeyboardEvent -- 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: For all button events, i.e. keyboard, mouse or spaceball events For keyboard events: For mouse button event For spaceball events: And finally motion events:
 * 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
 * State -- A string 'UP' if the button was up, 'DOWN' if it was down or 'UNKNOWN' for all other cases
 * Key -- a character of the pressed key
 * Button -- The pressed button, could be BUTTON1, ..., BUTTON5 or ANY
 * Button -- The pressed button, could be BUTTON1, ..., BUTTON7 or ANY
 * Translation -- a tuple of three floats
 * Rotation -- a quaternion for the rotation, i.e. a tuple of four floats

top

Display keys pressed and Events command
This macro displays in the report view the keys pressed and all events command

top

Manipulate the scenegraph in Python
It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.

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

top

Add and remove objects to/from the scenegraph
Adding new nodes to the scenegraph can be done this way. Take care of always adding a SoSeparator to contain the geometry, coordinates and material info of a same object. The following example adds a red line from (0,0,0) to (10,0,0):

To remove it, simply issue:

top

Save the sceneGraph in 3 series of 36 files
View the code snippet by expanding this section

top

Add custom widgets to the interface
You can create custom widgets with Qt designer, transform them into a python script, and then load them into the FreeCAD interface with PySide.

The python code produced by the Ui python compiler (the tool that converts qt-designer .ui files into python code) generally looks like this (it is simple, you can also code it directly in python):

Then, all you need to do is to create a reference to the FreeCAD Qt window, insert a custom widget into it, and "transform" this widget into yours with the Ui code we just made:

top

Add a Tab to the Combo View
The following code allows you to add a tab to the Combo view, separate from the preexisting "Model" and "Tasks" tabs. It also uses the module to load an UI file directly in that tab.

top

Enable or disable a window
This script give the ability to manipulate the UI from the Python console to show/hide different components in the FreeCAD interface such as:
 * Report view
 * Tree view
 * Property view
 * Selection view
 * Combo View
 * Python console
 * draftToolbar

top

Open a custom webpage
top

Get the HTML contents of an opened webpage
top

Retrieve the coordinates of 3 selected points or objects
top

List all objects
top

List the dimensions of an object, given its name
top

Function resident with the mouse click action
Here with SelObserver on a object select

Other example with ViewObserver on a object select or view

top

Find/select all elements below the cursor
top

List the components of an object
This function list the components of an object and extracts:
 * this object its XYZ coordinates,
 * its edges and their lengths center of mass and coordinates
 * its faces and their center of mass
 * its faces and their surfaces and coordinates

top

List the PropertiesList
top

Add a single Property Comment
top

Search and data extraction
Examples of research and decoding information on an object.

Each section is independently and is separated by "############" can be copied directly into the Python console, or in a macro or use this macro. The description of the macro in the commentary.

Displaying it in the "Report View" window (View > Views > Report view)

top

Manual search of an element with label
Note: Usually the angles are given in Radian. To convert them:


 * 1) angle in Degrees to Radians :
 * 2) *Angle in radian = pi * (angle in degree) / 180
 * 3) *Angle in radian = math.radians(angle in degree)
 * 4) angle in Radians to Degrees :
 * 5) *Angle in degree = 180 * (angle in radian) / pi
 * 6) *Angle in degree = math.degrees(angle in radian)

top

Cartesian coordinates
This code displays the Cartesian coordinates of the selected item.

Change the value of "numberOfPoints" if you want a different number of points (precision)

Other method display on "Int" and "Float"

top

Select all objects in the document
top

Select a face of an object by Name object and Face number
top

Get the normal vector of a face of an object by Name object and number Face (r.Q)
top

Get the normal vector of a face of an object by Name object and number of Face
top

Get the normal vector of an object selected and number of Face
top

Get the normal vector on the surface
This example show how to find normal vector on the surface by find the u,v parameters of one point on the surface and use u,v parameters to find normal vector

top

Get the normal vector of a surface from a STL file
top

Create one object to the position of the Camera
here same code simplified

top

Read And write one Expression
you are done then run for quit:

top

Create a Sketch on a Surface in PartDesign
This snippet can be useful, if you want to create a sketch on a surface in PartDesign from inside a macro. Note, that body might be None, if no active body is selected and that the Selection might be empty.

top

How to Simulate a Mouse Click at a given Coordinate
The position is relative to the GL widget. See forum thread.

top

Related

 * Scripted objects
 * Macros

top