Code snippets: Difference between revisions

From FreeCAD Documentation
m (65 revisions)
No edit summary
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.


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


=== A typical module file ===
=== A typical module file ===
Line 23: Line 19:
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.


import FreeCAD, FreeCADGui
<code python>
import FreeCAD, FreeCADGui
class ScriptCmd:

class ScriptCmd:
def Activated(self):
def Activated(self):
# Here your write what your ScriptCmd does...
# Here your write what your ScriptCmd does...
Line 32: Line 27:
def GetResources(self):
def GetResources(self):
return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'}
return {'Pixmap' : 'path_to_an_icon/myicon.png', 'MenuText': 'Short text', 'ToolTip': 'More detailed text'}
FreeCADGui.addCommand('Script_Cmd', ScriptCmd())
FreeCADGui.addCommand('Script_Cmd', ScriptCmd())
</code>


=== Import a new filetype ===
=== Import a new filetype ===
Line 43: Line 36:
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:


# 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")
<code python>
# Assumes Import_Ext.py is the file that has the code for opening and reading .ext files
FreeCAD.EndingAdd("Your new File Type (*.ext)","Import_Ext")
</code>


Then in the Import_Ext.py file:
Then in the Import_Ext.py file:


def open(filename):
<code python>
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()

</code>
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 ===
=== Adding a line ===
Line 62: Line 53:
A line simply has 2 points.
A line simply has 2 points.


import Part,PartGui
<code python>
doc=App.activeDocument()
import Part,PartGui
# add a line element to the document and set its points
doc=App.activeDocument()
l=Part.Line()
# add a line element to the document and set its points
l.StartPoint=(0.0,0.0,0.0)
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()
l.EndPoint=(1.0,1.0,1.0)
doc.recompute()
doc.addObject("Part::Feature","Line").Shape=l.toShape()
doc.recompute()
</code>


=== Adding a polygon ===
=== Adding a polygon ===
Line 77: Line 66:
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.


import Part,PartGui
<code python>
doc=App.activeDocument()
import Part,PartGui
n=list()
doc=App.activeDocument()
# create a 3D vector, set its coordinates and add it to the list
n=list()
v=App.Vector(0,0,0)
# create a 3D vector, set its coordinates and add it to the list
n.append(v)
v=App.Vector(0,0,0)
v=App.Vector(10,0,0)
n.append(v)
n.append(v)
v=App.Vector(10,0,0)
#... repeat for all nodes
n.append(v)
#... repeat for all nodes
# Create a polygon object and set its nodes
p=doc.addObject("Part::Polygon","Polygon")
# Create a polygon object and set its nodes
p.Nodes=n
p=doc.addObject("Part::Polygon","Polygon")
p.Nodes=n
doc.recompute()
doc.recompute()
</code>


=== Adding and removing an object to a group ===
=== Adding and removing an object to a group ===


doc=App.activeDocument()
<code python>
grp=doc.addObject("App::DocumentObjectGroup", "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
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
grp.removeObject(lin) # removes the lin object from the group grp
</code>


Note: You can even add other groups to a group...
Note: You can even add other groups to a group...
Line 107: Line 92:
=== Adding a Mesh ===
=== Adding a Mesh ===


import Mesh
<code python>
doc=App.activeDocument()
import Mesh
# create a new empty mesh
doc=App.activeDocument()
m = Mesh.Mesh()
# create a new empty mesh
# build up box out of 12 facets
m = Mesh.Mesh()
m.addFacet(0.0,0.0,0.0, 0.0,0.0,1.0, 0.0,1.0,1.0)
# 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, 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,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, 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, 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,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, 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,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, 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(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,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.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
m.scale(100.0)
me=doc.addObject("Mesh::Feature","Cube")
# add the mesh to the active document
me.Mesh=m
me=doc.addObject("Mesh::Feature","Cube")
me.Mesh=m
</code>


=== Adding an arc or a circle ===
=== Adding an arc or a circle ===


import Part
<code python>
doc = App.activeDocument()
import Part
doc = App.activeDocument()
c = Part.Circle()
c.Radius=10.0
c = Part.Circle()
f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature
c.Radius=10.0
f.Shape = c.toShape() # Assign the circle shape to the shape property
f = doc.addObject("Part::Feature", "Circle") # create a document with a circle feature
doc.recompute()
f.Shape = c.toShape() # Assign the circle shape to the shape property
doc.recompute()
</code>


=== Accessing and changing representation of an object ===
=== Accessing and changing representation of an object ===
Line 148: Line 129:
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...


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

v=gad.getObject("Cube") # access the view representation to the Mesh feature 'Cube'
v=gad.getObject("Cube") # access the view representation to the Mesh feature 'Cube'
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
</code>


=== Observing mouse events in the 3D viewer via Python ===
=== Observing mouse events in the 3D viewer via Python ===
Line 162: Line 141:
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.


App.newDocument()
<code python>
v=Gui.activeDocument().activeView()
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.
#This class logs any mouse button events. As the registered callback function fires twice for 'down' and
class ViewObserver:
#'up' events we need a boolean flag to handle this.
class ViewObserver:
def logPosition(self, info):
def logPosition(self, info):
down = (info["State"] == "DOWN")
down = (info["State"] == "DOWN")
Line 174: Line 152:
if (down):
if (down):
FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[0])+")\n")
FreeCAD.Console.PrintMessage("Clicked on position: ("+str(pos[0])+", "+str(pos[0])+")\n")
o = ViewObserver()
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
o = ViewObserver()
c = v.addEventCallback("SoMouseButtonEvent",o.logPosition)
</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
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)
<code python>
v.removeEventCallback("SoMouseButtonEvent",c)
</code>


The following event types are supported
The following event types are supported
Line 223: Line 197:
=== Manipulate the scenegraph in Python ===
=== 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.
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
<code python>
view = Gui.ActiveDocument.ActiveView # get the active viewer
from pivy.coin import * # load the pivy module
root = view.getSceneGraph() # the root is an SoSeparator node
view = Gui.ActiveDocument.ActiveView # get the active viewer
root.addChild(SoCube())
root = view.getSceneGraph() # the root is an SoSeparator node
view.fitAll()
root.addChild(SoCube())
view.fitAll()
</code>


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

<code python>
type = SoType.fromName("SoFCSelection")
type = SoType.fromName("SoFCSelection")
node = type.createInstance()
node = type.createInstance()
</code>


=== Adding and removing objects to/from the scenegraph ===
=== Adding and removing objects to/from the scenegraph ===
Line 244: Line 215:
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):


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


To remove it, simply issue:
To remove it, simply issue:


<code python>
sg.removeChild(no)
sg.removeChild(no)
</code>


===Adding custom widgets to the interface===
===Adding custom widgets to the interface===
Line 273: Line 240:
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):


class myWidget_Ui(object):
<code python>
class myWidget_Ui(object):
def setupUi(self, myWidget):
def setupUi(self, myWidget):
myWidget.setObjectName("my Nice New Widget")
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
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 = QtGui.QLabel(myWidget) # creates a label
self.label.setGeometry(QtCore.QRect(50,50,200,24)) # sets its size
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
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
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))
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))
</code>


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:


<code python>
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 297: Line 261:
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
</code>


{{Devdocnavi}}
{{Devdocnavi}}

Revision as of 02:43, 10 April 2009

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[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

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)
  • 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, 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

Template:Devdocnavi