Difference between revisions of "Code snippets"

From FreeCAD Documentation
Jump to: navigation, search
m (minor)
(adding "List the PropertiesList")
Line 6: Line 6:
 
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.  
 
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.  
  
 +
<syntaxhighlight>
 
  class ScriptWorkbench (Workbench):  
 
  class ScriptWorkbench (Workbench):  
 
     MenuText = "Scripts"
 
     MenuText = "Scripts"
Line 14: Line 15:
 
          
 
          
 
  Gui.addWorkbench(ScriptWorkbench())
 
  Gui.addWorkbench(ScriptWorkbench())
 +
</syntaxhighlight>
  
 
=== A typical module file ===
 
=== A typical module file ===
Line 19: Line 21:
 
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.
 
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.
  
 +
<syntaxhighlight>
 
  import FreeCAD, FreeCADGui  
 
  import FreeCAD, FreeCADGui  
 
   
 
   
Line 29: Line 32:
 
        
 
        
 
  FreeCADGui.addCommand('Script_Cmd', ScriptCmd())
 
  FreeCADGui.addCommand('Script_Cmd', ScriptCmd())
 +
</syntaxhighlight>
  
 
=== Import a new filetype ===
 
=== Import a new filetype ===
Line 35: Line 39:
  
 
This line must be added to the InitGui.py file to add the new file extension to the list:
 
This line must be added to the InitGui.py file to add the new file extension to the list:
 
+
<syntaxhighlight>
 
  # Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
 
  # Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
 
  FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")  
 
  FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")  
 +
</syntaxhighlight>
  
 
Then in the Import_Ext.py file:
 
Then in the Import_Ext.py file:
  
 +
<syntaxhighlight>
 
  def open(filename):  
 
  def open(filename):  
 
     doc=App.newDocument()
 
     doc=App.newDocument()
 
     # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
 
     # here you do all what is needed with filename, read, classify data, create corresponding FreeCAD objects
 
     doc.recompute()
 
     doc.recompute()
 +
</syntaxhighlight>
  
 
To export your document to some new filetype works the same way, except that you use:
 
To export your document to some new filetype works the same way, except that you use:
Line 52: Line 59:
  
 
A line simply has 2 points.
 
A line simply has 2 points.
 +
<syntaxhighlight>
  
 
  import Part,PartGui  
 
  import Part,PartGui  
Line 61: Line 69:
 
  doc.addObject("Part::Feature","Line").Shape=l.toShape()  
 
  doc.addObject("Part::Feature","Line").Shape=l.toShape()  
 
  doc.recompute()
 
  doc.recompute()
 +
</syntaxhighlight>
  
 
=== Adding a polygon ===
 
=== Adding a polygon ===
Line 66: Line 75:
 
A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.
 
A polygon is simply a set of connected line segments (a polyline in AutoCAD). It doesn't need to be closed.
  
 +
<syntaxhighlight>
 
  import Part,PartGui  
 
  import Part,PartGui  
 
  doc=App.activeDocument()
 
  doc=App.activeDocument()
Line 79: Line 89:
 
  p.Nodes=n  
 
  p.Nodes=n  
 
  doc.recompute()
 
  doc.recompute()
 +
</syntaxhighlight>
  
 
=== Adding and removing an object to a group ===
 
=== Adding and removing an object to a group ===
  
 +
<syntaxhighlight>
 
  doc=App.activeDocument()  
 
  doc=App.activeDocument()  
 
  grp=doc.addObject("App::DocumentObjectGroup", "Group")  
 
  grp=doc.addObject("App::DocumentObjectGroup", "Group")  
Line 87: Line 99:
 
  grp.addObject(lin) # adds the lin object to the group grp
 
  grp.addObject(lin) # adds the lin object to the group grp
 
  grp.removeObject(lin) # removes the lin object from the group grp
 
  grp.removeObject(lin) # removes the lin object from the group grp
 +
</syntaxhighlight>
  
 
Note: You can even add other groups to a group...
 
