本文整理汇总了Python中ImportGui.insert方法的典型用法代码示例。如果您正苦于以下问题:Python ImportGui.insert方法的具体用法?Python ImportGui.insert怎么用?Python ImportGui.insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ImportGui
的用法示例。
在下文中一共展示了ImportGui.insert方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ImportElement
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
def ImportElement():
doc=FreeCAD.ActiveDocument;
FreeCAD.Console.PrintMessage("Try to import...\n");
(fname1,fdir1) = QtGui.QFileDialog.getOpenFileName(None,'Open file','');
ImportGui.insert(fname1,doc.Name);
doc.recompute();
ob1=doc.Objects[-1];
# create groupe and add element to it
if (hasattr(doc,'OpticalSystem')==False):
gr1=doc.addObject("App::DocumentObjectGroup","OpticalSystem");
gr1.newObject("App::DocumentObjectGroup","Rays");
gr1_e=gr1.newObject("App::DocumentObjectGroup","Elements");
gr1_e.addObject(ob1);
else:
gr1_e=getattr(doc,'Elements');
gr1_e.addObject(ob1);
# end if
ob1.Label="IMPR";
ob1.ViewObject.ShapeColor=(0.5,0.5,0.5);
ob1.ViewObject.Transparency=80;
An=ob1.Placement.Rotation.toEuler();
P1=ob1.Placement.Base;
l1=["","Imported",ob1.Name,ob1.Label, \
P1.x,P1.y,P1.z, \
An[2],An[1],An[0],None,None,None,1.,1.52,None,None];
# add lens to list of optical system elements
OptElementsGui.AddToOSData(l1,"Element");
doc.recompute();
if (str(FreeCADGui.ActiveDocument.activeView())=='View3DInventor'):
FreeCADGui.activeDocument().activeView().viewRear();
FreeCADGui.activeDocument().activeView().viewRotateRight();
FreeCADGui.activeDocument().activeView().fitAll();
# end if
FreeCAD.Console.PrintMessage("Element is imported\n");
示例2: place_steps
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
def place_steps(doc,placement,board_thickness):
""" place_steps(doc,placement,board_thickness)->place step models on board
list of models and path to step files is set at start of this script
model_tab_filename= "" & step_path="" """
model_file=pythonopen(model_tab_filename, "r")
model_lines=model_file.readlines()
model_file.close()
model_dict=[]
if IDF_diag==1:
model_file=pythonopen(IDF_diag_path+"/missing_models.lst", "w")
keys=[]
#prev_step="*?.*?" #hope nobody will insert this step filename
step_dict=[]
for model_line in model_lines:
model_records=split_records(model_line)
if len(model_records)>1 and model_records[0] and not model_records[0] in keys:
keys.append(model_records[0])
model_dict.append((str(model_records[0]).replace('"',''),str(model_records[1]).replace('"','')))
model_dict=dict(model_dict)
validkeys=filter(lambda x:x in [place_item[2] for place_item in placement], model_dict.keys())
FreeCAD.Console.PrintMessage("Step models to be loaded for footprints: "+str(validkeys)+"\n")
grp=doc.addObject("App::DocumentObjectGroup", "Step Lib")
for validkey in validkeys:
ImportGui.insert(step_path+model_dict[validkey],FreeCAD.ActiveDocument.Name)
#partName=FreeCAD.ActiveDocument.ActiveObject.Name
impPart=FreeCAD.ActiveDocument.ActiveObject
#impPart.Shape=FreeCAD.ActiveDocument.ActiveObject.Shape
#impPart.ViewObject.DiffuseColor=FreeCAD.ActiveDocument.ActiveObject.ViewObject.DiffuseColor
impPart.ViewObject.Visibility=0
impPart.Label=validkey
grp.addObject(impPart)
step_dict.append((validkey,impPart))
FreeCAD.Console.PrintMessage("Reading step file "+str(model_dict[validkey])+" for footprint "+str(validkey)+"\n")
step_dict=dict(step_dict)
grp=doc.addObject("App::DocumentObjectGroup", "Step Models")
for place_item in placement:
if place_item[2] in step_dict:
step_model=doc.addObject("Part::Feature",place_item[0]+"_s")
FreeCAD.Console.PrintMessage("Adding STEP model "+str(place_item[0])+"\n")
#if prev_step!=place_item[2]:
# model0=Part.read(step_path+"/"+model_dict[place_item[2]])
# prev_step=place_item[2]
step_model.Shape=step_dict[place_item[2]].Shape
step_model.ViewObject.DiffuseColor=step_dict[place_item[2]].ViewObject.DiffuseColor
z_pos=0
rotateY=0
if place_item[6]=='BOTTOM':
rotateY=pi
z_pos=-board_thickness
placmnt=Base.Placement(Base.Vector(place_item[3],place_item[4],z_pos),toQuaternion(rotateY,place_item[5]*pi/180,0))
step_model.Placement=placmnt
grp.addObject(step_model)
else:
if IDF_diag==1:
model_file.writelines(str(place_item[0])+" "+str(place_item[2])+"\n")
model_file.close()
示例3: exportVRML
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
def exportVRML(doc,modelName,scale,dir):
## Export to VRML scaled 1/2.54
#VrmlFileName='.//'+doc.Label+'.wrl'
## outdir=os.path.dirname(os.path.realpath(__file__))+dir
outdir=dir
FreeCAD.Console.PrintMessage('\r\n'+outdir)
VrmlFileName=outdir+'/'+modelName+'.wrl'
StepFileName=outdir+'/'+modelName+'.step'
objs=[]
objs=GetListOfObjects(FreeCAD, doc)
#objs.append(FreeCAD.getDocument(doc.Name).getObject("Fusion001"))
FreeCAD.ActiveDocument.addObject('Part::Feature','Vrml_model').Shape=objs[0].Shape
FreeCAD.ActiveDocument.ActiveObject.Label='Vrml_model'
FreeCADGui.ActiveDocument.ActiveObject.ShapeColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).ShapeColor
FreeCADGui.ActiveDocument.ActiveObject.LineColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).LineColor
FreeCADGui.ActiveDocument.ActiveObject.PointColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).PointColor
FreeCADGui.ActiveDocument.ActiveObject.DiffuseColor=FreeCADGui.getDocument(doc.Name).getObject(objs[0].Name).DiffuseColor
FreeCAD.ActiveDocument.recompute()
newObj=FreeCAD.getDocument(doc.Name).getObject('Vrml_model')
#scale to export vrml start
Draft.scale(newObj,delta=FreeCAD.Vector(scale,scale,scale),center=FreeCAD.Vector(0,0,0),legacy=True)
FreeCAD.activeDocument().recompute()
#we need to remove object to export only scaled model
FreeCAD.getDocument(doc.Name).removeObject(objs[0].Name)
__objs__=[]
__objs__.append(FreeCAD.getDocument(doc.Name).getObject("Vrml_model"))
FreeCADGui.export(__objs__,VrmlFileName)
FreeCAD.activeDocument().recompute()
#restoring step module
import ImportGui
ImportGui.insert(StepFileName,doc.Name)
FreeCAD.Console.PrintMessage(FreeCAD.ActiveDocument.ActiveObject.Label+" exported and scaled to Vrml\r\n")
del __objs__
return 0
示例4: insert
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
def insert(filename,doc):
sayz("stpZ version "+___stpZversion___)
with gzip_utf8.open(filename, 'rb') as f:
file_content = f.read()
ext = os.path.splitext(os.path.basename(filename))[1]
fname=os.path.splitext(os.path.basename(filename))[0]
basepath=os.path.split(filename)[0]
filepath = os.path.join(basepath,fname + u'.stp')
tempdir = tempfile.gettempdir() # get the current temporary directory
tempfilepath = os.path.join(tempdir,fname + u'.stp')
with builtin.open(tempfilepath, 'w') as f: #py3
f.write(file_content)
ImportGui.insert(tempfilepath, doc)
#ImportGui.open(tempfilepath)
try:
os.remove(tempfilepath)
except OSError:
sayzerr("error on removing "+tempfilepath+" file")
pass
示例5: importPart
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
def importPart( filename, partName=None, doc_assembly=None ):
if doc_assembly == None:
doc_assembly = FreeCAD.ActiveDocument
updateExistingPart = partName != None
if updateExistingPart:
FreeCAD.Console.PrintMessage("updating part %s from %s\n" % (partName,filename))
else:
FreeCAD.Console.PrintMessage("importing part from %s\n" % filename)
doc_already_open = filename in [ d.FileName for d in FreeCAD.listDocuments().values() ]
debugPrint(4, "%s open already %s" % (filename, doc_already_open))
if doc_already_open:
doc = [ d for d in FreeCAD.listDocuments().values() if d.FileName == filename][0]
close_doc = False
else:
if filename.lower().endswith('.fcstd'):
doc = Fcstd_File_Parser( filename )
close_doc = False
else: #trying shaping import http://forum.freecadweb.org/viewtopic.php?f=22&t=12434&p=99772#p99772x
import ImportGui
doc = FreeCAD.newDocument( os.path.basename(filename) )
shapeobj = ImportGui.insert(filename,doc.Name)
close_doc = True
visibleObjects = [ obj for obj in doc.Objects
if hasattr(obj,'ViewObject') and obj.ViewObject.isVisible()
and hasattr(obj,'Shape') and len(obj.Shape.Faces) > 0 and 'Body' not in obj.Name] # len(obj.Shape.Faces) > 0 to avoid sketches, skip Body
debugPrint(3, '%s objects %s' % (doc.Name, doc.Objects))
if any([ 'importPart' in obj.Content for obj in doc.Objects]) and not len(visibleObjects) == 1:
subAssemblyImport = True
debugPrint(2, 'Importing subassembly from %s' % filename)
tempPartName = 'import_temporary_part'
obj_to_copy = doc_assembly.addObject("Part::FeaturePython",tempPartName)
obj_to_copy.Proxy = Proxy_muxAssemblyObj()
obj_to_copy.ViewObject.Proxy = ImportedPartViewProviderProxy()
obj_to_copy.Shape = muxObjects(doc)
if (not updateExistingPart) or \
(updateExistingPart and getattr( doc_assembly.getObject(partName),'updateColors',True)):
muxMapColors(doc, obj_to_copy)
else:
subAssemblyImport = False
if len(visibleObjects) != 1:
if not updateExistingPart:
msg = "A part can only be imported from a FreeCAD document with exactly one visible part. Aborting operation"
QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), "Value Error", msg )
else:
msg = "Error updating part from %s: A part can only be imported from a FreeCAD document with exactly one visible part. Aborting update of %s" % (partName, filename)
QtGui.QMessageBox.information( QtGui.QApplication.activeWindow(), "Value Error", msg )
#QtGui.QMessageBox.warning( QtGui.QApplication.activeWindow(), "Value Error!", msg, QtGui.QMessageBox.StandardButton.Ok )
return
obj_to_copy = visibleObjects[0]
if updateExistingPart:
obj = doc_assembly.getObject(partName)
prevPlacement = obj.Placement
if not hasattr(obj, 'updateColors'):
obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
importUpdateConstraintSubobjects( doc_assembly, obj, obj_to_copy )
else:
partName = findUnusedObjectName( doc.Label + '_', document=doc_assembly )
try:
obj = doc_assembly.addObject("Part::FeaturePython",partName)
except UnicodeEncodeError:
safeName = findUnusedObjectName('import_', document=doc_assembly)
obj = doc_assembly.addObject("Part::FeaturePython", safeName)
obj.Label = findUnusedLabel( doc.Label + '_', document=doc_assembly )
obj.addProperty("App::PropertyFile", "sourceFile", "importPart").sourceFile = filename
obj.addProperty("App::PropertyFloat", "timeLastImport","importPart")
obj.setEditorMode("timeLastImport",1)
obj.addProperty("App::PropertyBool","fixedPosition","importPart")
obj.fixedPosition = not any([i.fixedPosition for i in doc_assembly.Objects if hasattr(i, 'fixedPosition') ])
obj.addProperty("App::PropertyBool","updateColors","importPart").updateColors = True
obj.Shape = obj_to_copy.Shape.copy()
if updateExistingPart:
obj.Placement = prevPlacement
else:
# for Fcstd_File_Parser not all properties are implemented...
for p in obj_to_copy.ViewObject.PropertiesList: #assuming that the user may change the appearance of parts differently depending on the assembly.
if hasattr(obj.ViewObject, p) and p not in ['DiffuseColor']:
try:
setattr(obj.ViewObject, p, getattr(obj_to_copy.ViewObject, p))
except Exception as msg:
FreeCAD.Console.PrintWarning('Unable to setattr(obj.ViewObject, %s, %s)\n' % (p, getattr(obj_to_copy.ViewObject, p) ))
obj.ViewObject.Proxy = ImportedPartViewProviderProxy()
if getattr(obj,'updateColors',True) and hasattr( obj_to_copy.ViewObject, 'DiffuseColor'):
obj.ViewObject.DiffuseColor = copy.copy( obj_to_copy.ViewObject.DiffuseColor )
#obj.ViewObject.Transparency = copy.copy( obj_to_copy.ViewObject.Transparency ) # .Transparency property
tsp = copy.copy( obj_to_copy.ViewObject.Transparency ) # .Transparency workaround for FC 0.17 @ Nov 2016
if tsp < 100 and tsp!=0:
obj.ViewObject.Transparency = tsp+1
if tsp == 100:
obj.ViewObject.Transparency = tsp-1
obj.ViewObject.Transparency = tsp # .Transparency workaround end
obj.Proxy = Proxy_importPart()
obj.timeLastImport = os.path.getmtime( filename )
#clean up
if subAssemblyImport:
doc_assembly.removeObject(tempPartName)
if close_doc:
FreeCAD.closeDocument( doc.Name )
#.........这里部分代码省略.........
示例6: open
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
HDLR_stepfile_w = open(PATH_toStepFiles + FNME_stepfile, 'w') # open
except:
print "broken_3"
else:
# overwrite with new preamble
for line in LIST_PMBL:
HDLR_stepfile_w.write(line + "\n")
# add old data section
for line in PMBL_stepfile[(DICT_positions["A"]-1):]:
HDLR_stepfile_w.write(line.strip() + "\n")
HDLR_stepfile_w.close()
# load STEP model, manipulate and save as VRML
FreeCAD.newDocument("Unnamed")
FreeCAD.setActiveDocument("Unnamed")
ImportGui.insert(PATH_toStepFiles + FNME_stepfile,"Unnamed")
FNME_vrmlfile = FNME_stepfile[:-4] + ".wrl"
# change display mode and scale down
for part in FreeCAD.ActiveDocument.Objects:
part.ViewObject.DisplayMode = 1 #Shaded
Draft.scale(part,delta=App.Vector(0.3937,0.3937,0.3937),center=App.Vector(0,0,0),legacy=True)
if FLAG_makeTransparent: # if transparency is needed
# from PySide import QtGui
# QtGui.QInputDialog.getText(None, "Get text", "Input:")[0]
pass
__objs__=[] # select all parts (again)
for part in FreeCAD.ActiveDocument.Objects:
__objs__.append(part)
FreeCADGui.export(__objs__,(PATH_toVrmlFiles + FNME_vrmlfile))
del __objs__
示例7: get_layer_tail
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
subsystem_grp = doc.addObject("App::DocumentObjectGroup", subsystem)
subsystem_grp.Label = subsystem
for step,vv in v.items():
step_name = get_layer_tail(step)
step_grp = doc.addObject("App::DocumentObjectGroup", step_name)
step_grp.Label = step_name
subsystem_grp.addObject(step_grp)
for partkind,vvv in vv.items():
partkind_name = "%s::%s" % (step_name,partkind)
partkind_grp = doc.addObject("App::DocumentObjectGroup", partkind_name)
partkind_grp.Label = partkind_name
step_grp.addObject(partkind_grp)
filename = get_part_filename(subsystem, step_name, partkind)
FreeCAD.Console.PrintMessage(filename + "\n")
preimport_obj_count = len(doc.Objects)
ImportGui.insert(os.path.join(step_dir, filename), doc.Name)
# group new objects
for i in range(preimport_obj_count, len(doc.Objects)):
obj = doc.Objects[i]
if obj.TypeId == 'Part::Feature':
partkind_grp.addObject(obj)
FreeCAD.Gui.SendMsgToActiveView("ViewFit")
if not subsystem == "1.frame-bottom":
subsystem_grp.ViewObject.Visibility=False
doc.recompute()
示例8: export
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
def export(variant, overwrite=False, saveFCStd=False, exportDXF=False):
partPrefix = variant[:-4]
partPostfix = variant[5:]
pinCount = int(variant[5:7])
srcName = srcDir+variant+'.stp'
if not os.path.isfile(srcName):
FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n')
return
if not os.path.exists(dstDir):
os.makedirs(dstDir)
bodyCutName = 'body-' + partPrefix + '#'
bodyCut = None
try:
tmpl = App.getDocument(tmplName)
except:
tmpl = App.openDocument(tmplName+'.FCStd')
for obj in tmpl.Objects:
if obj.Label.startswith(bodyCutName):
bodyCut = obj
break
if bodyCut == None:
FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n')
return
FreeCAD.Console.PrintMessage('cehcking ' + variant + '\n')
names = [x for x in obj.Label.split('#')]
pitch = float(names[2])
dstName = dstDir+names[3]\
.replace('%e',partPrefix)\
.replace('%o',partPostfix)\
.replace('%c','%02d'%pinCount)\
.replace('%p','%.2f'%pitch)
if os.path.isfile(dstName+'.stp'):
if not overwrite:
FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n')
return
FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n')
newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999)))
guiDoc = Gui.getDocument(newDoc.Name)
bodyCut = newDoc.copyObject(bodyCut,True)
guiDoc.getObject(bodyCut.Name).Visibility = False;
ImportGui.insert(srcName,newDoc.Name)
objs = newDoc.getObjectsByLabel(bodyName)
if not objs:
FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n')
return
part = objs[0]
guiDoc.getObject(part.Name).Visibility = False;
objs = newDoc.getObjectsByLabel(fpName)
if not objs:
FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n')
return
footprint = objs[0]
placement = bodyCut.Placement
bodyCut.Placement = App.Placement()
for obj in bodyCut.Shapes:
# any better way to id array object?
if 'ArrayType' in obj.PropertiesList:
# TODO, we assum interval x sets the pitch, add more check later
obj.IntervalX.x = pitch
obj.NumberX = pinCount
obj.Placement.Base.x -= (pinCount-2)*pitch/2
else:
for sobj in obj.Shapes:
if sobj.TypeId == 'Part::Mirroring':
sobj.Source.Placement.Base.x -= (pinCount-2)*pitch/2
newDoc.recompute()
colors = []
objs = []
shapes = []
def make_part(obj,isCut):
names = [x for x in obj.Label.split('#')]
newObj = newDoc.addObject("Part::Feature", names[0])
if isCut:
newObj.Shape = part.Shape.cut(obj.Shape).removeSplitter()
else:
newObj.Shape = part.Shape.common(obj.Shape).removeSplitter()
color = names[1]
if not color in shaderColors.named_colors:
FreeCAD.Console.PrintWarning('unknown color : ' + color + '\n')
color = None
#.........这里部分代码省略.........
示例9: export
# 需要导入模块: import ImportGui [as 别名]
# 或者: from ImportGui import insert [as 别名]
def export(variant, fuse=False, overwrite=False, saveFCStd=False, exportDXF=False):
partPrefix = variant[:-4]
partPostfix = variant[5:]
pinCount = int(variant[5:7])
srcName = srcDir+variant+'.stp'
if not os.path.isfile(srcName):
FreeCAD.Console.PrintMessage('missing ' + variant + '.stp\n')
return
if not os.path.exists(dstDir):
os.makedirs(dstDir)
bodyCutName = 'body-' + partPrefix + '#'
bodyCut = None
try:
tmpl = App.getDocument(libName)
except:
tmpl = App.openDocument(tmplDir+libName+'.FCStd')
for obj in tmpl.Objects:
if obj.Label.startswith(bodyCutName):
bodyCut = obj
break
if bodyCut == None:
FreeCAD.Console.PrintMessage('missing template for ' + partPrefix + '\n')
return
FreeCAD.Console.PrintMessage('cehcking ' + variant + '\n')
names = [x for x in obj.Label.split('#')]
pitch = float(names[2])
dstName = dstDir+names[3]\
.replace('%e',partPrefix)\
.replace('%o',partPostfix)\
.replace('%c','%02d'%pinCount)\
.replace('%p','%.2f'%pitch)
settings = { 'align':'' }
if len(names) > 4:
for i in range(4,len(names)):
if names[i] == '': continue
option = [x for x in names[i].split(':')]
if not option[0] in settings:
FreeCAD.Console.PrintWarning('unknown setting : ' + option[0] + '\n')
else:
settings[option[0]] = option[1]
if os.path.isfile(dstName+'.stp'):
if not overwrite:
FreeCAD.Console.PrintMessage(dstName + ' already exists, skip!\n')
return
FreeCAD.Console.PrintMessage('exporting ' + dstName + '\n')
newDoc = App.newDocument(variant+'_'+str(random.randrange(10000,99999)))
guiDoc = Gui.getDocument(newDoc.Name)
bodyCut = newDoc.copyObject(bodyCut,True)
FreeCAD.Console.PrintMessage(bodyCut.Name + '\n')
guiDoc.getObject(bodyCut.Name).Visibility = False;
ImportGui.insert(srcName,newDoc.Name)
objs = newDoc.getObjectsByLabel(bodyName)
if not objs:
FreeCAD.Console.PrintMessage('missing body for ' + partPrefix + '\n')
return
part = objs[0]
guiDoc.getObject(part.Name).Visibility = False;
objs = newDoc.getObjectsByLabel(fpName)
if not objs:
FreeCAD.Console.PrintMessage('missing footprint for ' + partPrefix + '\n')
return
footprint = objs[0]
# NOTE!!! If we don't use Placement.copy here, we will be getting a surprise
# from FreeCAD. Even if we reset the bodyCut.Placement below, whenever we change
# the non-copied placement, bodyCut.Placement will get an update, too! Spooky!!
# There seems to be some dangling internal reference bug here.
placement = bodyCut.Placement.copy()
bodyCut.Placement = App.Placement()
offset = (pinCount-2)*pitch/2
if settings['align'] == 'pin':
placement.Base.x += offset
footprint.Placement = placement.copy()
for obj in bodyCut.Shapes:
# any better way to id array object?
if 'ArrayType' in obj.PropertiesList:
# TODO, we assum interval x sets the pitch, add more check later
obj.IntervalX.x = pitch
obj.NumberX = pinCount
obj.Placement.Base.x -= offset
#.........这里部分代码省略.........