【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++内联函数:原理、应用与性能优化实战指南

1. 从“函数调用”说起:为什么我们需要内联函数?写C代码,尤其是性能敏感的程序时,你肯定遇到过这样的纠结:某个函数逻辑很简单,比如就是比较两个数的大小,或者做一次简单的位运算。把它单独封装…

2026/10/25 22:27:47 阅读更多 →
Python RPA自动化安全扫描:集成SonoQuest实现漏洞管理全流程

Python RPA自动化安全扫描:集成SonoQuest实现漏洞管理全流程

1. 项目概述:当RPA遇见安全工具如果你是一名安全工程师、运维人员,或者任何需要与安全扫描工具打交道的开发者,那么你肯定对重复、繁琐的手动操作深恶痛绝。每天登录SonoQuest(一款知名的开源安全扫描与漏洞管理平台)的…

2026/10/26 11:39:47 阅读更多 →
技术人的奇怪爱好:从硬件改造到软件极客的探索价值

技术人的奇怪爱好:从硬件改造到软件极客的探索价值

最近在 Hacker News 上看到一个很有意思的帖子:"Ask HN: Share Your Eccentric Hobby"。表面看是让大家分享奇怪爱好,但仔细想想,这不正是我们技术人最熟悉的场景吗?从收集古董键盘到自制机械臂,从修复老式计…

2026/10/25 14:45:59 阅读更多 →

最新新闻

Electron桌面应用开发实战:从环境搭建到打包发布全流程

Electron桌面应用开发实战:从环境搭建到打包发布全流程

做前端这些年,我大部分时间都在跟浏览器标签页打交道,直到第一次把桌面应用跑起来,才发现原来自己一直被限制在地址栏和刷新按钮围起来的框框里。Electron这个词,最开始是在某段时间频繁出现在同事的讨论里,一个用HTML…

2026/10/26 12:00:21 阅读更多 →
滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

滑盖智能锁T109深度解析:结构原理、安装调试与故障排查

简介:亚太天能T109滑盖智能锁产品说明书是一份PDF格式的官方技术文档,主要面向智能锁安装人员、终端用户及售后维护者,帮助快速掌握产品安装、配置与常见故障处理。全包仅1个PDF文件,大小4.37MB,内容结构清晰&#xff…

2026/10/25 22:36:10 阅读更多 →
PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

PMSM弱磁控制原理与Simulink建模:高速AGV驱动系统设计指南

上个月我在调试一台高速AGV的驱动系统,整车要求空载跑到8m/s,电机转速已经拉到额定点,驱动器的输出电压也顶到了母线电压极限附近。再往上踩速度指令,转速纹丝不动,三相电流反而开始震荡。那会儿我的第一反应就是&…

2026/10/26 4:52:12 阅读更多 →
C++核心知识点:从内存管理到STL的实战指南

C++核心知识点:从内存管理到STL的实战指南

C 这门语言我前前后后折腾了十几年,用它写过嵌入式驱动、做过游戏服务端,也搭过基础组件库。每次看到新人一头扎进"C 核心知识点"这个搜索词,我其实挺感慨的——这门语言的难点从来不是语法多,而是知识点之间的耦合太深…

2026/10/26 12:00:21 阅读更多 →
T109滑盖智能锁怎么装?安装调试与故障排查全攻略

T109滑盖智能锁怎么装?安装调试与故障排查全攻略

简介:亚太天能T109滑盖智能锁产品说明书以PDF格式发布,适合智能锁用户、安装人员与售后维修人员阅读。内容围绕T109系列指纹密码刷卡锁展开,先介绍前面板、后面板、锁体、机械钥匙、电池盒盖等部件名称与功能,再给出完整安装步骤&…

2026/10/26 5:00:37 阅读更多 →
LLM知识降熵:从信息垄断到理解权下放

LLM知识降熵:从信息垄断到理解权下放

你有没有过这种经历:翻开源码注释、论文摘要或者一份专业报告,每个字都认识,连在一起却像天书。想找人聊聊,身边要么没人懂,要么懂的懒得跟你解释。后来我试着把同一段内容丢给一个大语言模型,几秒钟之后&a…

2026/10/26 3:16:46 阅读更多 →

日新闻

周新闻

月新闻

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

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

2026/10/26 12:00:19 阅读更多 →
Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

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

2026/10/25 13:21:54 阅读更多 →
黑夜航拍船只数据集训练YOLOV5模型全流程解析

黑夜航拍船只数据集训练YOLOV5模型全流程解析

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

2026/10/26 8:34:37 阅读更多 →