Note: You can even add other groups to a group...
Line 92: Line 105:
 
=== Adding a Mesh ===
 
=== Adding a Mesh ===
  
 +
<syntaxhighlight>
 
  import Mesh
 
  import Mesh
 
  doc=App.activeDocument()
 
  doc=App.activeDocument()
Line 114: Line 128:
 
  me=doc.addObject("Mesh::Feature","Cube")
 
  me=doc.addObject("Mesh::Feature","Cube")
 
  me.Mesh=m
 
  me.Mesh=m
 +
</syntaxhighlight>
  
 
=== Adding an arc or a circle ===
 
=== Adding an arc or a circle ===
  
 +
<syntaxhighlight>
 
  import Part
 
  import Part
 
  doc = App.activeDocument()
 
  doc = App.activeDocument()
Line 124: Line 140:
 
  f.Shape = c.toShape() # Assign the circle shape to the shape property  
 
  f.Shape = c.toShape() # Assign the circle shape to the shape property  
 
  doc.recompute()
 
  doc.recompute()
 +
</syntaxhighlight>
  
 
=== Accessing and changing representation of an object ===
 
=== Accessing and changing representation of an object ===
Line 129: Line 146:
 
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...
 
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...
  
 +
<syntaxhighlight>
 
  gad=Gui.activeDocument()  # access the active document containing all  
 
  gad=Gui.activeDocument()  # access the active document containing all  
 
                           # view representations of the features in the
 
                           # view representations of the features in the
Line 136: Line 154:
 
  v.ShapeColor              # prints the color to the console  
 
  v.ShapeColor              # prints the color to the console  
 
  v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white
 
  v.ShapeColor=(1.0,1.0,1.0) # sets the shape color to white
 +
</syntaxhighlight>
  
 
=== Observing mouse events in the 3D viewer via Python ===
 
=== Observing mouse events in the 3D viewer via Python ===
Line 141: Line 160:
 
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.
 
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.
  
 +
<syntaxhighlight>
 
  App.newDocument()
 
  App.newDocument()
 
  v=Gui.activeDocument().activeView()
 
  v=Gui.activeDocument().activeView()
Line 155: Line 175:
 
  o = ViewObserver()
 
  o = ViewObserver()
 
  c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
 
  c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
 +
</syntaxhighlight>
  
 
Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call
 
Now, pick somewhere on the area in the 3D viewer and observe the messages in the output window. To finish the observation just call
  
 +
<syntaxhighlight>
 
  v.removeEventCallback("SoMouseButtonEvent",c)
 
  v.removeEventCallback("SoMouseButtonEvent",c)
 +
</syntaxhighlight>
  
 
The following event types are supported
 
The following event types are supported
Line 199: Line 222:
 
It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.
 
It is also possible to get and change the scenegraph in Python, with the 'pivy' module -- a Python binding for Coin.
  
 +
<syntaxhighlight>
 
  from pivy.coin import *                # load the pivy module
 
  from pivy.coin import *                # load the pivy module
 
  view = Gui.ActiveDocument.ActiveView  # get the active viewer
 
  view = Gui.ActiveDocument.ActiveView  # get the active viewer
Line 204: Line 228:
 
  root.addChild(SoCube())
 
  root.addChild(SoCube())
 
  view.fitAll()
 
  view.fitAll()
 +
</syntaxhighlight>
  
 
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.
 
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
 
However, it is possible to create a node by its internal name. An instance of the type 'SoFCSelection' can be created with
  
 +
<syntaxhighlight>
 
  type = SoType.fromName("SoFCSelection")
 
  type = SoType.fromName("SoFCSelection")
 
  node = type.createInstance()
 
  node = type.createInstance()
 +
</syntaxhighlight>
  
 
=== Adding and removing objects to/from the scenegraph ===
 
=== Adding and removing objects to/from the scenegraph ===
Line 215: Line 242:
 
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):
 
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):
  
 +
