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

发布时间:2026/9/27 9:56:21

【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 项目集成对你有用就点个赞以后需要用到就收藏⭐

相关新闻

C++运算符重载实战:从分式类到复数类的面向对象设计

C++运算符重载实战:从分式类到复数类的面向对象设计

2026/9/27 9:55:43

1. 项目概述:从分式到复数的优雅跨越 在C面向对象编程的学习和实践中,构建自定义的数值类型是一个经典且极具价值的练习。它不仅能让你深刻理解类与对象、封装、运算符重载等核心概念,更能让你亲手搭建起一个可用的“数学工具”。今天要聊的这…

hot100 完全平方数(279)

hot100 完全平方数(279)

2026/8/24 22:35:35

本题采用完全背包动态规划算法(Unbounded Knapsack DP)解决整数拆分为最少完全平方数之和的组合寻优问题。其核心本质是将正整数 n 视作背包的容量上限,将所有小于等于 n 的完全平方数(1, 4, 9, 16, ...)视作体积与价值…

C/C++条件判断入门:从整除判断掌握if-else逻辑控制

C/C++条件判断入门:从整除判断掌握if-else逻辑控制

2026/8/24 22:35:35

1. 项目概述:从一道经典练习看C/C逻辑控制如果你刚开始接触C或C,在学完变量、输入输出之后,第一个让你感觉“程序开始有思想了”的语法,大概率就是if-else。它让代码不再是简单的顺序执行,而是能根据条件做出判断和选择…

CANN/GE ACL数据集缓冲区添加函数

CANN/GE ACL数据集缓冲区添加函数

2026/9/26 19:14:12

aclmdlAddDatasetBuffer 【免费下载链接】ge GE(Graph Engine)是面向昇腾的图编译器和执行器,提供了计算图优化、多流并行、内存复用和模型下沉等技术手段,加速模型执行效率,减少模型内存占用。 GE 提供对 PyTorch、Te…

用ffmpeg高效批量调整图片尺寸的实战指南

用ffmpeg高效批量调整图片尺寸的实战指南

2026/9/27 1:30:29

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

Transformers 音频特征提取工具库 audio_utils 全解析:从 Mel 刻度换算到对数 Mel 频谱

Transformers 音频特征提取工具库 audio_utils 全解析:从 Mel 刻度换算到对数 Mel 频谱

2026/9/27 1:30:37

Transformers 音频特征提取工具库 audio_utils 全解析:从 Mel 刻度换算到对数 Mel 频谱 【免费下载链接】transformers 🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and mu…

RustFS 多节点集群重启与滚动升级实战:Readiness、Quorum 与 Degraded 模式完全指南

RustFS 多节点集群重启与滚动升级实战:Readiness、Quorum 与 Degraded 模式完全指南

2026/9/27 1:30:35

RustFS 多节点集群重启与滚动升级实战:Readiness、Quorum 与 Degraded 模式完全指南 【免费下载链接】rustfs 🚀2.3x faster than MinIO for 4KB object payloads. RustFS is an open-source, S3-compatible high-performance object storage system sup…

Java Integer缓存揭秘:128陷阱原理、避坑与面试全解

Java Integer缓存揭秘:128陷阱原理、避坑与面试全解

2026/9/27 1:30:34

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

RustFS Scanner 数据用量发布权威性决策:配额准入如何获得可用的权威依据

RustFS Scanner 数据用量发布权威性决策:配额准入如何获得可用的权威依据

2026/9/26 16:36:51

RustFS Scanner 数据用量发布权威性决策:配额准入如何获得可用的权威依据 【免费下载链接】rustfs 🚀2.3x faster than MinIO for 4KB object payloads. RustFS is an open-source, S3-compatible high-performance object storage system supporting mi…

远程协作的工作台整理

远程协作的工作台整理

2026/9/26 14:29:04

远程协作的工作台整理远程协作的核心不是再加一个工具,而是让交接信息足够完整。异步任务要写明目标、输入位置、完成标准和需要决策的人。 工作台的最小配置 将日程、待办、代码和沟通入口收拢到少数固定位置;通知按紧急程度分层。工作台不需要模仿办公…

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能

2026/9/26 13:57:22

持续集成 流水线自动化与 声明式交付 实践:原型怎样变成可用功能分类:[AI/大模型]细分主题:AI 增强型 CI/CD 流水线自动化与 GitOps 实践:Agent 工作流、工具调用与任务拆解:从原型到生产的验收清单很多团队在尝试用大…

容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场

容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场

2026/9/26 23:35:16

容器编排 生产环境运维与排障实战:复盘记录怎样真正派上用场分类:[工程技术]细分主题:Kubernetes 生产环境运维与排障实战:可复制的项目复盘模板与决策记录大部分团队的事故复盘报告,最后都变成了躺在 Confluence 或钉…