使用<include>标签-控件空指针

项目使用toolbar时,因布局需给include标签加id,在activity中使用toolbar的id会报空指针。经排查发现,include标签加id后,不能用toolbar的id,只能用include的id。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目里用到toolbar的时候 由于布局关系需要给include 标签加上一个id,然后在activity中使用toolbar的id以后就会报空指针,几经周转,终于找到原因,原来include标签加上id以后,toolbar的id就不能用,只能用include的id。

感谢这位大佬:使用include标签出现的空指针问题

头文件:#ifndef TCPCLIENT_H #define TCPCLIENT_H #include <QWidget> #include<QTcpSocket> #include <QLineEdit> #include <QTextEdit> #include <QPushButton> #include <QGridLayout> QT_BEGIN_NAMESPACE namespace Ui { class TCPClient; } QT_END_NAMESPACE class TCPClient : public QWidget { Q_OBJECT public: TCPClient(QWidget *parent = nullptr); ~TCPClient(); private: Ui::TCPClient *ui; QLineEdit *adr; QLineEdit *prt; QLineEdit *ipt; QTextEdit *sta; QPushButton *cbt; QPushButton *sbt; QTcpSocket *tcpsocket; bool connected = false; private slots: void toggleConnection(); void sendMessage(); void readPendingDatagrams(); }; #endif // TCPCLIENT_H cpp文件:#include “tcpclient.h” #include “ui_tcpclient.h” TCPClient::TCPClient(QWidget *parent) QWidget(parent) , ui(new Ui::TCPClient) { ui->setupUi(this); adr = new QLineEdit(“127.0.0.1”, this); prt = new QLineEdit(“12345”,this); ipt = new QLineEdit(this); sta = new QTextEdit(this); sta->setReadOnly(true); cbt =new QPushButton(tr(“连接”),this); sbt =new QPushButton(tr(“发送”),this); QGridLayout *grid = new QGridLayout(this); grid->addWidget(adr,0,0,1,1); grid->addWidget(prt,0,2,1,1); grid->addWidget(ipt,4,0,1,3); grid->addWidget(sta,1,0,3,4); grid->addWidget(sbt,4,3,1,1); grid->addWidget(cbt,0,3,1,1); grid->setSpacing(20); connect(cbt, &QPushButton::clicked, this, &TCPClient::toggleConnection); connect(sbt, &QPushButton::clicked, this, &TCPClient::sendMessage); connect(tcpsocket, &QTcpSocket::readyRead, this, &TCPClient::readPendingDatagrams); } TCPClient::~TCPClient() { delete ui; } void TCPClient::toggleConnection() { if (connected) { tcpsocket->disconnectFromHost();//断开与服务器的连接 tcpsocket->close();//关闭通信套接字 connected = false; cbt->setText("连接"); sbt->setEnabled(false); sta->append("已断开连接"); } else { QString IP=adr->text(); quint16 Port=prt->text().toInt(); tcpsocket->connectToHost(IP,Port); connected = true; cbt->setText("断开连接"); sbt->setEnabled(true); connect(tcpsocket,&QTcpSocket::connected,[=](){ sta->setText("服务器连接成功!"); }); connect(tcpsocket,&QTcpSocket::readyRead,[=](){ //获取通信套接字的内容 QString str=tcpsocket->readAll(); //在显示编辑区域显示 sta->append("服务器端:"+str);//不用settext 这样会覆盖之前的消息 });} } void TCPClient::sendMessage() { if(nullptr==tcpsocket)//连接失败则不发送 return; //获取发送的信息 QString str=ipt->text(); //将信息写入到通信套接字 tcpsocket->write(str.toUtf8().data()); //将自己的信息显示在聊天窗口 sta->append("客服端:"+str); } void TCPClient::readPendingDatagrams() { connect(tcpsocket,&QTcpSocket::readyRead,={ //获取通信套接字的内容 QString str=tcpsocket->readAll(); //在显示编辑区域显示 sta->append(“服务器端:”+str);//不用settext 这样会覆盖之前的消息 }); } 这是一段qt编写的tcp通信的服务器,但在运行时程序异常关闭,请检查该代码,指出错误并改正
07-15
//初始化 void Form_VTK::init() { colorFunc = vtkSmartPointer<vtkColorTransferFunction>::New(); mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); actor = vtkSmartPointer<vtkActor>::New(); renderer = vtkSmartPointer<vtkRenderer>::New(); scalarBar = vtkSmartPointer<vtkScalarBarActor>::New(); renderWindow = vtkSmartPointer<vtkGenericOpenGLRenderWindow>::New(); // 输出VTK版本信息(用于调试兼容性问题) qDebug() << "VTK版本: " << vtkVersion::GetVTKVersion(); //设置UI vtkWidget = ui->widget; // VTK渲染窗口部件 propertyComboBox = ui->comboBox; // 属性选择下拉框 connect( propertyComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), // 显式指定参数类型 this, &Form_VTK::onPropertyChanged ); propertyComboBox->setEnabled(false); initVTKView(); } //初始化VTK视图 void Form_VTK::initVTKView() { } //加载VTK void Form_VTK::loadVtkData(QString filePath) { bIsInitCompleted = false; // 读取VTK数据 vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New(); reader->SetFileName(filePath.toStdString().c_str()); reader->Update(); polyData = reader->GetOutput(); if (polyData->GetNumberOfPoints() == 0) { qDebug() << "错误:VTK文件无有效数据"; return; } // 初始化属性列表(填充下拉框) vtkPointData* pointData = polyData->GetPointData(); for (int i = 0; i < pointData->GetNumberOfArrays(); i++) { propertyComboBox->addItem(pointData->GetArrayName(i)); } setVtkColorFunc(); // 设置属性颜色 bIsInitCompleted = true; } //卸载VTK void Form_VTK::unloadVtkData() { // 1. 重置标志位 bIsInitCompleted = false; // 2. 释放 VTK 数据对象 if (polyData) { polyData->Initialize(); // 清数据 polyData = nullptr; // 释放指针 } // 3. 重置渲染管线组件 if (mapper) { mapper->RemoveAllInputs(); // 移除输入数据 mapper->SetScalarRange(0, 0); // 重置标量范围 mapper->SetArrayName(nullptr); // 清除数组名 } if (actor) { renderer->RemoveActor(actor); // 从渲染器移除actor actor->SetMapper(nullptr); // 解除与mapper的关联 } if (colorFunc) { colorFunc->RemoveAllPoints(); // 清颜色映射点 colorFunc->Modified(); // 通知管线更新 } if (scalarBar) { renderer->RemoveActor2D(scalarBar); // 移除标量条 scalarBar->SetLookupTable(nullptr); // 解除与颜色映射的关联 scalarBar->SetTitle(""); // 清标题 } // 4. 重置渲染器和渲染窗口 if (renderer) { renderer->RemoveActor2D(actor); renderer->SetBackground(1.0, 1.0, 1.0); // 重置背景色 } if (renderWindow && vtkWidget) { renderWindow->Render(); // 刷新渲染窗口(显示白) } // 5. 重置UI控件 propertyComboBox->clear(); // 清下拉框选项 propertyComboBox->setEnabled(false); // 禁用下拉框 // 6. 输出卸载日志(调试用) qDebug() << "VTK数据已卸载"; } //设置属性颜色 void Form_VTK::setVtkColorFunc() { // 确保存在有效的PolyData if (!polyData || polyData->GetNumberOfPoints() == 0) { qDebug() << "错误:无效的PolyData"; return; } // 获取目标数组(使用第一个数组) vtkPointData* pointData = polyData->GetPointData(); if (!pointData) return; QString strName = pointData->GetArrayName(0); vtkDataArray* targetArray = pointData->GetArray(strName.toStdString().c_str()); if (!targetArray) return; // 关键步骤:设置活动标量 pointData->SetActiveScalars(targetArray->GetName()); // 获取PointData1的范围(min, max) double range[2]; targetArray->GetRange(range); qDebug() << "PointData1 范围: " << range[0] << "到" << range[1]; // 检查是否为有效范围 if (fabs(range[1] - range[0]) < 1e-6) { qDebug() << "警告:数据范围太小,使用默认范围[-1, 1]"; range[0] = -1.0; range[1] = 1.0; } double minVal = range[0]; double maxVal = range[1]; double midVal = (minVal + maxVal) * 0.5; qDebug() << "minVal:" << minVal << " midVal:" << midVal << " maxVal:" << maxVal; // 创建发散色阶(蓝--红) colorFunc->RemoveAllPoints(); colorFunc->SetColorSpaceToDiverging(); colorFunc->AddRGBPoint(minVal, 0.23, 0.299, 0.754); // 深蓝 (最小值) colorFunc->AddRGBPoint(midVal, 0.865, 0.865, 0.865); // 中性灰 (中间值) colorFunc->AddRGBPoint(maxVal, 0.706, 0.016, 0.15); // 深红 (最大值) colorFunc->Build(); // 配置Mapper mapper->SetInputData(polyData); mapper->SetLookupTable(colorFunc); mapper->SetScalarModeToUsePointData(); mapper->ColorByArrayComponent(strName.toStdString().c_str(), -1); mapper->SetScalarRange(minVal, maxVal); // 设置完整数据范围 mapper->ScalarVisibilityOn(); mapper->Modified(); // 配置Actor actor->SetMapper(mapper); // 配置渲染器 renderer->AddActor(actor); renderer->SetBackground(1.0, 1.0, 1.0); //renderer->SetBackground(0.4, 0.4, 0.5); // 浅灰背景(类似ParaView) renderer->ResetCamera(); //标量条 configureScalarBar(true,strName); bool visible = scalarBar->GetVisibility(); // 关联渲染窗口 renderWindow->AddRenderer(renderer); vtkWidget->SetRenderWindow(renderWindow); renderWindow->Render(); } //配置标量条 void Form_VTK::configureScalarBar(bool bInit, QString title) { //------------------------------------------------------------------------------ if(!bInit) { //scalarBar->SetLookupTable(colorFunc); scalarBar->SetTitle(title.toStdString().c_str()); } else { scalarBar->SetLookupTable(colorFunc); scalarBar->SetTitle(title.toStdString().c_str()); scalarBar->SetNumberOfLabels(7); // 解除字体约束 scalarBar->UnconstrainedFontSizeOn(); // 标题字体属性配置 vtkTextProperty* titleProp = scalarBar->GetTitleTextProperty(); titleProp->SetFontSize(16); // 标题字体大小 titleProp->SetFontFamily(VTK_ARIAL); titleProp->SetColor(1, 1, 200); // 标题颜色 // 标签字体属性配置(保持原有) vtkTextProperty* labelProp = scalarBar->GetLabelTextProperty(); labelProp->SetFontSize(13); // 标签字体大小 labelProp->SetFontFamily(VTK_ARIAL); labelProp->SetColor(1, 1, 1); // 标签颜色 // ====== 关键修改:设置标量条宽度和位置 ====== scalarBar->SetOrientationToVertical(); // 确保垂直方向(默认) scalarBar->SetPosition(0.83, 0.1); // 左下角坐标(归一化坐标系) scalarBar->SetPosition2(0.05, 0.8); // 右上角相对偏移(宽度10%,高度80%) renderer->AddActor2D(scalarBar); } //------------------------------------------------------------------------------ } //属性切换 void Form_VTK::onPropertyChanged(int index) { if(!bIsInitCompleted) return; if (index < 0 || !polyData || !propertyComboBox) return; vtkPointData* pointData = polyData->GetPointData(); if (!pointData) return; // 获取当前属性数组 QString strName = pointData->GetArrayName(index); vtkDataArray* selectedArray = pointData->GetArray(strName.toStdString().c_str()); if (!selectedArray) return; // 关键步骤:设置活动标量 pointData->SetActiveScalars(selectedArray->GetName()); // 更新颜色映射范围 double range[2]; selectedArray->GetRange(range); // 获取属性值范围[min, max] qDebug() << strName << " 范围: " << range[0] << "到" << range[1]; if (!std::isfinite(range[0]) || !std::isfinite(range[1])) { qDebug() << "属性范围包含无效数值(NaN或无穷大)"; return; } double minVal = range[0]; double maxVal = range[1]; double midVal = (minVal + maxVal) * 0.5; qDebug() << "minVal:" << minVal << " midVal:" << midVal << " maxVal:" << maxVal; // 创建发散色阶(蓝--红) colorFunc->RemoveAllPoints(); colorFunc->SetColorSpaceToDiverging(); colorFunc->AddRGBPoint(minVal, 0.23, 0.299, 0.754); // 深蓝 (最小值) colorFunc->AddRGBPoint(midVal, 0.865, 0.865, 0.865); // 中性灰 (中间值) colorFunc->AddRGBPoint(maxVal, 0.706, 0.016, 0.15); // 深红 (最大值) colorFunc->Build(); // 配置Mapper mapper->SetInputData(polyData); mapper->SetLookupTable(colorFunc); mapper->SetScalarModeToUsePointData(); mapper->ColorByArrayComponent(strName.toStdString().c_str(), -1); mapper->SetScalarRange(minVal, maxVal); // 设置完整数据范围 mapper->ScalarVisibilityOn(); mapper->Modified(); // 配置Actor actor->SetMapper(mapper); // 配置渲染器 renderer->AddActor(actor); renderer->SetBackground(1.0, 1.0, 1.0); //renderer->SetBackground(0.4, 0.4, 0.5); // 浅灰背景(类似ParaView) renderer->ResetCamera(); // 更新颜色条(确保scalarBar有效) configureScalarBar(false,strName); // 触发渲染更新(确保renderWindow有效) if (renderWindow) { renderWindow->AddRenderer(renderer); vtkWidget->SetRenderWindow(renderWindow); renderWindow->Render(); } } 补充完整initVTKView()接口,我的要求是,先初始化init()并完成对VTK视图界面的初始化,然后loadVtkData()加载VTK对象a,然后unloadVtkData()卸载VTK对象a,最后loadVtkData()加载VTK对象b
07-11
帮我在每行代码后用中文注释出意思与作用,不要改变代码 结构,#pragma once //============================================================================== // WARNING!! This file is overwritten by the Block Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\FXM\Documents\nx_customized\23-RuledFaces\RuledFaces.hpp // // This file was generated by the NX Block Styler // Created by: fxm2hh // Version: NX 2212 // Date: 07-17-2025 (Format: mm-dd-yyyy) // Time: 14:33 // //============================================================================== #ifndef RuledFaces_H_INCLUDED #define RuledFaces_H_INCLUDED //------------------------------------------------------------------------------ //These includes are needed for the following template code //------------------------------------------------------------------------------ #include <uf_defs.h> #include <uf_ui_types.h> // Internal Includes #include <NXOpen/ListingWindow.hxx> #include <NXOpen/Session.hxx> #include <NXOpen/UI.hxx> #include <NXOpen/NXMessageBox.hxx> #include <NXOpen/Callback.hxx> #include <NXOpen/NXException.hxx> #include <NXOpen/BlockStyler_UIBlock.hxx> #include <NXOpen/BlockStyler_BlockDialog.hxx> #include <NXOpen/BlockStyler_PropertyList.hxx> #include <NXOpen/BlockStyler_Group.hxx> #include <NXOpen/BlockStyler_ObjectColorPicker.hxx> #include <NXOpen/BlockStyler_BodyCollector.hxx> #include <NXOpen/BlockStyler_Separator.hxx> #include <NXOpen/BlockStyler_FaceCollector.hxx> #include <iostream> #include <unordered_map> #include <unordered_set> #include "NXOpen_ALL.h" #include "uf_all.h" //------------------------------------------------------------------------------ //Bit Option for Property: EntityType //------------------------------------------------------------------------------ #define EntityType_AllowBodies (1 << 6); //------------------------------------------------------------------------------ //Bit Option for Property: BodyRules //------------------------------------------------------------------------------ #define BodyRules_SingleBody (1 << 0); #define BodyRules_FeatureBodies (1 << 1); #define BodyRules_BodiesinGroup (1 << 2); //------------------------------------------------------------------------------ //Bit Option for Property: EntityType //------------------------------------------------------------------------------ #define EntityType_AllowFaces (1 << 4); #define EntityType_AllowDatums (1 << 5); //------------------------------------------------------------------------------ //Bit Option for Property: FaceRules //------------------------------------------------------------------------------ #define FaceRules_SingleFace (1 << 0); #define FaceRules_RegionFaces (1 << 1); #define FaceRules_TangentFaces (1 << 2); #define FaceRules_TangentRegionFaces (1 << 3); #define FaceRules_BodyFaces (1 << 4); #define FaceRules_FeatureFaces (1 << 5); #define FaceRules_AdjacentFaces (1 << 6); #define FaceRules_ConnectedBlendFaces (1 << 7); #define FaceRules_AllBlendFaces (1 << 8); #define FaceRules_RibFaces (1 << 9); #define FaceRules_SlotFaces (1 <<10); #define FaceRules_BossandPocketFaces (1 <<11); #define FaceRules_MergedRibFaces (1 <<12); #define FaceRules_RegionBoundaryFaces (1 <<13); #define FaceRules_FaceandAdjacentFaces (1 <<14); #define FaceRules_HoleFaces (1 <<15); //------------------------------------------------------------------------------ // Namespaces needed for following template //------------------------------------------------------------------------------ using namespace std; using namespace NXOpen; using namespace NXOpen::BlockStyler; // 哈希函数对象 struct EdgePtrHash { size_t operator()(Edge* edge) const { return std::hash<int>()(edge->Tag()); } }; // 相等比较函数对象 struct EdgePtrEqual { bool operator()(Edge* lhs, Edge* rhs) const { return lhs->Tag() == rhs->Tag(); } }; using EdgeSet = std::unordered_set<Edge*, EdgePtrHash, EdgePtrEqual>; class DllExport RuledFaces { // class members public: static Session* theSession; static UI* theUI; RuledFaces(); ~RuledFaces(); NXOpen::BlockStyler::BlockDialog::DialogResponse Launch(); void print(const NXString&); void print(const string&); void print(const char*); //----------------------- BlockStyler Callback Prototypes --------------------- // The following member function prototypes define the callbacks // specified in your BlockStyler dialog. The empty implementation // of these prototypes is provided in the RuledFaces.cpp file. // You are REQUIRED to write the implementation for these functions. //------------------------------------------------------------------------------ void initialize_cb(); void dialogShown_cb(); int apply_cb(); int ok_cb(); int update_cb(NXOpen::BlockStyler::UIBlock* block); PropertyList* GetBlockProperties(const char* blockID); private: Part* workPart; NXMessageBox* mb; ListingWindow* lw; LogFile* lf; const char* theDlxFileName; NXOpen::BlockStyler::BlockDialog* theDialog; NXOpen::BlockStyler::Group* group0; NXOpen::BlockStyler::ObjectColorPicker* colorPicker0;// Block type: Color Picker NXOpen::BlockStyler::ObjectColorPicker* colorPicker01;// Block type: Color Picker NXOpen::BlockStyler::BodyCollector* bodySelect0;// Block type: Body Collector NXOpen::BlockStyler::Separator* separator0;// Block type: Separator NXOpen::BlockStyler::Group* group;// Block type: Group NXOpen::BlockStyler::FaceCollector* face_select0;// Block type: Face Collector NXOpen::BlockStyler::FaceCollector* face_select01;// Block type: Face Collector NXOpen::BlockStyler::Separator* separator01;// Block type: Separator NXOpen::BlockStyler::ObjectColorPicker* colorPicker02;// Block type: Color Picker private: int _fixed_face_color, _transitional_face_color, _transitioned_face_color; void do_it(); Features::Ruled* doCreateRuledFace(Edge* edge1, Edge* edge2); bool doReplaceFace(Face* origin_face, Face* replace_face); bool isEqualXY(const Point3d& a1, const Point3d& a2, const Point3d& b1, const Point3d& b2, double eps); bool ifContainEqulaEdge(Edge* origin_edge, EdgeSet& edge_set, Edge*& res_edge); vector<Body*> getBodies(); void getFixedAndTransitionalFaces(const vector<Body*>& bodies, vector<Face*>& fixed_faces, vector<Face*>& transitional_faces); EdgeSet getFixedEdgeSet(const vector<Face*>& fixed_faces); bool tryReverseRuledDirection(Features::Ruled* ruled_face); }; #endif //RuledFaces_H_INCLUDED
最新发布
08-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值