本篇主要在qt做一个例子读取cad文件数据,使用的开源库是dxflib。用到dxflib的DL_CreationAdapter,DL_Dxf。DL_Dxf是用来读取.dxf文件的类,DL_CreatinAdapter是一个容器,当DL_Dxf加载.dxf文件后,就会响应DL_CreationAdapter这个类,读取cad数据。
我们来看看他的工作原理:
//自己声明一个类继承DL_CreationAdapter
class MyDxfFilter : public DL_CreationAdapter {
//重写虚函数来把度出来的数据保存到自己设计好的数据结构中
virtual void addLine(const DL_LineData& d);
...
}
void MyDxfFilter::addLine(const DL_LineData& d) {
std::cout << "Line: " << d.x1 << "/" << d.y1
<< " " << d.x2 << "/" << d.y2 << std::endl;
}
MyDxfFilter f;
DL_Dxf dxf;
//读取.dxf文件
if (!dxf.in("drawing.dxf", &f)) {
std::cerr << "drawing.dxf could not be opened.\n";
}
在这段程序中,当dxf.in("drawing.dxf", &f)读取.dxf文件成功了,如果文件中有很多line,那么f对象会一直递归调用虚函数接口addLine(),直到所有的line都读完。
重这个特征,我们就可以把所有我们要读取的数据都出来了!
直接上程序!:
entitiesDatas.h
#ifndef ENTITIESDATAS_H
#define ENTITIESDATAS_H
#include <QDebug>
#include "dl_dxf.h"
#include "dl_creationadapter.h"
#include "dl_attributes.h"
#include "dl_codes.h"
#include "dl_entities.h"
#include "dl_exception.h"
#include "dl_global.h"
#include "dl_writer.h"
#include "dl_writer_ascii.h"
#include <QList>
#include <QString>
class EntitiesDatas:public DL_CreationAdapter
{
public:
// explicit EntitiesDatas();
virtual void EntitiesDatas::addPoint(const DL_PointData &d){
points.append(d);
qDebug()<<"^^^^^^^^^^^^^^^^^^^^^^^^^^^^add point";
}
virtual void EntitiesDatas::addLine(const DL_LineData &d){
lines.append(d);
qDebug()<<"~~~~~~~~~~~~~~~~~~~~~~~~~~add line";
}
virtual void EntitiesDatas::addArc(const DL_ArcData &d){
arcs.append(d);
qDebug()<<"#######################add arc";
}
virtual void EntitiesDatas::addCircle(const DL_CircleData &d){
circles.append(d);
qDebug()<<"!!!!!!!!!!!!!!!!!!!!!!!!add circle";
}
virtual void EntitiesDatas::addEllipse(const DL_EllipseData &d){
ellipses.append(d);
qDebug()<<"%%%%%%%%%%%%