<syntaxhighlight>
 
  from pivy import coin
 
  from pivy import coin
 
  sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
 
  sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
Line 229: Line 257:
 
  no.addChild(li)
 
  no.addChild(li)
 
  sg.addChild(no)
 
  sg.addChild(no)
 +
</syntaxhighlight>
  
 
To remove it, simply issue:
 
To remove it, simply issue:
  
 +
<syntaxhighlight>
 
  sg.removeChild(no)
 
  sg.removeChild(no)
 +
</syntaxhighlight>
  
 
===Adding custom widgets to the interface===
 
===Adding custom widgets to the interface===
Line 240: Line 271:
 
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):
 
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):
  
 +
<syntaxhighlight>
 
  class myWidget_Ui(object):
 
  class myWidget_Ui(object):
 
   def setupUi(self, myWidget):
 
   def setupUi(self, myWidget):
Line 252: Line 284:
 
     myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
 
     myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
 
     self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))
 
     self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))
 +
</syntaxhighlight>
  
 
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:
 
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:
  
 +
<syntaxhighlight>
 
   app = QtGui.qApp
 
   app = QtGui.qApp
 
   FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
 
   FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
Line 261: Line 295:
 
   myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
 
   myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
 
   FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
 
   FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window
 +
</syntaxhighlight>
  
 
===Adding a Tab to the Combo View===
 
===Adding a Tab to the Combo View===
Line 266: Line 301:
 
The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.
 
The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.
  
 +
<syntaxhighlight>
 
  from PyQt4 import QtGui,QtCore
 
  from PyQt4 import QtGui,QtCore
 
  from PyQt4 import uic
 
  from PyQt4 import uic
Line 296: Line 332:
 
   
 
   
 
  #tab.removeTab(2)
 
  #tab.removeTab(2)
 +
</syntaxhighlight>
  
 
===Opening a custom webpage===
 
===Opening a custom webpage===
  
 +
<syntaxhighlight>
 
  import WebGui
 
  import WebGui
 
  WebGui.openBrowser("http://www.example.com")
 
  WebGui.openBrowser("http://www.example.com")
 +
</syntaxhighlight>
  
 
===Getting the HTML contents of an opened webpage===
 
===Getting the HTML contents of an opened webpage===
  
 +
<syntaxhighlight>
 
  from PyQt4 import QtGui,QtWebKit
 
  from PyQt4 import QtGui,QtWebKit
 
  a = QtGui.qApp
 
  a = QtGui.qApp
Line 310: Line 350:
 
  html = unicode(v.toHtml())
 
  html = unicode(v.toHtml())
 
  print html
 
  print html
 +
</syntaxhighlight>
  
 
===Retrieve and use the coordinates of 3 selected points or objects===
 
===Retrieve and use the coordinates of 3 selected points or objects===
<pre>
+
 
 +
<syntaxhighlight>
 
# -*- coding: utf-8 -*-
 
# -*- coding: utf-8 -*-
 
# the line above to put the accentuated in the remarks
 
# the line above to put the accentuated in the remarks
Line 336: Line 378:
  
 
   Console.PrintMessage(str(pt[1]) + "\r\n")
 
   Console.PrintMessage(str(pt[1]) + "\r\n")
</pre>
+
</syntaxhighlight>
  
 
===List all objects===
 
===List all objects===
<pre>
+
 
 +
<syntaxhighlight>
 
# -*- coding: utf-8 -*-
 
# -*- coding: utf-8 -*-
 
# List all objects
 
# List all objects
Line 351: Line 394:
 
     print name            # Displays the name of the object
 
     print name            # Displays the name of the object
 
#doc.removeObject("Ortho") # Clears the designated object
 
#doc.removeObject("Ortho") # Clears the designated object
</pre>
+
</syntaxhighlight>
  
 
===Function resident with the mouse click action===
 
===Function resident with the mouse click action===
<pre>
+
 
 +
<syntaxhighlight>
 
# -*- coding: utf-8 -*-
 
# -*- coding: utf-8 -*-
 
