QgsVectorFileWriter class
A convenience class for writing vector files to disk.
Contents
There are two possibilities how to use this class:
- static call to QgsVectorFileWriter::
writeAsVectorFormat(...) which saves the whole vector layer - create an instance of the class and issue calls to addFeature(...)
Base classes
- class QgsFeatureSink
- An interface for objects which accept features via addFeature(s) methods.
Public types
- struct DriverDetails
- Details of available driver formats.
- class FieldValueConverter
- Interface to convert raw field values to their user-friendly value.
- struct FilterFormatDetails
- Details of available filters and formats.
- class SaveVectorOptions
- Options to pass to writeAsVectorFormat()
- enum ActionOnExistingFile { CreateOrOverwriteFile, CreateOrOverwriteLayer, AppendToLayerNoNewFields, AppendToLayerAddFields }
- Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteLayer.
- enum EditionCapability { CanAddNewLayer = 1 << 0, CanAppendToExistingLayer = 1 << 1, CanAddNewFieldsToExistingLayer = 1 << 2, CanDeleteLayer = 1 << 3 }
- Edition capability flags.
- enum VectorFormatOption { SortRecommended = 1 << 1, SkipNonSpatialFormats = 1 << 2 }
- Options for sorting and filtering vector formats.
- enum WriterError { NoError = 0, ErrDriverNotFound, ErrCreateDataSource, ErrCreateLayer, ErrAttributeTypeUnsupported, ErrAttributeCreationFailed, ErrProjection, ErrFeatureWriteFailed, ErrInvalidLayer, Canceled }
Public static functions
- static auto areThereNewFieldsToCreate(const QString& datasetName, const QString& layerName, QgsVectorLayer* layer, const QgsAttributeList& attributes) -> bool
- Returns whether there are among the attributes specified some that do not exist yet in the layer.
- static auto convertCodecNameForEncodingOption(const QString& codecName) -> QString
- Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile.
- static auto defaultDatasetOptions(const QString& driverName) -> QStringList
- Returns a list of the default dataset options for a specified driver.
- static auto defaultLayerOptions(const QString& driverName) -> QStringList
- Returns a list of the default layer options for a specified driver.
- static auto deleteShapeFile(const QString& fileName) -> bool
- Delete a shapefile (and its accompanying shx / dbf / prf)
- static auto driverForExtension(const QString& extension) -> QString
- Returns the OGR driver name for a specified file extension.
- static auto editionCapabilities(const QString& datasetName) -> QgsVectorFileWriter::EditionCapabilities
- Returns edition capabilities for an existing dataset name.
- static auto fileFilterString(VectorFormatOptions options = SortRecommended) -> QString
- Returns filter string that can be used for dialogs.
- static auto filterForDriver(const QString& driverName) -> QString
- Creates a filter for an OGR driver key.
-
static auto ogrDriverList(VectorFormatOptions options = SortRecommended) -> QList<QgsVectorFileWriter::
DriverDetails> - Returns the driver list that can be used for dialogs.
-
static auto ogrTypeFromWkbType(QgsWkbTypes::
Type type) -> OGRwkbGeometryType - Gets the ogr geometry type from an internal QGIS wkb type enum.
-
static auto supportedFiltersAndFormats(VectorFormatOptions options = SortRecommended) -> QList<QgsVectorFileWriter::
FilterFormatDetails> - Returns a list or pairs, with format filter string as first element and OGR format key as second element.
- static auto supportedFormatExtensions(VectorFormatOptions options = SortRecommended) -> QStringList
- Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
- static auto supportsFeatureStyles(const QString& driverName) -> bool
- Returns true if the specified driverName supports feature styles.
- static auto targetLayerExists(const QString& datasetName, const QString& layerName) -> bool
- Returns whether the target layer already exists.
-
static auto writeAsVectorFormat(QgsVectorLayer* layer,
const QString& fileName,
const QString& fileEncoding,
const QgsCoordinateReferenceSystem& destCRS = QgsCoordinateReferenceSystem(),
const QString& driverName = "GPKG",
bool onlySelected = false,
QString* errorMessage = nullptr,
const QStringList& datasourceOptions = QStringList(),
const QStringList& layerOptions = QStringList(),
bool skipAttributeCreation = false,
QString* newFilename = nullptr,
QgsVectorFileWriter::
SymbologyExport symbologyExport = QgsVectorFileWriter:: NoSymbology, double symbologyScale = 1.0, const QgsRectangle* filterExtent = nullptr, QgsWkbTypes:: Type overrideGeometryType = QgsWkbTypes:: Unknown, bool forceMulti = false, bool includeZ = false, const QgsAttributeList& attributes = QgsAttributeList(), QgsVectorFileWriter:: FieldValueConverter* fieldValueConverter = nullptr, QString* newLayer = nullptr) -> QgsVectorFileWriter:: WriterError - Write contents of vector layer to an (OGR supported) vector format.
-
static auto writeAsVectorFormat(QgsVectorLayer* layer,
const QString& fileName,
const QString& fileEncoding,
const QgsCoordinateTransform& ct,
const QString& driverName = "GPKG",
bool onlySelected = false,
QString* errorMessage = nullptr,
const QStringList& datasourceOptions = QStringList(),
const QStringList& layerOptions = QStringList(),
bool skipAttributeCreation = false,
QString* newFilename = nullptr,
QgsVectorFileWriter::
SymbologyExport symbologyExport = QgsVectorFileWriter:: NoSymbology, double symbologyScale = 1.0, const QgsRectangle* filterExtent = nullptr, QgsWkbTypes:: Type overrideGeometryType = QgsWkbTypes:: Unknown, bool forceMulti = false, bool includeZ = false, const QgsAttributeList& attributes = QgsAttributeList(), QgsVectorFileWriter:: FieldValueConverter* fieldValueConverter = nullptr, QString* newLayer = nullptr) -> QgsVectorFileWriter:: WriterError - Writes a layer out to a vector file.
-
static auto writeAsVectorFormat(QgsVectorLayer* layer,
const QString& fileName,
const QgsVectorFileWriter::
SaveVectorOptions& options, QString* newFilename = nullptr, QString* errorMessage = nullptr, QString* newLayer = nullptr) -> QgsVectorFileWriter:: WriterError - Writes a layer out to a vector file.
Constructors, destructors, conversion operators
-
QgsVectorFileWriter(const QString& vectorFileName,
const QString& fileEncoding,
const QgsFields& fields,
QgsWkbTypes::
Type geometryType, const QgsCoordinateReferenceSystem& srs = QgsCoordinateReferenceSystem(), const QString& driverName = "GPKG", const QStringList& datasourceOptions = QStringList(), const QStringList& layerOptions = QStringList(), QString* newFilename = nullptr, QgsVectorFileWriter:: SymbologyExport symbologyExport = QgsVectorFileWriter:: NoSymbology, QgsFeatureSink::SinkFlags sinkFlags = nullptr, QString* newLayer = nullptr) - Create a new vector file writer.
-
QgsVectorFileWriter(const QString& vectorFileName,
const QString& fileEncoding,
const QgsFields& fields,
QgsWkbTypes::
Type geometryType, const QgsCoordinateReferenceSystem& srs, const QString& driverName, const QStringList& datasourceOptions, const QStringList& layerOptions, QString* newFilename, QgsVectorFileWriter:: SymbologyExport symbologyExport, QgsVectorFileWriter:: FieldValueConverter* fieldValueConverter, const QString& layerName, QgsVectorFileWriter:: ActionOnExistingFile action, QString* newLayer = nullptr) - Create a new vector file writer.
- QgsVectorFileWriter(const QgsVectorFileWriter& rh) deleted
- QgsVectorFileWriter cannot be copied.
- ~QgsVectorFileWriter() override
- Close opened shapefile for writing.
Public functions
- auto addFeature(QgsFeature& feature, QgsFeatureSink::Flags flags = nullptr) -> bool override
- Adds a single feature to the sink.
- auto addFeatures(QgsFeatureList& features, QgsFeatureSink::Flags flags = nullptr) -> bool override
- Adds a list of features to the sink.
-
auto addFeatureWithStyle(QgsFeature& feature,
QgsFeatureRenderer* renderer,
QgsUnitTypes::
DistanceUnit outputUnit = QgsUnitTypes:: DistanceMeters) -> bool - Adds a feature to the currently opened data source, using the style from a specified renderer.
- auto attrIdxToOgrIdx() -> QMap<int, int>
- auto errorMessage() -> QString
- Retrieves error message.
-
auto hasError() -> QgsVectorFileWriter::
WriterError - Checks whether there were any errors in constructor.
- auto operator=(const QgsVectorFileWriter& rh) -> QgsVectorFileWriter& deleted
- QgsVectorFileWriter cannot be copied.
- void setSymbologyScale(double scale)
- Set reference scale for output.
- auto symbologyScale() const -> double
- Returns the reference scale for output.
Protected functions
-
auto createEmptyGeometry(QgsWkbTypes::
Type wkbType) -> OGRGeometryH
Protected variables
- QMap<int, int> mAttrIdxToOgrIdx
- Map attribute indizes to OGR field indexes.
- WriterError mError
- Contains error value if construction was not successful.
- FieldValueConverter* mFieldValueConverter
- Field value converter.
- double mSymbologyScale
- Scale for symbology export (e.g. for symbols units in map units)
-
QgsWkbTypes::
Type mWkbType - Geometry type which is being used.
Enum documentation
enum QgsVectorFileWriter:: ActionOnExistingFile
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteLayer.
| Enumerators | |
|---|---|
| CreateOrOverwriteFile |
Create or overwrite file. |
| CreateOrOverwriteLayer |
Create or overwrite layer. |
| AppendToLayerNoNewFields |
Append features to existing layer, but do not create new fields. |
| AppendToLayerAddFields |
Append features to existing layer, and create new fields if needed. |
enum QgsVectorFileWriter:: EditionCapability
Edition capability flags.
| Enumerators | |
|---|---|
| CanAddNewLayer |
Flag to indicate that a new layer can be added to the dataset. |
| CanAppendToExistingLayer |
Flag to indicate that new features can be added to an existing layer. |
| CanAddNewFieldsToExistingLayer |
Flag to indicate that new fields can be added to an existing layer. Imply CanAppendToExistingLayer. |
| CanDeleteLayer |
Flag to indicate that an existing layer can be deleted. |
enum QgsVectorFileWriter:: VectorFormatOption
Options for sorting and filtering vector formats.
| Enumerators | |
|---|---|
| SortRecommended |
Use recommended sort order, with extremely commonly used formats listed first. |
| SkipNonSpatialFormats |
Filter out any formats which do not have spatial support (e.g. those which cannot save geometries) |
enum QgsVectorFileWriter:: WriterError
| Enumerators | |
|---|---|
| NoError | |
| ErrDriverNotFound | |
| ErrCreateDataSource | |
| ErrCreateLayer | |
| ErrAttributeTypeUnsupported | |
| ErrAttributeCreationFailed | |
| ErrProjection | |
| ErrFeatureWriteFailed | |
| ErrInvalidLayer | |
| Canceled |
Writing was interrupted by manual cancelation. |
Function documentation
static bool QgsVectorFileWriter:: areThereNewFieldsToCreate(const QString& datasetName,
const QString& layerName,
QgsVectorLayer* layer,
const QgsAttributeList& attributes)
Returns whether there are among the attributes specified some that do not exist yet in the layer.
static QStringList QgsVectorFileWriter:: defaultDatasetOptions(const QString& driverName)
Returns a list of the default dataset options for a specified driver.
| Parameters | |
|---|---|
| driverName | name of OGR driver |
static QStringList QgsVectorFileWriter:: defaultLayerOptions(const QString& driverName)
Returns a list of the default layer options for a specified driver.
| Parameters | |
|---|---|
| driverName | name of OGR driver |
static bool QgsVectorFileWriter:: deleteShapeFile(const QString& fileName)
Delete a shapefile (and its accompanying shx / dbf / prf)
| Parameters | |
|---|---|
| fileName | /path/to/file.shp |
| Returns | bool true if the file was deleted successfully |
static QString QgsVectorFileWriter:: driverForExtension(const QString& extension)
Returns the OGR driver name for a specified file extension.
E.g. the driver name for the ".shp" extension is "ESRI Shapefile". If no suitable drivers are found then an empty string is returned.
static QgsVectorFileWriter::EditionCapabilities QgsVectorFileWriter:: editionCapabilities(const QString& datasetName)
Returns edition capabilities for an existing dataset name.
static QString QgsVectorFileWriter:: fileFilterString(VectorFormatOptions options = SortRecommended)
Returns filter string that can be used for dialogs.
The options argument can be used to control the sorting and filtering of returned drivers.
static QList<QgsVectorFileWriter:: DriverDetails> QgsVectorFileWriter:: ogrDriverList(VectorFormatOptions options = SortRecommended)
Returns the driver list that can be used for dialogs.
It contains all OGR drivers plus some additional internal QGIS driver names to distinguish between more supported formats of the same OGR driver.
The returned list consists of structs containing the driver long name (e.g. user-friendly display name for the format) and internal driver short name.
The options argument can be used to control the sorting and filtering of returned drivers.
static OGRwkbGeometryType QgsVectorFileWriter:: ogrTypeFromWkbType(QgsWkbTypes:: Type type)
Gets the ogr geometry type from an internal QGIS wkb type enum.
Will drop M values and convert Z to 2.5D where required.
static QList<QgsVectorFileWriter:: FilterFormatDetails> QgsVectorFileWriter:: supportedFiltersAndFormats(VectorFormatOptions options = SortRecommended)
Returns a list or pairs, with format filter string as first element and OGR format key as second element.
The options argument can be used to control the sorting and filtering of returned formats.
static QStringList QgsVectorFileWriter:: supportedFormatExtensions(VectorFormatOptions options = SortRecommended)
Returns a list of file extensions for supported formats, e.g "shp", "gpkg".
The options argument can be used to control the sorting and filtering of returned formats.
static bool QgsVectorFileWriter:: supportsFeatureStyles(const QString& driverName)
Returns true if the specified driverName supports feature styles.
The driverName argument must be a valid GDAL driver name.
static bool QgsVectorFileWriter:: targetLayerExists(const QString& datasetName,
const QString& layerName)
Returns whether the target layer already exists.
static QgsVectorFileWriter:: WriterError QgsVectorFileWriter:: writeAsVectorFormat(QgsVectorLayer* layer,
const QString& fileName,
const QString& fileEncoding,
const QgsCoordinateReferenceSystem& destCRS = QgsCoordinateReferenceSystem(),
const QString& driverName = "GPKG",
bool onlySelected = false,
QString* errorMessage = nullptr,
const QStringList& datasourceOptions = QStringList(),
const QStringList& layerOptions = QStringList(),
bool skipAttributeCreation = false,
QString* newFilename = nullptr,
QgsVectorFileWriter:: SymbologyExport symbologyExport = QgsVectorFileWriter:: NoSymbology,
double symbologyScale = 1.0,
const QgsRectangle* filterExtent = nullptr,
QgsWkbTypes:: Type overrideGeometryType = QgsWkbTypes:: Unknown,
bool forceMulti = false,
bool includeZ = false,
const QgsAttributeList& attributes = QgsAttributeList(),
QgsVectorFileWriter:: FieldValueConverter* fieldValueConverter = nullptr,
QString* newLayer = nullptr)
Write contents of vector layer to an (OGR supported) vector format.
| Parameters | |
|---|---|
| layer | layer to write |
| fileName | file name to write to |
| fileEncoding | encoding to use |
| destCRS | CRS to reproject exported geometries to, or invalid CRS for no reprojection |
| driverName | OGR driver to use |
| onlySelected | write only selected features of layer |
| errorMessage | pointer to buffer fo error message |
| datasourceOptions | list of OGR data source creation options |
| layerOptions | list of OGR layer creation options |
| skipAttributeCreation | only write geometries |
| newFilename | QString pointer which will contain the new file name created (in case it is different to fileName). |
| symbologyExport | symbology to export |
| symbologyScale | scale of symbology |
| filterExtent | if not a null pointer, only features intersecting the extent will be saved (added in QGIS 2.4) |
| overrideGeometryType | set to a valid geometry type to override the default geometry type for the layer. This parameter allows for conversion of geometryless tables to null geometries, etc (added in QGIS 2.14) |
| forceMulti | set to true to force creation of multi* geometries (added in QGIS 2.14) |
| includeZ | set to true to include z dimension in output. This option is only valid if overrideGeometryType is set. (added in QGIS 2.14) |
| attributes | attributes to export (empty means all unless skipAttributeCreation is set) |
| fieldValueConverter | field value converter (added in QGIS 2.16) |
| newLayer | QString pointer which will contain the new layer name created (in case it is different to the provided layer name) (added in QGIS 3.4, not available in python) |
static QgsVectorFileWriter:: WriterError QgsVectorFileWriter:: writeAsVectorFormat(QgsVectorLayer* layer,
const QString& fileName,
const QString& fileEncoding,
const QgsCoordinateTransform& ct,
const QString& driverName = "GPKG",
bool onlySelected = false,
QString* errorMessage = nullptr,
const QStringList& datasourceOptions = QStringList(),
const QStringList& layerOptions = QStringList(),
bool skipAttributeCreation = false,
QString* newFilename = nullptr,
QgsVectorFileWriter:: SymbologyExport symbologyExport = QgsVectorFileWriter:: NoSymbology,
double symbologyScale = 1.0,
const QgsRectangle* filterExtent = nullptr,
QgsWkbTypes:: Type overrideGeometryType = QgsWkbTypes:: Unknown,
bool forceMulti = false,
bool includeZ = false,
const QgsAttributeList& attributes = QgsAttributeList(),
QgsVectorFileWriter:: FieldValueConverter* fieldValueConverter = nullptr,
QString* newLayer = nullptr)
Writes a layer out to a vector file.
| Parameters | |
|---|---|
| layer | layer to write |
| fileName | file name to write to |
| fileEncoding | encoding to use |
| ct | coordinate transform to reproject exported geometries with, or invalid transform for no transformation |
| driverName | OGR driver to use |
| onlySelected | write only selected features of layer |
| errorMessage | pointer to buffer fo error message |
| datasourceOptions | list of OGR data source creation options |
| layerOptions | list of OGR layer creation options |
| skipAttributeCreation | only write geometries |
| newFilename | QString pointer which will contain the new file name created (in case it is different to fileName). |
| symbologyExport | symbology to export |
| symbologyScale | scale of symbology |
| filterExtent | if not a null pointer, only features intersecting the extent will be saved (added in QGIS 2.4) |
| overrideGeometryType | set to a valid geometry type to override the default geometry type for the layer. This parameter allows for conversion of geometryless tables to null geometries, etc (added in QGIS 2.14) |
| forceMulti | set to true to force creation of multi* geometries (added in QGIS 2.14) |
| includeZ | set to true to include z dimension in output. This option is only valid if overrideGeometryType is set. (added in QGIS 2.14) |
| attributes | attributes to export (empty means all unless skipAttributeCreation is set) |
| fieldValueConverter | field value converter (added in QGIS 2.16) |
| newLayer | QString pointer which will contain the new layer name created (in case it is different to the provided layer name) (added in QGIS 3.4, not available in python) |
static QgsVectorFileWriter:: WriterError QgsVectorFileWriter:: writeAsVectorFormat(QgsVectorLayer* layer,
const QString& fileName,
const QgsVectorFileWriter:: SaveVectorOptions& options,
QString* newFilename = nullptr,
QString* errorMessage = nullptr,
QString* newLayer = nullptr)
Writes a layer out to a vector file.
| Parameters | |
|---|---|
| layer | source layer to write |
| fileName | file name to write to |
| options | options. |
| newFilename | QString pointer which will contain the new file name created (in case it is different to fileName). |
| errorMessage | pointer to buffer fo error message |
| newLayer | QString pointer which will contain the new layer name created (in case it is different to the provided layer name) (added in QGIS 3.4, not available in python) |
QgsVectorFileWriter:: QgsVectorFileWriter(const QString& vectorFileName,
const QString& fileEncoding,
const QgsFields& fields,
QgsWkbTypes:: Type geometryType,
const QgsCoordinateReferenceSystem& srs,
const QString& driverName,
const QStringList& datasourceOptions,
const QStringList& layerOptions,
QString* newFilename,
QgsVectorFileWriter:: SymbologyExport symbologyExport,
QgsVectorFileWriter:: FieldValueConverter* fieldValueConverter,
const QString& layerName,
QgsVectorFileWriter:: ActionOnExistingFile action,
QString* newLayer = nullptr)
Create a new vector file writer.
| Parameters | |
|---|---|
| vectorFileName | file name to write to |
| fileEncoding | encoding to use |
| fields | fields to write |
| geometryType | geometry type of output file |
| srs | spatial reference system of output file |
| driverName | OGR driver to use |
| datasourceOptions | list of OGR data source creation options |
| layerOptions | list of OGR layer creation options |
| newFilename | potentially modified file name (output parameter) |
| symbologyExport | symbology to export |
| fieldValueConverter | field value converter (added in QGIS 2.16) |
| layerName | layer name. If let empty, it will be derived from the filename (added in QGIS 3.0) |
| action | action on existing file (added in QGIS 3.0) |
| newLayer | potentially modified layer name (output parameter) (added in QGIS 3.4) |
bool QgsVectorFileWriter:: addFeature(QgsFeature& feature,
QgsFeatureSink::Flags flags = nullptr) override
Adds a single feature to the sink.
| Returns | true in case of success and false in case of failure |
|---|
Feature addition behavior is controlled by the specified flags.
bool QgsVectorFileWriter:: addFeatures(QgsFeatureList& features,
QgsFeatureSink::Flags flags = nullptr) override
Adds a list of features to the sink.
| Returns | true in case of success and false in case of failure |
|---|
Feature addition behavior is controlled by the specified flags.
bool QgsVectorFileWriter:: addFeatureWithStyle(QgsFeature& feature,
QgsFeatureRenderer* renderer,
QgsUnitTypes:: DistanceUnit outputUnit = QgsUnitTypes:: DistanceMeters)
Adds a feature to the currently opened data source, using the style from a specified renderer.
QMap<int, int> QgsVectorFileWriter:: attrIdxToOgrIdx()
void QgsVectorFileWriter:: setSymbologyScale(double scale)
Set reference scale for output.
The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map.
double QgsVectorFileWriter:: symbologyScale() const
Returns the reference scale for output.
The scale value indicates the scale denominator, e.g. 1000.0 for a 1:1000 map.