QGIS接口:将图层导出为shp文件

2022-07-19  本文已影响0人  NullUser

1.QgsVectorFileWriter类

QgsVectorFileWriter类位于qgsvectorfilewriter.h中,可以将矢量图层写入磁盘,支持多种写入格式,如shapefiles、geopackage、Posrgres SQL。

有两种方法来使用该类:

  1. 直接调用static接口QgsVectorFileWriter::writeAsVectorFormat(...)将整个矢量图层保存。
  2. 创建该类的实例,并调用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 );

QgsVectorFileWriter::SaveVectorOptions类

SaveVectorOptions为QgsVectorFileWriter的内部类,调用writeAsVectorFormat()时将该对象传入。
该类内部通过public的成员变量保存了一些设置信息:

2.QGIS中导出图层时的调用栈

在QgisApp的createActions()中,连接了Action的动作槽,其中包含了“图层另存为”action,槽函数调用saveAsFile()。

void QgisApp::createActions()
{
  connect( mActionLayerSaveAs, &QAction::triggered, this, [ = ] { saveAsFile(); } );
}
  1. 调用QgisApp::saveAsFile()后,判断图层类型,如果是矢量图层,则调用QgisApp::saveAsVectorFileGeneral()。
  2. 之后创建“保存”对话框QgsVectorLayerSaveAsDialog,在对话框中输入保存格式(shp文件,postgres sql语句等)、文件编码、字段、范围等信息。
  3. 通过对话框确认保存后,创建SaveVectorOptions对象,并从对话框对象获取关键数据:保存格式、文件编码、字段、范围等。
  4. 创建QgsVectorFileWriterTask对象,并将options传入,该对象由QgsApplication::taskManager()统一调度,最终会调用该对象的run()函数。
  5. 在QgsVectorFileWriterTask::run()内部调用static函数QgsVectorFileWriter::writeAsVectorFormatV2()保存矢量图层。
QgisApp::saveAsFile(...)
└─QgisApp::saveAsVectorFileGeneral(...)
    └─new QgsVectorLayerSaveAsDialog
    └─ dialog->exec()
    └─ QgsVectorFileWriter::SaveVectorOptions options;
    └─new QgsVectorFileWriterTask(...)
          └─ QgsVectorFileWriterTask::run()
                └─ QgsVectorFileWriter::writeAsVectorFormatV2
上一篇 下一篇

猜你喜欢

热点阅读