Line drawing function
This page shows how advanced functionality can easily be built in python. In this exercise, we will be building a new function that draws a line. This fuction can then be linked to a freecad command, and that command can be called by any element of the interface, like a menu item or a toolbar button.
The main script
First we will make a script containing all our functionality. We will make a getpoint function, then a line function that will, when executed, call two times the getpoint function, then draw the line. Here is our script:
import FreeCADGui, Part
"this function returns (x,y,z) coordinates from a mouse click" view = FreeCADGui.ActiveDocument.ActiveView point = None
def getposition(info): down = (info["State"] == "DOWN") pos = info["Position"] if (down): point = view.getPoint(pos,pos)
callback = view.addEventCallback("SoMouseButtonEvent",getposition) while not (point): pass view.removeEventCallback(callback) return (point.x,point.y,point.z)
"this function creates a line" x1,y1,z1 = getpoint() x2,y2,z2 = getpoint() newline = Part.makeLine((x1,y1,z1),(x2,y2,z2)) Part.show(newline)
import Part, FreeCADGui
In python, when you want to use functions from another module, you need to import it before. In our case, we will need functions from the Part module, for creating the line, and frm the Gui module (FreeCADGui), for manipulating the 3D view.
Here we define our first function. It is a good habit, when creating functions and classes, to start them imediately with a string describing what the function does. When you will use this function from the freecad python interpreter, this string will appear as a tooltip.