【Qt + OpenCASCADE】实现 SolidWorks 风格的装配树(附完整代码)

发布时间:2026/7/26 7:14:32
【Qt + OpenCASCADE】实现 SolidWorks 风格的装配树(附完整代码) 一、目的实现像 SolidWorks 那样左边是结构树右边是 3D 视图选中树节点 → 对应 3D 实体变为亮色高亮勾选/取消勾选树节点 → 对应 3D 实体在视图中显示/消失二、效果三、实现QTreeViewQAbstractItemMode树形结构展示、选中/勾选交互OpenCASCADE (OCCT)STEP 文件读取STEP 装配结构解析、BRep/装配模型管理、3D 渲染四、重点代码讲解a、step文件导入boolStepPartTreeView::loadStepFile(constQStringfilePath,constocc::handleTDocStd_Documentdoc){clearTree();if(doc.IsNull()){QMessageBox::warning(this,QStringLiteral(错误),QStringLiteral(XCAF 文档未初始化));returnfalse;}STEPCAFControl_Reader reader;reader.SetColorMode(true);reader.SetNameMode(true);reader.SetLayerMode(true);IFSelect_ReturnStatus statusreader.ReadFile(filePath.toUtf8().constData());if(status!IFSelect_RetDone){QMessageBox::warning(this,QStringLiteral(错误),QStringLiteral(无法读取 STEP 文件));returnfalse;}if(!reader.Transfer(doc)){QMessageBox::warning(this,QStringLiteral(错误),QStringLiteral(STEP 数据转换失败));returnfalse;}occ::handleXCAFDoc_ShapeToolshapeToolXCAFDoc_DocumentTool::ShapeTool(doc-Main());if(!shapeTool.IsNull()){shapeTool-UpdateAssemblies();}m_model-loadDocument(doc);expandToDepth(1);if(!m_context.IsNull()!m_model-graph().IsNull()){constQListintvisibleIdsm_model-visibleGraphNodeIds();for(intid:visibleIds){occ::handleAIS_InteractiveObjectaisensureAIS(id);if(!ais.IsNull()){m_context-Display(ais,AIS_Shaded,-1,false);}}if(!m_view.IsNull()){m_view-FitAll();if(m_occtViewer)m_occtViewer-fill();}m_context-UpdateCurrentViewer();}returntrue;}voidStepPartTreeModel::loadDocument(constocc::handleTDocStd_Documentdoc){beginResetModel();m_nodes.clear();m_graphIdToNodeIndex.clear();m_rootNodeIndex-1;m_docdoc;if(!m_doc.IsNull()){m_graphnewXCAFDoc_AssemblyGraph(m_doc);constTColStd_PackedMapOfIntegerrootsm_graph-GetRoots();QString rootNameQStringLiteral(装配体);for(TColStd_PackedMapOfInteger::Iteratorit(roots);it.More();it.Next()){QString ngetShapeName(m_graph-GetNode(it.Key()));if(!n.isEmpty()){rootNamen;break;}}m_rootNodeIndexappendNode(rootName,FeatNodeKind::RootDoc,-1,-1);for(TColStd_PackedMapOfInteger::Iteratorit(roots);it.More();it.Next()){buildAssemblyBranch(it.Key(),m_rootNodeIndex);}}else{m_graph.Nullify();}endResetModel();}b、选中高亮voidStepPartTreeView::onSelectionChanged(constQItemSelection,constQItemSelection){clearHighlight();constQModelIndexList selselectionModel()-selectedRows();QListintids;for(constQModelIndexidx:sel){intnodeIdxstatic_castint(idx.internalId());QListintsubIds;m_model-collectShapeGraphIds(nodeIdx,subIds);constQListintsubIdsConstsubIds;for(intid:subIdsConst){if(!ids.contains(id))ids.append(id);}if(subIds.isEmpty()){inteffIdm_model-effectiveGraphNodeId(nodeIdx);if(effId0!ids.contains(effId))ids.append(effId);}}if(ids.isEmpty()){if(!m_context.IsNull())m_context-UpdateCurrentViewer();return;}constQListintidsConstids;for(intid:idsConst){highlightNode(id);}intfirstIdids.first();TDF_Label labelm_model-labelFromGraphId(firstId);if(!m_context.IsNull())m_context-UpdateCurrentViewer();emitnodeSelected(firstId,label);}c、勾选显隐voidStepPartTreeModel::setNodeVisibleRecursive(intnodeIndex,boolvisible){if(nodeIndex0||nodeIndexm_nodes.size())return;NodeInfoinfom_nodes[nodeIndex];if(info.visible!visible){info.visiblevisible;QModelIndex idxcreateIndex(info.rowInParent,0,quintptr(nodeIndex));emitdataChanged(idx,idx,{Qt::CheckStateRole,IsVisibleRole});}constQVectorintchildreninfo.childrenIndex;for(intchild:children)setNodeVisibleRecursive(child,visible);}voidStepPartTreeView::onModelDataChanged(constQModelIndextopLeft,constQModelIndex,constQListintroles){if(!roles.contains(Qt::CheckStateRole))return;if(!topLeft.isValid())return;QListintids;intnodeIdxstatic_castint(topLeft.internalId());m_model-collectShapeGraphIds(nodeIdx,ids);if(ids.isEmpty()){inteffIdm_model-effectiveGraphNodeId(nodeIdx);if(effId0)ids.append(effId);}boolvisibletopLeft.data(IsVisibleRole).toBool();if(m_context.IsNull())return;boolchangedfalse;constQListintidsConstids;for(intid:idsConst){if(m_highlightedNodeIds.contains(id)){if(!visible){autoitm_aisObjects.find(id);if(it!m_aisObjects.end()!it.value().IsNull()){restoreOriginalColor(it.value());if(m_context-IsDisplayed(it.value())){m_context-Erase(it.value(),false);changedtrue;}}m_highlightedNodeIds.remove(id);}continue;}occ::handleAIS_InteractiveObjectais;autoitm_aisObjects.find(id);if(it!m_aisObjects.end()){aisit.value();}else{aisensureAIS(id);}if(ais.IsNull())continue;if(visible){if(!m_context-IsDisplayed(ais)){m_context-Display(ais,AIS_Shaded,-1,false);changedtrue;}}else{if(m_context-IsDisplayed(ais)){m_context-Erase(ais,false);changedtrue;}}}if(changed)m_context-UpdateCurrentViewer();emitupdateViewRequired();}d、AIS 对象的懒惰初始化 缓存occ::handleAIS_InteractiveObjectStepPartTreeView::ensureAIS(intgraphNodeId){autoitm_aisObjects.find(graphNodeId);if(it!m_aisObjects.end())returnit.value();if(m_model-graph().IsNull()||m_context.IsNull())returnocc::handleAIS_InteractiveObject();TDF_Label labelm_model-graph()-GetNode(graphNodeId);if(label.IsNull())returnocc::handleAIS_InteractiveObject();occ::handleAIS_InteractiveObjectais;TopoDS_Shape shape;try{if(XCAFDoc_ShapeTool::GetShape(label,shape)!shape.IsNull()){}else{shapegetShapeRecursive(label);}}catch(...){shapegetShapeRecursive(label);}if(!shape.IsNull()){try{occ::handleAIS_ShapeaisShapenewAIS_Shape(shape);aisShape-SetDisplayMode(AIS_Shaded);m_context-Display(aisShape,AIS_Shaded,-1,false);if(m_context-IsDisplayed(aisShape)){aisaisShape;m_context-Erase(ais,false);}else{m_context-Remove(aisShape,false);}}catch(...){}}if(ais.IsNull()){try{occ::handleXCAFPrs_AISObjectxcafAisnewXCAFPrs_AISObject(label);xcafAis-SetDisplayMode(AIS_Shaded);m_context-Display(xcafAis,AIS_Shaded,-1,false);if(m_context-IsDisplayed(xcafAis)){aisxcafAis;m_context-Erase(ais,false);}else{m_context-Remove(xcafAis,false);}}catch(...){}}if(!ais.IsNull()){m_aisObjects[graphNodeId]ais;}returnais;}e、视图初始化voidOcctViewerWidget::showEvent(QShowEvent*event){// 延迟初始化if(!m_isCreated){initOcctViewer();}}voidOcctViewerWidget::initOcctEnv(){occ::handleOpenGl_GraphicDriverFactoryfactorynewOpenGl_GraphicDriverFactory();Graphic3d_GraphicDriverFactory::RegisterFactory(factory,true);occ::handleGraphic3d_GraphicDriverFactorydriverFactoryGraphic3d_GraphicDriverFactory::DefaultDriverFactory();if(driverFactory.IsNull())return;m_displayConnectionnewAspect_DisplayConnection();m_driverdriverFactory-CreateDriver(m_displayConnection);if(m_driver.IsNull())return;// 创建视图管理器m_viewernewV3d_Viewer(m_driver);m_viewer-SetDefaultViewSize(1000.0);m_viewer-SetDefaultViewProj(V3d_XposYnegZpos);m_viewer-SetComputedMode(true);m_viewer-SetDefaultComputedMode(true);m_viewer-SetDefaultLights();m_viewer-SetLightOn();// 创建交互上下文m_contextnewAIS_InteractiveContext(m_viewer);m_context-SetPixelTolerance(10);// 设置选择像素差// 创建内部视图m_viewm_context-CurrentViewer()-CreateView();}voidOcctViewerWidget::initOcctViewer(){// m_occtWindow new OcctWindow(this);WId window_handle(WId)winId();m_occtWindownewWNT_Window((Aspect_Handle)window_handle);m_view-SetWindow(m_occtWindow);if(!m_occtWindow-IsMapped()){m_occtWindow-Map();}m_view-SetBackgroundColor(Quantity_NOC_BLACK);m_view-MustBeResized();m_view-Camera()-SetProjectionType(Graphic3d_Camera::Projection_Orthographic);showViewCube();m_isCreatedtrue;isometric();fill();}项目源码Windows 环境 OCCT 8.0 编译构建及与 Qt6 项目集成对你有用就点个赞以后需要用到就收藏⭐