# causes an action to the mouse click on an object
 
# causes an action to the mouse click on an object
Line 377: Line 421:
 
FreeCADGui.Selection.addObserver(s)    # install the function mode resident
 
FreeCADGui.Selection.addObserver(s)    # install the function mode resident
 
#FreeCADGui.Selection.removeObserver(s) # Uninstall the resident function
 
#FreeCADGui.Selection.removeObserver(s) # Uninstall the resident function
</pre>
+
</syntaxhighlight>
  
 
===List the components of an object===
 
===List the components of an object===
<pre>
+
 
 +
<syntaxhighlight>
 
# -*- coding: utf-8 -*-
 
# -*- coding: utf-8 -*-
 
# This function list the components of an object
 
# This function list the components of an object
Line 434: Line 479:
  
 
detail()
 
detail()
</pre>
+
</syntaxhighlight>
 +
 
 +
===List the PropertiesList===
 +
 
 +
<syntaxhighlight>
 +
o = App.ActiveDocument.ActiveObject
 +
op = o.PropertiesList
 +
for p in op:
 +
    print "Property: ", p, " Value: ", o.getPropertyByName (p)
 +
</syntaxhighlight>
  
 
{{docnav|Embedding FreeCAD|Line drawing function}}
 
{{docnav|Embedding FreeCAD|Line drawing function}}

Revision as of 14:06, 19 April 2014

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.

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

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.

 import FreeCAD, FreeCADGui 
 
 class ScriptCmd: 
    def Activated(self): 
        # Here your write what your ScriptCmd does...
        FreeCAD.Console.PrintMessage('Hello, World!')
    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 InitGui.py file to add the new file extension to the list:

 # Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
 FreeCAD.addImportType("Your new File Type (*.ext)","Import_Ext")

Then in the Import_Ext.py 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()

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") 

Adding a line

A line simply has 2 points.

 import Part,PartGui 
 doc=App.activeDocument() 
 # add a line element to the document and set its points 
 l=Part.Line()
 l.StartPoint=(0.0,0.0,0.0)
 l.EndPoint=(1.0,1.0,1.0)
 doc.addObject("Part::Feature","Line").Shape=l.toShape() 
 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() 
 # 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) 
 #... repeat for all nodes 
 # 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::Feature", "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()
 # create a new empty mesh
 m = Mesh.Mesh()
 # 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)
 # scale to a edge langth of 100
 m.scale(100.0)
 # 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 = Part.Circle() 
 c.Radius=10.0  
 f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature 
 f.Shape = c.toShape() # Assign the circle shape to the shape 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.

 App.newDocument()
 v=Gui.activeDocument().activeView()
 
 #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.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[1])+")\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

 v.removeEventCallback("SoMouseButtonEvent",c)

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:

  • 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, with 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
 root.addChild(SoCube())
 view.fitAll()

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()

Adding and removing 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):

 from pivy import coin
 sg = Gui.ActiveDocument.ActiveView.getSceneGraph()
 co = coin.SoCoordinate3()
 pts = [[0,0,0],[10,0,0]]
 co.point.setValues(0,len(pts),pts)
 ma = coin.SoBaseColor()
 ma.rgb = (1,0,0)
 li = coin.SoLineSet()
 li.numVertices.setValue(2)
 no = coin.SoSeparator()
 no.addChild(co)
 no.addChild(ma)
 no.addChild(li)
 sg.addChild(no)

To remove it, simply issue:

 sg.removeChild(no)

