1.QgsVectorFileWriter类
QgsVectorFileWriter类位于qgsvectorfilewriter.h中,可以将矢量图层写入磁盘,支持多种写入格式,如shapefiles、geopackage、Posrgres SQL。
有两种方法来使用该类:
- 直接调用static接口QgsVectorFileWriter::writeAsVectorFormat(...)将整个矢量图层保存。
- 创建该类的实例,并调用addFeature(...)
writeAsVectorFormat(...)
该接口有三个版本,writeAsVectorFormat(...)为第一版,writeAsVectorFormatV2(...)为第二版,用以代替writeAsVectorFormat(...)。从QGIS3.20开始,使用writeAsVectorFormatV3(...)代替了writeAsVectorFormatV2(...)
writeAsVectorFormatV3()
/**
* Writes a layer out to a vector file.
* \param layer source layer to write
* \param fileName file name to write to
* \param transformContext coordinate transform context
* \param options save options
* \param newFilename potentially modified file name (output parameter)
* \param newLayer potentially modified layer name (output parameter)
* \param errorMessage will be set to the error message text, if an error occurs while writing the layer
* \returns Error message code, or QgsVectorFileWriter.NoError if the write operation was successful
* \since QGIS 3.20
*/
static QgsVectorFileWriter::WriterError writeAsVectorFormatV3( QgsVectorLayer *layer,
const QString &fileName,
const QgsCoordinateTransformContext &transformContext,
const QgsVectorFileWriter::SaveVectorOptions &options,
QString *errorMessage SIP_OUT = nullptr,
QString *newFilename SIP_OUT = nullptr,
QString *newLayer SIP_OUT = nullptr );
- layer: 需要写入的原图层
- fileName:写入的文件名
- transformContext:坐标转换上下文
- options:与保存相关的设置,如文件编码、图层元数据等。保存的目标格式也通过该对象设置。
- errorMessage:输出参数,如果保存出错,以此返回错误信息。
- newFilename:输出参数
- newLayer:输出参数
QgsVectorFileWriter::SaveVectorOptions类
SaveVectorOptions为QgsVectorFileWriter的内部类,调用writeAsVectorFormat()时将该对象传入。
该类内部通过public的成员变量保存了一些设置信息:
- driverName:驱动名称,对应了保存的格式,如:ESRI Shapefile、geopackage
- layerName:图层名,如果为空的话,将会从文件名产生
- fileEncoding:文件编码,如:UTF-8
- attributes:需要导出的属性,通过该变量过滤出不需要导出的字段
......
2.QGIS中导出图层时的调用栈
在QgisApp的createActions()中,连接了Action的动作槽,其中包含了“图层另存为”action,槽函数调用saveAsFile()。
void QgisApp::createActions()
{
connect( mActionLayerSaveAs, &QAction::triggered, this, [ = ] { saveAsFile(); } );
}
- 调用QgisApp::saveAsFile()后,判断图层类型,如果是矢量图层,则调用QgisApp::saveAsVectorFileGeneral()。
- 之后创建“保存”对话框QgsVectorLayerSaveAsDialog,在对话框中输入保存格式(shp文件,postgres sql语句等)、文件编码、字段、范围等信息。
- 通过对话框确认保存后,创建SaveVectorOptions对象,并从对话框对象获取关键数据:保存格式、文件编码、字段、范围等。
- 创建QgsVectorFileWriterTask对象,并将options传入,该对象由QgsApplication::taskManager()统一调度,最终会调用该对象的run()函数。
- 在QgsVectorFileWriterTask::run()内部调用static函数QgsVectorFileWriter::writeAsVectorFormatV2()保存矢量图层。
QgisApp::saveAsFile(...)
└─QgisApp::saveAsVectorFileGeneral(...)
└─new QgsVectorLayerSaveAsDialog
└─ dialog->exec()
└─ QgsVectorFileWriter::SaveVectorOptions options;
└─new QgsVectorFileWriterTask(...)
└─ QgsVectorFileWriterTask::run()
└─ QgsVectorFileWriter::writeAsVectorFormatV2
网友评论