在基于ANSA的二次开发中,许多功能开发都需要利用到模型的结构树,如模型任务分发功能定制,连接(焊点、粘胶、焊缝等)的自动化生成都需要用到结构树。下面介绍三种结构树构造方法并对每种方案的性能进行说明。方法二主要思路:获取原始结构树中的所有节点,并通过关键字Hierarchy读取其原始节点链字符串构建一个一一对应的字典,然后从根节点开始从上向下一个分支一个分支的逐层构建。前期将原始节点链字符串进行保存,获取若由于某种原因(如网格划分)导致结构树破坏,利用该方法再将原始结构树进行复原。针对一个完整的车身(BIW)CAD数据,进行构造,64核电脑用时0.12秒。fromansaimportguitkfromansaimportbasefromtypingimportList,Tuple,Dict,Uniondeck=base.CurrentDeck()PARTTYPETUPLE:Tuple[str]=('ANSAPART','ANSAGROUP')VIEWCOLNAMETUPLE:Tuple[str]=('ModuleId','Name','Status')#ListView列名称defsetItemText(item:object,name:str,id:str='')->None:'''对输入的item设置名称和ID'''guitk.BCListViewItemSetText(item,VIEWCOLNAMETUPLE.index('Name'),name)ifid:guitk.BCListViewItemSetText(item,VIEWCOLNAMETUPLE.index('ModuleId'),id)returnNonedefcreateItem(parentItem:object,part:base.Entity,isTop:bool=False)->object:'''功能:为输入的part在parentItem下创建一个新的item参数:parentItemobject准备新创建item的父节点,为item或listView类型part:Entity一个part或group对象isTopbool判断需要创建节点是否为根节点的判断器返回值:返回生成的item对象'''ifnotisTop:item:object=guitk.BCListViewItemAddChild(parentItem)else:item:object=guitk.BCListViewAddTopLevelItem(parentItem)ifpart.ansa_type(deck)==PARTTYPETUPLE[0]:partId:str=part.get_entity_values(deck,['ModuleId',])['ModuleId']else:partId:str=''setItemText(item,part._name.strip(),id=partId)guitk.BCListViewItemSetUserData(item,part)returnitemdefloadModelTree02()->None:partIter:List[base.Entity]=base.CollectEntitiesI(deck,None,PARTTYPETUPLE)hierToPartDict:Dict[str,List[base.Entity]]=dict()forpartinpartIter:tree:str=part.get_entity_values(deck,['Hierarchy',])['Hierarchy']tree=tree.strip()try:hierToPartDict[tree].append(part)exceptKeyError:hierToPartDict[tree]=[part]crtTreeBranch(leftModelView,'',hierToPartDict,isTop=True)defcrtTreeBranch(parent:object,name:str,hierToPartDict:Dict[str,List[base.Entity]],isTop:bool=False)->None:children:List[base.Entity]=hierToPartDict.get(name,None)ifnotchildren:returnNoneforchildinchildren:item=leftPartToItemDict.get(child,None)ifnotitem:item=createItem(parent,child,isTop=isTop)leftPartToItemDict[child]=itemifchild.ansa_type(deck)==PARTTYPETUPLE[0]:continuecrtTreeBranch(item,f'{name}{child._name.strip()}/',hierToPartDict)returnNoneif__name__=='__main__':#用于存储结构树数据,实现part和新创建的item一一对应leftPartToItemDict:Dict[str,List[object]]=dict()mainWindow:object=guitk.BCWindowCreate('结构树构造',guitk.constants.BCOnExitDestroy)mainBox:object=guitk.BCVBoxCreate(mainWindow)leftModelView:object=guitk.BCListViewCreate(mainBox,3,VIEWCOLNAMETUPLE,True)guitk.BCListViewSetIsRootDecorated(leftModelView,True)guitk.BCListViewSetFilterEnabled(leftModelView,True)guitk.BCListViewSetSelectionMode(leftModelView,guitk.constants.BCMulti)loadModelTree02()guitk.BCShow(mainWindow)未经作者同意,不得转载该文!!!来源:檐苔