Adding 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 PyQt4.

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):

 class myWidget_Ui(object):
  def setupUi(self, myWidget):
    myWidget.setObjectName("my Nice New Widget")
    myWidget.resize(QtCore.QSize(QtCore.QRect(0,0,300,100).size()).expandedTo(myWidget.minimumSizeHint())) # sets size of the widget
 
    self.label = QtGui.QLabel(myWidget) # creates a label
    self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size
    self.label.setObjectName("label") # sets its name, so it can be found by name
 
  def retranslateUi(self, draftToolbar): # built-in QT function that manages translations of widgets
    myWidget.setWindowTitle(QtGui.QApplication.translate("myWidget", "My Widget", None, QtGui.QApplication.UnicodeUTF8))
    self.label.setText(QtGui.QApplication.translate("myWidget", "Welcome to my new widget!", None, QtGui.QApplication.UnicodeUTF8))

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:

  app = QtGui.qApp
  FCmw = app.activeWindow() # the active qt window, = the freecad window since we are inside it
  myNewFreeCADWidget = QtGui.QDockWidget() # create a new dckwidget
  myNewFreeCADWidget.ui = myWidget_Ui() # load the Ui script
  myNewFreeCADWidget.ui.setupUi(myNewFreeCADWidget) # setup the ui
  FCmw.addDockWidget(QtCore.Qt.RightDockWidgetArea,myNewFreeCADWidget) # add the widget to the main window

Adding a Tab to the Combo View

The following code allows you to add a tab to the FreeCAD ComboView, besides the "Project" and "Tasks" tabs. It also uses the uic module to load an ui file directly in that tab.

 from PyQt4 import QtGui,QtCore
 from PyQt4 import uic
 #from PySide import QtGui,QtCore
 
 def getMainWindow():
    "returns the main window"
    # using QtGui.qApp.activeWindow() isn't very reliable because if another
    # widget than the mainwindow is active (e.g. a dialog) the wrong widget is
    # returned
    toplevel = QtGui.qApp.topLevelWidgets()
    for i in toplevel:
        if i.metaObject().className() == "Gui::MainWindow":
            return i
    raise Exception("No main window found")
 
 def getComboView(mw):
    dw=mw.findChildren(QtGui.QDockWidget)
    for i in dw:
        if str(i.objectName()) == "Combo View":
            return i.findChild(QtGui.QTabWidget)
    raise Exception("No tab widget found")
 
 mw = getMainWindow()
 tab = getComboView(getMainWindow())
 tab2=QtGui.QDialog()
 tab.addTab(tab2,"A Special Tab")
 uic.loadUi("/myTaskPanelforTabs.ui",tab2)
 tab2.show()
 
 #tab.removeTab(2)

Opening a custom webpage

 import WebGui
 WebGui.openBrowser("http://www.example.com")

Getting the HTML contents of an opened webpage

 from PyQt4 import QtGui,QtWebKit
 a = QtGui.qApp
 mw = a.activeWindow()
 v = mw.findChild(QtWebKit.QWebFrame)
 html = unicode(v.toHtml())
 print html

Retrieve and use the coordinates of 3 selected points or objects

# -*- coding: utf-8 -*-
# the line above to put the accentuated in the remarks
# If this line is missing, an error will be returned
# extract and use the coordinates of 3 objects selected
import Part, FreeCAD, math, PartGui, FreeCADGui
from FreeCAD import Base, Console
sel = FreeCADGui.Selection.getSelection() # " sel " contains the items selected
if len(sel)!=3 :
  # If there are no 3 objects selected, an error is displayed in the report view
  # The \r and \n at the end of line mean return and the newline CR + LF.
  Console.PrintError("Select 3 points exactly\r\n")
else :
  points=[]
  for obj in sel:
    points.append(obj.Shape.BoundBox.Center)

  for pt in points:
    # display of the coordinates in the report view
    Console.PrintMessage(str(pt.x)+"\r\n")
    Console.PrintMessage(str(pt.y)+"\r\n")
    Console.PrintMessage(str(pt.z)+"\r\n")

  Console.PrintMessage(str(pt[1]) + "\r\n")

List all objects

# -*- coding: utf-8 -*-
# List all objects
App.ActiveDocument=App.getDocument("Unnamed")
doc = FreeCAD.ActiveDocument
objs = FreeCAD.ActiveDocument.Objects
#print objs
#print len(FreeCAD.ActiveDocument.Objects)
for obj in objs:
    name = obj.Name        # list the names of the objects
    print name             # Displays the name of the object
