Objetos programados con archivo adjunto
Introducción
El propósito de esta página es mostrar un ejemplo mínimo de la función Part EditAttachment usando Objetos guionizados en Python.
Consulte Ejemplo mínimo completo y completo a continuación.
El siguiente GIF muestra cómo acoplar nuestra caja personalizada a un cilindro y cómo actualizar automáticamente su posición cuando cambia la posición del cilindro.
NOTA: La caja es un objeto personalizado creado con nuestro script, y el cilindro es un objeto FreeCAD normal generado desde el Entorno de Trabajo de Piezas.
Cómo hacer que los objetos programados sean adjuntables
Agregar extensión adjunta
Primero, necesitamos agregar la extensión Part::AttachExtensionPython a nuestro objeto Part::FeaturePython en el constructor, o método __init__, de nuestro objeto de script personalizado.
class Box():
"""Custom Scripted Box Object"""
def __init__(self, obj):
self.Type = 'Box'
obj.Proxy = self
... custom properties
# Needed to make this object "attachable"
obj.addExtension('Part::AttachExtensionPython')
Sin agregar este código, veremos el siguiente cuadro de diálogo de advertencia al adjuntar nuestro objeto con script personalizado a otro objeto.
Actualizar la posición en función del objeto adjunto
Luego, en el método `execute` de nuestro objeto con script personalizado, necesitamos llamar a `positionBySupport` en nuestro objeto `Part::FeaturePython`.
class Box:
...
def execute(self, obj):
obj.positionBySupport()
# Assign a Shape to obj
obj.Shape = Part.makeBox(...)
Sin llamar a positionBySupport, nuestro objeto con script personalizado no actualizará su posición cuando cambie la posición del objeto adjunto.
Ejemplo mínimo completo
import FreeCAD as App
import Part
class Box():
"""
Simple Custom Box Object
See Also:
https://wiki.freecad.org/FeaturePython_Objects
"""
def __init__(self, obj):
"""
Constructor
Arguments
---------
- obj: an existing document object or an object created with FreeCAD.Document.addObject('Part::FeaturePython', '{name}').
"""
self.Type = 'Box'
obj.Proxy = self
obj.addProperty('App::PropertyLength', 'Length',
'Dimensions', 'Box length').Length = 10.0
obj.addProperty('App::PropertyLength', 'Width',
'Dimensions', 'Box width').Width = 10.0
obj.addProperty('App::PropertyLength', 'Height',
'Dimensions', 'Box height').Height = 10.0
# Needed to make this object "attachable",
# or able to attach parameterically to other objects
obj.addExtension('Part::AttachExtensionPython')
def execute(self, obj):
"""
Called on document recompute
"""
# Needed to update position when attached-to object changes position.
# Reposition object based on AttachmentSupport, MapMode and MapPathParameter properties.
# Returns True if attachment calculation was successful, False if object is not attached and Placement wasn't updated,
obj.positionBySupport()
obj.Shape = Part.makeBox(obj.Length, obj.Width, obj.Height)
def create_box(obj_name, document):
"""
Create a Box.
"""
obj = document.addObject('Part::FeaturePython', obj_name)
Box(obj)
obj.ViewObject.Proxy = 0 # Mandatory unless ViewProvider is coded
return obj
document = App.ActiveDocument
if document is None:
document = App.newDocument('Part Attachment Example')
box = create_box('CustomBox', document)
document.recompute()
cylinder = App.ActiveDocument.addObject('Part::Cylinder', 'Cylinder')
document.recompute()
box.AttachmentSupport = cylinder
box.MapMode = 'ObjectXY'
document.recompute()
Referencias
- Part EditAttachment
- FreeCAD Forum - Parametric attachment of scripted object
- FreeCAD Forum - Port attachment to be an extension
- GitHub - freecad-part-attachment-python-example
Probado con la siguiente versión de FreeCAD
Probado con la siguiente información de versión de FreeCAD:
OS: Ubuntu 18.04.3 LTS Word size of OS: 64-bit Word size of FreeCAD: 64-bit Version: 0.18.16146 (Git) AppImage Build type: Release Branch: (HEAD detached at 0.18.4) Hash: 980bf9060e28555fecd9e3462f68ca74007b70f8 Python version: 3.6.7 Qt version: 5.6.2 Coin version: 4.0.0a OCC version: 7.3.0 Locale: English/UnitedStates (en_US)
Nota: Para FreeCAD 0.19, este tutorial necesita una pequeña actualización:
- El segundo argumento del método `addExtension` ha quedado obsoleto.
- Para más detalles, consulte https://forum.freecad.org/viewtopic.php?f=10&t=54370
- FreeCAD scripting: Python, Introduction to Python, Python scripting tutorial, FreeCAD Scripting Basics
- Modules: Builtin modules, Units, Quantity
- Workbenches: Workbench creation, Gui Commands, Commands, Installing more workbenches
- Meshes and Parts: Mesh Scripting, Topological data scripting, Mesh to Part, PythonOCC
- Parametric objects: Scripted objects, Viewproviders (Custom icon in tree view)
- Scenegraph: Coin (Inventor) scenegraph, Pivy
- Graphical interface: Interface creation, Interface creation completely in Python (1, 2, 3, 4, 5), PySide, PySide examples beginner, intermediate, advanced
- Macros: Macros, How to install macros
- Embedding: Embedding FreeCAD, Embedding FreeCADGui
- Other: Expressions, Code snippets, Line drawing function, FreeCAD vector math library (deprecated)
- Hubs: User hub, Power users hub, Developer hub