#doc.removeObject("Ortho") # Clears the designated object

Function resident with the mouse click action

# -*- coding: utf-8 -*-
# causes an action to the mouse click on an object
# This function remains resident (in memory) with the function "addObserver(s)"
# "removeObserver(s) # Uninstalls the resident function
class SelObserver:
    def addSelection(self,doc,obj,sub,pnt):  # Selection
        print "addSelection"
        print doc                            # Name of the document
        print obj                            # Name of the object
        print sub                            # The part of the object name
        print pnt                            # Coordinates of the object

    def removeSelection(self,doc,obj,sub):   # Delete the selected object
        print "removeSelection"
    def setSelection(self,doc):              # Selection in ComboView
        print "setSelection"
    def clearSelection(self,doc):            # If click on the screen, clear the selection
        print "clearSelection"               # If click on another object, clear the previous object

s=SelObserver()
FreeCADGui.Selection.addObserver(s)    # install the function mode resident
#FreeCADGui.Selection.removeObserver(s) # Uninstall the resident function

List the components of an object

# -*- coding: utf-8 -*-
# This function list the components of an object
# and extract this object its XYZ coordinates,
# its edges and their lengths
# its faces and their surfaces

import Draft,Part
def detail():
    sel = FreeCADGui.Selection.getSelection()   # Select an object
    if len(sel) != 0:                           # If there is a selection then
        Vertx=[]
        Edges=[]
        Faces=[]
        compt_V=0
        compt_E=0
        compt_F=0
        pas    =0

        for num in sel[0].Shape.Vertexes:       # Search the XYZ coordinates and displays
            compt_V+=1
            if pas == 0:                        
                Vertx.append("X1: "+str(num.Point[0]))
                Vertx.append("Y1: "+str(num.Point[1]))
                Vertx.append("Z1: "+str(num.Point[2]))
                print "X1: "+str(num.Point[0])," Y1: "+str(num.Point[1])," Z1: "+str(num.Point[2]),
                pas=1
            else:
                Vertx.append("X2: "+str(num.Point[0]))
                Vertx.append("Y2: "+str(num.Point[1]))
                Vertx.append("Z2: "+str(num.Point[2]))
                print " X2: "+str(num.Point[0])," Y2: "+str(num.Point[1])," Z2: "+str(num.Point[2])
                pas=0
        print "Number of Vertex       : ", compt_V
        perimetre = 0.0   
        EdgesLong = []

        for j in enumerate(sel[0].Shape.Edges):                                     # Search the "Edges" and their lengths
            compt_E+=1
            Edges.append("Edge%d" % (j[0]+1))
            EdgesLong.append(str(sel[0].Shape.Edges[compt_E-1].Length))
            perimetre += (sel[0].Shape.Edges[compt_E-1].Length)                      # calculates the perimeter
            print "Edge",str(compt_E)," > ",str(sel[0].Shape.Edges[compt_E-1].Length)# Displays the "Edge" and its length
        print "Perimeter of the form  : ",perimetre

        FacesSurf = []
        for j in enumerate(sel[0].Shape.Faces):                                      # Search the "Faces" and their surface
            compt_F+=1
            Faces.append("Face%d" % (j[0]+1))
            FacesSurf.append(str(sel[0].Shape.Faces[compt_F-1].Area))
            print "Face",str(compt_F)," > ",sel[0].Shape.Faces[compt_F-1].Area       # Displays 'Face' and its surface
        print "Surface of the form    : ",sel[0].Shape.Area                          # Displays the total surface of the form

detail()

List the PropertiesList

o = App.ActiveDocument.ActiveObject
op = o.PropertiesList
for p in op:
    print "Property: ", p, " Value: ", o.getPropertyByName (p)
Available translations of this page: Flag-cn.jpg Flag-es.jpg Flag-fr.jpg Flag-it.jpg Flag-jp.jpg Template:Se