39 #include <QTextStream> 47 #include <ogr_srs_api.h> 48 #include <cpl_error.h> 52 #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1800 53 #define TO8F(x) (x).toUtf8().constData() 55 #define TO8F(x) QFile::encodeName( x ).constData() 77 const QString &theVectorFileName,
99 srs, driverName, datasourceOptions, layerOptions, newFilename,
nullptr,
114 init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName,
115 datasourceOptions, layerOptions, newFilename,
nullptr,
142 init( vectorFileName, fileEncoding, fields, geometryType, srs, driverName,
143 datasourceOptions, layerOptions, newFilename, fieldValueConverter,
147 void QgsVectorFileWriter::init(
QString vectorFileName,
162 if ( vectorFileName.
isEmpty() )
169 if ( driverName ==
"MapInfo MIF" )
173 else if ( driverName ==
"SpatiaLite" )
176 if ( !datasourceOptions.
contains(
"SPATIALITE=YES" ) )
178 datasourceOptions.
append(
"SPATIALITE=YES" );
181 else if ( driverName ==
"DBF file" )
184 if ( !layerOptions.
contains(
"SHPT=NULL" ) )
186 layerOptions.
append(
"SHPT=NULL" );
196 OGRSFDriverH poDriver;
220 if ( driverName ==
"ESRI Shapefile" && !vectorFileName.
endsWith(
".shp", Qt::CaseInsensitive ) )
222 vectorFileName +=
".shp";
224 else if ( driverName ==
"DBF file" && !vectorFileName.
endsWith(
".dbf", Qt::CaseInsensitive ) )
226 vectorFileName +=
".dbf";
229 #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM < 1700 232 for (
int i = 0; i < fields.
count(); ++i )
234 QString name = fields[i].name().left( 10 );
237 mErrorMessage =
QObject::tr(
"trimming attribute name '%1' to ten significant characters produces duplicate column name." )
238 .
arg( fields[i].name() );
255 Q_FOREACH (
const QString& ext, allExts )
257 if ( vectorFileName.
endsWith(
'.' + ext, Qt::CaseInsensitive ) )
266 vectorFileName +=
'.' + allExts[0];
272 if ( vectorFileName.
endsWith(
".gdb", Qt::CaseInsensitive ) )
274 QDir dir( vectorFileName );
278 QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst );
303 char **options =
nullptr;
304 if ( !datasourceOptions.
isEmpty() )
306 options =
new char *[ datasourceOptions.
size()+1 ];
307 for (
int i = 0; i < datasourceOptions.
size(); i++ )
310 options[i] = CPLStrdup( datasourceOptions[i].toLocal8Bit().constData() );
312 options[ datasourceOptions.
size()] =
nullptr;
317 mDS = OGR_Dr_CreateDataSource( poDriver,
TO8F( vectorFileName ), options );
319 mDS = OGROpen(
TO8F( vectorFileName ), TRUE,
nullptr );
323 for (
int i = 0; i < datasourceOptions.
size(); i++ )
324 CPLFree( options[i] );
341 QString layerName( layerNameIn );
347 const int layer_count = OGR_DS_GetLayerCount(
mDS );
348 for (
int i = 0; i < layer_count; i++ )
350 OGRLayerH hLayer = OGR_DS_GetLayer(
mDS, i );
351 if ( EQUAL( OGR_L_GetName( hLayer ),
TO8F( layerName ) ) )
353 if ( OGR_DS_DeleteLayer(
mDS, i ) != OGRERR_NONE )
371 QgsDebugMsg(
"Opened data source in update mode" );
378 QgsDebugMsg(
"error finding QTextCodec for " + fileEncoding );
385 QgsDebugMsg(
"error finding QTextCodec for " + enc );
403 int optIndex = layerOptions.
indexOf(
"FEATURE_DATASET=" );
404 if ( optIndex != -1 )
411 options =
new char *[ layerOptions.
size()+1 ];
412 for (
int i = 0; i < layerOptions.
size(); i++ )
415 options[i] = CPLStrdup( layerOptions[i].toLocal8Bit().constData() );
417 options[ layerOptions.
size()] =
nullptr;
421 CPLSetConfigOption(
"SHAPE_ENCODING",
"" );
423 if ( driverName ==
"DGN" )
425 mLayer = OGR_DS_GetLayerByName(
mDS,
"elements" );
438 for (
int i = 0; i < layerOptions.
size(); i++ )
439 CPLFree( options[i] );
445 if ( !settings.
value(
"/qgis/ignoreShapeEncoding",
true ).
toBool() )
447 CPLSetConfigOption(
"SHAPE_ENCODING",
nullptr );
454 QString layerName = vectorFileName.
left( vectorFileName.
indexOf(
".shp", Qt::CaseInsensitive ) );
455 QFile prjFile( layerName +
".qpj" );
456 if ( prjFile.
open( QIODevice::WriteOnly ) )
464 QgsDebugMsg(
"Couldn't open file " + layerName +
".qpj" );
481 OGRFeatureDefnH defn = OGR_L_GetLayerDefn(
mLayer );
497 fldIdx < fields.
count(); ++fldIdx )
499 QgsField attrField = fields[fldIdx];
501 if ( fieldValueConverter )
517 OGRFieldType ogrType = OFTString;
518 int ogrWidth = attrField.
length();
519 int ogrPrecision = attrField.
precision();
520 if ( ogrPrecision > 0 )
523 switch ( attrField.
type() )
525 #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM < 2000000 526 case QVariant::LongLong:
528 ogrWidth = ogrWidth > 0 && ogrWidth <= 21 ? ogrWidth : 21;
532 case QVariant::LongLong:
534 const char* pszDataTypes = GDALGetMetadataItem( poDriver, GDAL_DMD_CREATIONFIELDDATATYPES, NULL );
535 if ( pszDataTypes && strstr( pszDataTypes,
"Integer64" ) )
536 ogrType = OFTInteger64;
539 ogrWidth = ogrWidth > 0 && ogrWidth <= 20 ? ogrWidth : 20;
544 case QVariant::String:
546 if ( ogrWidth <= 0 || ogrWidth > 255 )
551 ogrType = OFTInteger;
552 ogrWidth = ogrWidth > 0 && ogrWidth <= 10 ? ogrWidth : 10;
556 case QVariant::Double:
576 case QVariant::DateTime:
584 ogrType = OFTDateTime;
599 for ( i = 0; i < 10; i++ )
604 for ( j = 0; j < fields.
size() && name.compare( fields[j].name(), Qt::CaseInsensitive ) != 0; j++ )
607 if ( j == fields.
size() )
625 OGR_Fld_SetWidth( fld, ogrWidth );
628 if ( ogrPrecision >= 0 )
630 OGR_Fld_SetPrecision( fld, ogrPrecision );
638 if ( OGR_L_CreateField(
mLayer, fld,
true ) != OGRERR_NONE )
645 OGR_Fld_Destroy( fld );
648 OGR_Fld_Destroy( fld );
651 QgsDebugMsg(
QString(
"returned field index for %1: %2" ).arg( name ).arg( ogrIdx ) );
652 if ( ogrIdx < 0 || existingIdxs.
contains( ogrIdx ) )
654 #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM < 1700 657 int fieldCount = OGR_FD_GetFieldCount( defn );
659 OGRFieldDefnH fdefn = OGR_FD_GetFieldDefn( defn, fieldCount - 1 );
662 const char *fieldName = OGR_Fld_GetNameRef( fdefn );
664 if ( attrField.
name().
left( strlen( fieldName ) ) == fieldName )
666 ogrIdx = fieldCount - 1;
671 ogrIdx = OGR_FD_GetFieldCount( defn ) - 1;
685 existingIdxs.
insert( ogrIdx );
691 for (
int fldIdx = 0; fldIdx < fields.
count(); ++fldIdx )
706 *newFilename = vectorFileName;
722 datasetOptions.
clear();
723 layerOptions.
clear();
725 driverMetadata.
insert(
"AVCE00",
727 "Arc/Info ASCII Coverage",
737 datasetOptions.
clear();
738 layerOptions.
clear();
742 "systems default line termination conventions. " 743 "This may be overridden here." ),
752 QObject::tr(
"By default, BNA files are created in multi-line format. " 753 "For each record, the first line contains the identifiers and the " 754 "type/number of coordinates to follow. Each following line contains " 755 "a pair of coordinates." ),
760 QObject::tr(
"BNA records may contain from 2 to 4 identifiers per record. " 761 "Some software packages only support a precise number of identifiers. " 762 "You can override the default value (2) by a precise value" ),
767 <<
"NB_SOURCE_FIELDS",
772 QObject::tr(
"The BNA writer will try to recognize ellipses and circles when writing a polygon. " 773 "This will only work if the feature has previously been read from a BNA file. " 774 "As some software packages do not support ellipses/circles in BNA data file, " 775 "it may be useful to tell the writer by specifying ELLIPSES_AS_ELLIPSES=NO not " 776 "to export them as such, but keep them as polygons." ),
781 QObject::tr(
"Limit the number of coordinate pairs per line in multiline format." ),
786 QObject::tr(
"Set the number of decimal for coordinates. Default value is 10." ),
790 driverMetadata.
insert(
"BNA",
802 datasetOptions.
clear();
803 layerOptions.
clear();
806 QObject::tr(
"By default when creating new .csv files they " 807 "are created with the line termination conventions " 808 "of the local platform (CR/LF on Win32 or LF on all other systems). " 809 "This may be overridden through the use of the LINEFORMAT option." ),
818 QObject::tr(
"By default, the geometry of a feature written to a .csv file is discarded. " 819 "It is possible to export the geometry in its WKT representation by " 820 "specifying GEOMETRY=AS_WKT. It is also possible to export point geometries " 821 "into their X,Y,Z components by specifying GEOMETRY=AS_XYZ, GEOMETRY=AS_XY " 822 "or GEOMETRY=AS_YX." ),
833 QObject::tr(
"Create the associated .csvt file to describe the type of each " 834 "column of the layer and its optional width and precision." ),
848 QObject::tr(
"Write a UTF-8 Byte Order Mark (BOM) at the start of the file." ),
852 driverMetadata.
insert(
"CSV",
854 "Comma Separated Value [CSV]",
864 datasetOptions.
clear();
865 layerOptions.
clear();
868 QObject::tr(
"Override the type of shapefile created. " 869 "Can be one of NULL for a simple .dbf file with no .shp file, POINT, " 870 "ARC, POLYGON or MULTIPOINT for 2D, or POINTZ, ARCZ, POLYGONZ or " 871 "MULTIPOINTZ for 3D;" ) +
872 #
if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM < GDAL_COMPUTE_VERSION(2,1,0)
873 QObject::tr(
" Shapefiles with measure values are not supported," 874 " nor are MULTIPATCH files." ) +
876 #
if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,1,0)
877 QObject::tr(
" POINTM, ARCM, POLYGONM or MULTIPOINTM for measured geometries" 878 " and POINTZM, ARCZM, POLYGONZM or MULTIPOINTZM for 3D measured" 881 #
if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,2,0)
882 QObject::tr(
" MULTIPATCH files are supported since GDAL 2.2." ) +
895 #
if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,1,0)
905 #
if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,2,0)
917 QObject::tr(
"set the encoding value in the DBF file. " 918 "The default value is LDID/87. It is not clear " 919 "what other values may be appropriate." ),
927 QObject::tr(
"Set to YES to resize fields to their optimal size." ),
931 driverMetadata.
insert(
"ESRI",
943 datasetOptions.
clear();
944 layerOptions.
clear();
946 driverMetadata.
insert(
"DBF File",
958 datasetOptions.
clear();
959 layerOptions.
clear();
961 driverMetadata.
insert(
"FMEObjects Gateway",
963 "FMEObjects Gateway",
973 datasetOptions.
clear();
974 layerOptions.
clear();
977 QObject::tr(
"Set to YES to write a bbox property with the bounding box " 978 "of the geometries at the feature and feature collection level." ),
983 QObject::tr(
"Maximum number of figures after decimal separator to write in coordinates. " 984 "Default to 15. Truncation will occur to remove trailing zeros." ),
988 driverMetadata.
insert(
"GeoJSON",
1001 datasetOptions.
clear();
1002 layerOptions.
clear();
1005 QObject::tr(
"whether the document must be in RSS 2.0 or Atom 1.0 format. " 1006 "Default value : RSS" ),
1014 QObject::tr(
"The encoding of location information. Default value : SIMPLE. " 1015 "W3C_GEO only supports point geometries. " 1016 "SIMPLE or W3C_GEO only support geometries in geographic WGS84 coordinates." ),
1025 QObject::tr(
"If defined to YES, extension fields will be written. " 1026 "If the field name not found in the base schema matches " 1027 "the foo_bar pattern, foo will be considered as the namespace " 1028 "of the element, and a <foo:bar> element will be written. " 1029 "Otherwise, elements will be written in the <ogr:> namespace." ),
1034 QObject::tr(
"If defined to NO, only <entry> or <item> elements will be written. " 1035 "The user will have to provide the appropriate header and footer of the document." ),
1040 QObject::tr(
"XML content that will be put between the <channel> element and the " 1041 "first <item> element for a RSS document, or between the xml tag and " 1042 "the first <entry> element for an Atom document. " ),
1047 QObject::tr(
"Value put inside the <title> element in the header. " 1048 "If not provided, a dummy value will be used as that element is compulsory." ),
1053 QObject::tr(
"Value put inside the <description> element in the header. " 1054 "If not provided, a dummy value will be used as that element is compulsory." ),
1059 QObject::tr(
"Value put inside the <link> element in the header. " 1060 "If not provided, a dummy value will be used as that element is compulsory." ),
1065 QObject::tr(
"Value put inside the <updated> element in the header. " 1066 "Should be formatted as a XML datetime. " 1067 "If not provided, a dummy value will be used as that element is compulsory." ),
1072 QObject::tr(
"Value put inside the <author><name> element in the header. " 1073 "If not provided, a dummy value will be used as that element is compulsory." ),
1078 QObject::tr(
"Value put inside the <id> element in the header. " 1079 "If not provided, a dummy value will be used as that element is compulsory." ),
1083 driverMetadata.
insert(
"GeoRSS",
1096 datasetOptions.
clear();
1097 layerOptions.
clear();
1100 QObject::tr(
"If provided, this URI will be inserted as the schema location. " 1101 "Note that the schema file isn't actually accessed by OGR, so it " 1102 "is up to the user to ensure it will match the schema of the OGR " 1103 "produced GML data file." ),
1108 QObject::tr(
"This writes a GML application schema file to a corresponding " 1109 ".xsd file (with the same basename). If INTERNAL is used the " 1110 "schema is written within the GML file, but this is experimental " 1111 "and almost certainly not valid XML. " 1112 "OFF disables schema generation (and is implicit if XSISCHEMAURI is used)." ),
1121 QObject::tr(
"This is the prefix for the application target namespace." ),
1126 QObject::tr(
"Can be set to TRUE to avoid writing the prefix of the " 1127 "application target namespace in the GML file." ),
1132 QObject::tr(
"Defaults to 'http://ogr.maptools.org/'. " 1133 "This is the application target namespace." ),
1134 "http://ogr.maptools.org/" 1138 QObject::tr(
"If not specified, GML2 will be used." ),
1148 QObject::tr(
"only valid when FORMAT=GML3/GML3Degree/GML3.2) Default to YES. " 1149 "If YES, SRS with EPSG authority will be written with the " 1150 "'urn:ogc:def:crs:EPSG::' prefix. In the case, if the SRS is a " 1151 "geographic SRS without explicit AXIS order, but that the same " 1152 "SRS authority code imported with ImportFromEPSGA() should be " 1153 "treated as lat/long, then the function will take care of coordinate " 1154 "order swapping. If set to NO, SRS with EPSG authority will be " 1155 "written with the 'EPSG:' prefix, even if they are in lat/long order." ),
1160 QObject::tr(
"only valid when FORMAT=GML3/GML3Degree/GML3.2) Default to YES. " 1161 "If set to NO, the <gml:boundedBy> element will not be written for " 1167 QObject::tr(
"Default to YES. If YES, the output will be indented with spaces " 1168 "for more readability, but at the expense of file size." ),
1173 driverMetadata.
insert(
"GML",
1175 "Geography Markup Language [GML]",
1186 datasetOptions.
clear();
1187 layerOptions.
clear();
1190 QObject::tr(
"Human-readable identifier (e.g. short name) for the layer content" ),
1195 QObject::tr(
"Human-readable description for the layer content" ),
1200 QObject::tr(
"Name for the feature identifier column" ),
1209 #if defined(GDAL_COMPUTE_VERSION) && GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,0,0) 1211 QObject::tr(
"If a spatial index must be created." ),
1216 driverMetadata.
insert(
"GPKG",
1229 datasetOptions.
clear();
1230 layerOptions.
clear();
1232 driverMetadata.
insert(
"GMT",
1234 "Generic Mapping Tools [GMT]",
1244 datasetOptions.
clear();
1245 layerOptions.
clear();
1248 QObject::tr(
"By default when writing a layer whose features are of " 1249 "type wkbLineString, the GPX driver chooses to write " 1250 "them as routes. If FORCE_GPX_TRACK=YES is specified, " 1251 "they will be written as tracks." ),
1256 QObject::tr(
"By default when writing a layer whose features are of " 1257 "type wkbMultiLineString, the GPX driver chooses to write " 1258 "them as tracks. If FORCE_GPX_ROUTE=YES is specified, " 1259 "they will be written as routes, provided that the multilines " 1260 "are composed of only one single line." ),
1265 QObject::tr(
"If GPX_USE_EXTENSIONS=YES is specified, " 1266 "extra fields will be written inside the <extensions> tag." ),
1271 QObject::tr(
"Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS_URL " 1272 "is set. The namespace value used for extension tags. By default, 'ogr'." ),
1277 QObject::tr(
"Only used if GPX_USE_EXTENSIONS=YES and GPX_EXTENSIONS_NS " 1278 "is set. The namespace URI. By default, 'http://osgeo.org/gdal'." ),
1279 "http://osgeo.org/gdal" 1283 QObject::tr(
"By default files are created with the line termination " 1284 "conventions of the local platform (CR/LF on win32 or LF " 1285 "on all other systems). This may be overridden through use " 1286 "of the LINEFORMAT layer creation option which may have a value " 1287 "of CRLF (DOS format) or LF (Unix format)." ),
1295 driverMetadata.
insert(
"GPX",
1297 "GPS eXchange Format [GPX]",
1308 datasetOptions.
clear();
1309 layerOptions.
clear();
1311 driverMetadata.
insert(
"Interlis 1",
1315 "*.itf *.xml *.ili",
1323 datasetOptions.
clear();
1324 layerOptions.
clear();
1326 driverMetadata.
insert(
"Interlis 2",
1330 "*.itf *.xml *.ili",
1338 datasetOptions.
clear();
1339 layerOptions.
clear();
1342 QObject::tr(
"Allows you to specify the field to use for the KML <name> element. " ),
1347 QObject::tr(
"Allows you to specify the field to use for the KML <description> element." ),
1352 QObject::tr(
"Allows you to specify the AltitudeMode to use for KML geometries. " 1353 "This will only affect 3D geometries and must be one of the valid KML options." ),
1356 <<
"relativeToGround" 1361 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,2,0) 1363 QObject::tr(
"The DOCUMENT_ID datasource creation option can be used to specified " 1364 "the id of the root <Document> node. The default value is root_doc." ),
1369 driverMetadata.
insert(
"KML",
1371 "Keyhole Markup Language [KML]",
1382 datasetOptions.
clear();
1383 layerOptions.
clear();
1386 QObject::tr(
"Use this to turn on 'quick spatial index mode'. " 1387 "In this mode writing files can be about 5 times faster, " 1388 "but spatial queries can be up to 30 times slower." ),
1396 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,0,2) 1398 QObject::tr(
"(multiples of 512): Block size for .map files. Defaults " 1399 "to 512. MapInfo 15.2 and above creates .tab files with a " 1400 "blocksize of 16384 bytes. Any MapInfo version should be " 1401 "able to handle block sizes from 512 to 32256." ),
1405 #if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(2,0,0) 1407 QObject::tr(
"xmin,ymin,xmax,ymax: Define custom layer bounds to increase the " 1408 "accuracy of the coordinates. Note: the geometry of written " 1409 "features must be within the defined box." ),
1414 driverMetadata.
insert(
"MapInfo File",
1426 driverMetadata.
insert(
"MapInfo MIF",
1438 datasetOptions.
clear();
1439 layerOptions.
clear();
1442 QObject::tr(
"Determine whether 2D (seed_2d.dgn) or 3D (seed_3d.dgn) " 1443 "seed file should be used. This option is ignored if the SEED option is provided." ),
1453 QObject::tr(
"Indicate whether the whole seed file should be copied. " 1454 "If not, only the first three elements will be copied." ),
1459 QObject::tr(
"Indicates whether the color table should be copied from the seed file." ),
1464 QObject::tr(
"Override the master unit name from the seed file with " 1465 "the provided one or two character unit name." ),
1470 QObject::tr(
"Override the sub unit name from the seed file with the provided " 1471 "one or two character unit name." ),
1476 QObject::tr(
"Override the number of subunits per master unit. " 1477 "By default the seed file value is used." ),
1482 QObject::tr(
"Override the number of UORs (Units of Resolution) " 1483 "per sub unit. By default the seed file value is used." ),
1488 QObject::tr(
"ORIGIN=x,y,z: Override the origin of the design plane. " 1489 "By default the origin from the seed file is used." ),
1493 driverMetadata.
insert(
"DGN",
1505 datasetOptions.
clear();
1506 layerOptions.
clear();
1509 QObject::tr(
"Should update files be incorporated into the base data on the fly. " ),
1517 QObject::tr(
"Should multipoint soundings be split into many single point sounding features. " 1518 "Multipoint geometries are not well handled by many formats, " 1519 "so it can be convenient to split single sounding features with many points " 1520 "into many single point features." ),
1525 QObject::tr(
"Should a DEPTH attribute be added on SOUNDG features and assign the depth " 1526 "of the sounding. This should only be enabled with SPLIT_MULTIPOINT is " 1532 QObject::tr(
"Should all the low level geometry primitives be returned as special " 1533 "IsolatedNode, ConnectedNode, Edge and Face layers." ),
1538 QObject::tr(
"If enabled, numeric attributes assigned an empty string as a value will " 1539 "be preserved as a special numeric value. This option should not generally " 1540 "be needed, but may be useful when translated S-57 to S-57 losslessly." ),
1545 QObject::tr(
"Should LNAM and LNAM_REFS fields be attached to features capturing " 1546 "the feature to feature relationships in the FFPT group of the S-57 file." ),
1551 QObject::tr(
"Should additional attributes relating features to their underlying " 1552 "geometric primitives be attached. These are the values of the FSPT group, " 1553 "and are primarily needed when doing S-57 to S-57 translations." ),
1558 QObject::tr(
"Should attribute values be recoded to UTF-8 from the character encoding " 1559 "specified in the S57 DSSI record." ),
1565 driverMetadata.
insert(
"S57",
1577 datasetOptions.
clear();
1578 layerOptions.
clear();
1580 driverMetadata.
insert(
"SDTS",
1582 "Spatial Data Transfer Standard [SDTS]",
1583 QObject::tr(
"Spatial Data Transfer Standard [SDTS]" ),
1592 datasetOptions.
clear();
1593 layerOptions.
clear();
1596 QObject::tr(
"Can be used to avoid creating the geometry_columns and spatial_ref_sys " 1597 "tables in a new database. By default these metadata tables are created " 1598 "when a new database is created." ),
1613 QObject::tr(
"Controls the format used for the geometry column. Defaults to WKB." 1614 "This is generally more space and processing efficient, but harder " 1615 "to inspect or use in simple applications than WKT (Well Known Text)." ),
1623 QObject::tr(
"Controls whether layer and field names will be laundered for easier use " 1624 "in SQLite. Laundered names will be converted to lower case and some special " 1625 "characters(' - #) will be changed to underscores." ),
1642 QObject::tr(
"column_name1[,column_name2, ...] A list of (String) columns that " 1643 "must be compressed with ZLib DEFLATE algorithm. This might be beneficial " 1644 "for databases that have big string blobs. However, use with care, since " 1645 "the value of such columns will be seen as compressed binary content with " 1646 "other SQLite utilities (or previous OGR versions). With OGR, when inserting, " 1647 "modifying or queryings compressed columns, compression/decompression is " 1648 "done transparently. However, such columns cannot be (easily) queried with " 1649 "an attribute filter or WHERE clause. Note: in table definition, such columns " 1650 "have the 'VARCHAR_deflate' declaration type." ),
1654 driverMetadata.
insert(
"SQLite",
1667 datasetOptions.
clear();
1668 layerOptions.
clear();
1671 QObject::tr(
"Can be used to avoid creating the geometry_columns and spatial_ref_sys " 1672 "tables in a new database. By default these metadata tables are created " 1673 "when a new database is created." ),
1682 QObject::tr(
"Insert the content of the EPSG CSV files into the spatial_ref_sys table. " 1683 "Set to NO for regular SQLite databases." ),
1692 QObject::tr(
"Controls whether layer and field names will be laundered for easier use " 1693 "in SQLite. Laundered names will be converted to lower case and some special " 1694 "characters(' - #) will be changed to underscores." ),
1699 QObject::tr(
"If the database is of the SpatiaLite flavor, and if OGR is linked " 1700 "against libspatialite, this option can be used to control if a spatial " 1701 "index must be created." ),
1706 QObject::tr(
"If the format of the geometry BLOB is of the SpatiaLite flavor, " 1707 "this option can be used to control if the compressed format for " 1708 "geometries (LINESTRINGs, POLYGONs) must be used" ),
1713 QObject::tr(
"Used to force the SRID number of the SRS associated with the layer. " 1714 "When this option isn't specified and that a SRS is associated with the " 1715 "layer, a search is made in the spatial_ref_sys to find a match for the " 1716 "SRS, and, if there is no match, a new entry is inserted for the SRS in " 1717 "the spatial_ref_sys table. When the SRID option is specified, this " 1718 "search (and the eventual insertion of a new entry) will not be done: " 1719 "the specified SRID is used as such." ),
1724 QObject::tr(
"column_name1[,column_name2, ...] A list of (String) columns that " 1725 "must be compressed with ZLib DEFLATE algorithm. This might be beneficial " 1726 "for databases that have big string blobs. However, use with care, since " 1727 "the value of such columns will be seen as compressed binary content with " 1728 "other SQLite utilities (or previous OGR versions). With OGR, when inserting, " 1729 "modifying or queryings compressed columns, compression/decompression is " 1730 "done transparently. However, such columns cannot be (easily) queried with " 1731 "an attribute filter or WHERE clause. Note: in table definition, such columns " 1732 "have the 'VARCHAR_deflate' declaration type." ),
1736 driverMetadata.
insert(
"SpatiaLite",
1748 datasetOptions.
clear();
1749 layerOptions.
clear();
1752 QObject::tr(
"Override the header file used - in place of header.dxf." ),
1757 QObject::tr(
"Override the trailer file used - in place of trailer.dxf." ),
1761 driverMetadata.
insert(
"DXF",
1773 datasetOptions.
clear();
1774 layerOptions.
clear();
1777 QObject::tr(
"Indicates the GeoConcept export file extension. " 1778 "TXT was used by earlier releases of GeoConcept. GXT is currently used." ),
1786 QObject::tr(
"path to the GCT : the GCT file describe the GeoConcept types definitions: " 1787 "In this file, every line must start with //# followed by a keyword. " 1788 "Lines starting with // are comments." ),
1793 QObject::tr(
"defines the feature to be created. The TYPE corresponds to one of the Name " 1794 "found in the GCT file for a type section. The SUBTYPE corresponds to one of " 1795 "the Name found in the GCT file for a sub-type section within the previous " 1800 driverMetadata.
insert(
"Geoconcept",
1812 datasetOptions.
clear();
1813 layerOptions.
clear();
1816 QObject::tr(
"When this option is set, the new layer will be created inside the named " 1817 "FeatureDataset folder. If the folder does not already exist, it will be created." ),
1822 QObject::tr(
"Set name of geometry column in new layer. Defaults to 'SHAPE'." ),
1827 QObject::tr(
"Name of the OID column to create. Defaults to 'OBJECTID'." ),
1831 driverMetadata.
insert(
"FileGDB",
1844 datasetOptions.
clear();
1845 layerOptions.
clear();
1848 QObject::tr(
"By default, the driver will try to detect the data type of fields. If set " 1849 "to STRING, all fields will be of String type." ),
1858 QObject::tr(
"By default, the driver will read the first lines of each sheet to detect " 1859 "if the first line might be the name of columns. If set to FORCE, the driver " 1860 "will consider the first line will be taken as the header line. If set to " 1861 "DISABLE, it will be considered as the first feature. Otherwise " 1862 "auto-detection will occur." ),
1871 driverMetadata.
insert(
"XLSX",
1873 "MS Office Open XML spreadsheet",
1884 datasetOptions.
clear();
1885 layerOptions.
clear();
1888 QObject::tr(
"By default, the driver will try to detect the data type of fields. If set " 1889 "to STRING, all fields will be of String type." ),
1898 QObject::tr(
"By default, the driver will read the first lines of each sheet to detect " 1899 "if the first line might be the name of columns. If set to FORCE, the driver " 1900 "will consider the first line will be taken as the header line. If set to " 1901 "DISABLE, it will be considered as the first feature. Otherwise " 1902 "auto-detection will occur." ),
1911 driverMetadata.
insert(
"ODS",
1913 "Open Document Spreadsheet",
1932 for ( ; it != sDriverMetadata.
constEnd(); ++it )
1934 if ( it.
key().startsWith( driverName ) || it.
value().longName.startsWith( driverName ) )
1936 driverMetadata = it.
value();
1948 OGRwkbGeometryType ogrType =
static_cast<OGRwkbGeometryType
>( type );
1970 OGRFeatureH poFeature = createFeature( feature );
1984 for ( ; symbolIt != symbols.
constEnd(); ++symbolIt )
1986 int nSymbolLayers = ( *symbolIt )->symbolLayerCount();
1987 for (
int i = 0; i < nSymbolLayers; ++i )
1991 if ( it == mSymbolLayerTable.constEnd() )
1999 currentStyle = ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf );
2003 if ( symbolIt != symbols.
constBegin() || i != 0 )
2005 styleString.
append(
';' );
2007 styleString.
append( currentStyle );
2011 OGR_F_SetStyleString( poFeature, currentStyle.toLocal8Bit().constData() );
2012 if ( !writeFeature(
mLayer, poFeature ) )
2024 if ( !writeFeature(
mLayer, poFeature ) )
2030 OGR_F_Destroy( poFeature );
2034 OGRFeatureH QgsVectorFileWriter::createFeature(
QgsFeature& feature )
2039 OGRFeatureH poFeature = OGR_F_Create( OGR_L_GetLayerDefn(
mLayer ) );
2045 OGRErr err = OGR_F_SetFID( poFeature, static_cast<long>( fid ) );
2046 if ( err != OGRERR_NONE )
2049 .arg( feature.
id() )
2050 .arg( err ).
arg( CPLGetLastErrorMsg() )
2058 int fldIdx = it.key();
2059 int ogrField = it.value();
2072 #ifdef OGRNullMarker 2073 OGR_F_SetFieldNull( poFeature, ogrField );
2083 switch ( attrValue.
type() )
2085 #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 2000000 2087 case QVariant::UInt:
2088 OGR_F_SetFieldInteger( poFeature, ogrField, attrValue.
toInt() );
2090 case QVariant::LongLong:
2091 case QVariant::ULongLong:
2092 OGR_F_SetFieldInteger64( poFeature, ogrField, attrValue.
toLongLong() );
2094 case QVariant::String:
2099 OGR_F_SetFieldInteger( poFeature, ogrField, attrValue.
toInt() );
2101 case QVariant::String:
2102 case QVariant::LongLong:
2103 case QVariant::UInt:
2104 case QVariant::ULongLong:
2108 case QVariant::Double:
2109 OGR_F_SetFieldDouble( poFeature, ogrField, attrValue.
toDouble() );
2111 case QVariant::Date:
2112 OGR_F_SetFieldDateTime( poFeature, ogrField,
2118 case QVariant::DateTime:
2125 OGR_F_SetFieldDateTime( poFeature, ogrField,
2135 case QVariant::Time:
2142 OGR_F_SetFieldDateTime( poFeature, ogrField,
2150 case QVariant::Invalid:
2180 OGRGeometryH mGeom2 =
nullptr;
2217 OGR_F_Destroy( poFeature );
2221 OGRErr err = OGR_G_ImportFromWkb( mGeom2, const_cast<unsigned char *>( geom->
asWkb() ), static_cast< int >( geom->
wkbSize() ) );
2222 if ( err != OGRERR_NONE )
2228 OGR_F_Destroy( poFeature );
2233 OGR_F_SetGeometryDirectly( poFeature, mGeom2 );
2238 OGRErr err = OGR_G_ImportFromWkb( ogrGeom, const_cast<unsigned char *>( geom->
asWkb() ), static_cast< int >( geom->
wkbSize() ) );
2240 if ( err != OGRERR_NONE )
2246 OGR_F_Destroy( poFeature );
2251 OGR_F_SetGeometryDirectly( poFeature, ogrGeom );
2266 for (
int i = 0; i < attributes.
size(); i++ )
2268 if ( omap.
find( i ) != omap.
end() )
2273 bool QgsVectorFileWriter::writeFeature( OGRLayerH layer, OGRFeatureH feature )
2275 if ( OGR_L_CreateFeature( layer, feature ) != OGRERR_NONE )
2280 OGR_F_Destroy( feature );
2290 OGR_DS_Destroy(
mDS );
2295 OSRDestroySpatialReference(
mOgrRef );
2309 bool skipAttributeCreation,
2312 double symbologyScale,
2321 if ( destCRS && layer )
2327 errorMessage, datasourceOptions, layerOptions, skipAttributeCreation,
2328 newFilename, symbologyExport, symbologyScale, filterExtent,
2329 overrideGeometryType, forceMulti, includeZ, attributes,
2330 fieldValueConverter );
2344 bool skipAttributeCreation,
2347 double symbologyScale,
2376 : driverName(
"ESRI Shapefile" )
2381 , onlySelectedFeatures( false )
2384 , skipAttributeCreation( false )
2387 , symbologyScale( 1.0 )
2390 , forceMulti( false )
2391 , fieldValueConverter( nullptr )
2411 bool shallTransform =
false;
2417 shallTransform =
true;
2422 outputCRS = &layer->
crs();
2440 else if ( attributes.
isEmpty() )
2447 attributes.
append( idx );
2454 Q_FOREACH (
int attrIdx, attributes )
2463 QString srcFileName = theURIParts[0];
2468 *errorMessage =
QObject::tr(
"Cannot overwrite a OGR layer in place" );
2495 for (
int i = 0; i < fields.
size(); i++ )
2497 if ( fields.
at( i ).
type() == QVariant::LongLong )
2503 fields[i].setType( QVariant::Int );
2539 errorMessage->
clear();
2545 writer->addRendererAttributes( layer, attributes );
2561 bool useFilterRect =
true;
2562 if ( shallTransform )
2571 useFilterRect =
false;
2574 if ( useFilterRect )
2580 filterRectEngine->prepareGeometry();
2603 int n = 0, errors = 0;
2612 writer->startRender( layer );
2615 bool transactionsEnabled =
true;
2617 if ( OGRERR_NONE != OGR_L_StartTransaction( writer->
mLayer ) )
2619 QgsDebugMsg(
"Error when trying to enable transactions on OGRLayer." );
2620 transactionsEnabled =
false;
2623 writer->resetMap( attributes );
2630 if ( shallTransform )
2643 QString msg =
QObject::tr(
"Failed to transform a point while drawing a feature with ID '%1'. Writing stopped. (Exception: %2)" )
2647 *errorMessage = msg;
2664 if ( err !=
NoError && errorMessage )
2666 if ( errorMessage->
isEmpty() )
2668 *errorMessage =
QObject::tr(
"Feature write errors:" );
2674 if ( errors > 1000 )
2678 *errorMessage +=
QObject::tr(
"Stopping after %1 errors" ).
arg( errors );
2688 if ( transactionsEnabled )
2690 if ( OGRERR_NONE != OGR_L_CommitTransaction( writer->
mLayer ) )
2692 QgsDebugMsg(
"Error while committing transaction on OGRLayer." );
2696 writer->stopRender( layer );
2699 if ( errors > 0 && errorMessage && n > 0 )
2701 *errorMessage +=
QObject::tr(
"\nOnly %1 of %2 features written." ).
arg( n - errors ).
arg( n );
2714 const char *suffixes[] = {
".shp",
".shx",
".dbf",
".prj",
".qix",
".qpj" };
2715 for ( std::size_t i = 0; i <
sizeof( suffixes ) /
sizeof( *suffixes ); i++ )
2726 QgsDebugMsg(
QString(
"Removing file %1 failed: %2" ).arg( file, f.errorString() ) );
2745 int const drvCount = OGRGetDriverCount();
2747 for (
int i = 0; i < drvCount; ++i )
2749 OGRSFDriverH drv = OGRGetDriver( i );
2752 QString drvName = OGR_Dr_GetName( drv );
2753 if ( OGR_Dr_TestCapability( drv,
"CreateDataSource" ) != 0 )
2759 resultMap.
insert( filterString, drvName );
2772 int const drvCount = OGRGetDriverCount();
2775 for (
int i = 0; i < drvCount; ++i )
2777 OGRSFDriverH drv = OGRGetDriver( i );
2780 QString drvName = OGR_Dr_GetName( drv );
2781 if ( OGR_Dr_TestCapability( drv,
"CreateDataSource" ) != 0 )
2784 if ( drvName ==
"MapInfo File" )
2786 writableDrivers <<
"MapInfo MIF";
2788 else if ( drvName ==
"SQLite" )
2795 QString option =
"SPATIALITE=YES";
2797 OGRSFDriverH poDriver;
2802 OGRDataSourceH ds = OGR_Dr_CreateDataSource( poDriver,
TO8F(
QString(
"/vsimem/spatialitetest.sqlite" ) ), options );
2805 writableDrivers <<
"SpatiaLite";
2806 OGR_Dr_DeleteDataSource( poDriver,
TO8F(
QString(
"/vsimem/spatialitetest.sqlite" ) ) );
2807 OGR_DS_Destroy( ds );
2810 CPLFree( options[0] );
2812 else if ( drvName ==
"ESRI Shapefile" )
2814 writableDrivers <<
"DBF file";
2816 writableDrivers << drvName;
2821 Q_FOREACH (
const QString& drvName, writableDrivers )
2838 for ( ; it != driverFormatMap.
constEnd(); ++it )
2840 if ( !filterString.
isEmpty() )
2841 filterString +=
";;";
2843 filterString += it.
key();
2845 return filterString;
2859 if ( codecName ==
"System" )
2867 c.
toInt( &isNumber );
2894 #if defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1700 2895 mSymbolLayerTable.clear();
2896 OGRStyleTableH ogrStyleTable = OGR_STBL_Create();
2897 OGRStyleMgrH styleManager = OGR_SM_Create( ogrStyleTable );
2900 int nTotalLevels = 0;
2903 for ( ; symbolIt != symbolList.
end(); ++symbolIt )
2908 int nLevels = ( *symbolIt )->symbolLayerCount();
2909 for (
int i = 0; i < nLevels; ++i )
2911 mSymbolLayerTable.insert(( *symbolIt )->symbolLayer( i ),
QString::number( nTotalLevels ) );
2912 OGR_SM_AddStyle( styleManager,
QString::number( nTotalLevels ).toLocal8Bit(),
2913 ( *symbolIt )->symbolLayer( i )->ogrFeatureStyle( mmsf, musf ).
toLocal8Bit() );
2917 OGR_DS_SetStyleTableDirectly( ds, ogrStyleTable );
2945 startRender( layer );
2967 *errorMessage = msg;
2972 mRenderContext.expressionContext().setFeature( fet );
2975 if ( !featureSymbol )
2981 if ( it == features.
end() )
2985 it.
value().append( fet );
2991 for (
int i = 0; i < symbols.
count(); i++ )
2997 if ( level < 0 || level >= 1000 )
3000 while ( level >= levels.
count() )
3002 levels[level].
append( item );
3007 int nTotalFeatures = 0;
3010 for (
int l = 0; l < levels.
count(); l++ )
3013 for (
int i = 0; i < level.
count(); i++ )
3017 if ( levelIt == features.
end() )
3026 int llayer = item.
layer();
3029 for ( ; featureIt != featureList.
end(); ++featureIt )
3032 OGRFeatureH ogrFeature = createFeature( *featureIt );
3039 QString styleString = levelIt.
key()->symbolLayer( llayer )->ogrFeatureStyle( mmsf, musf );
3043 if ( !writeFeature(
mLayer, ogrFeature ) )
3048 OGR_F_Destroy( ogrFeature );
3053 stopRender( layer );
3055 if ( nErrors > 0 && errorMessage )
3057 *errorMessage +=
QObject::tr(
"\nOnly %1 of %2 features written." ).
arg( nTotalFeatures - nErrors ).
arg( nTotalFeatures );
3074 return 1000 / scaleDenominator;
3091 return scaleDenominator / 1000;
3139 for (
int i = 0; i < rendererAttributes.
size(); ++i )
3152 OGRSFDriverH hDriver =
nullptr;
3153 OGRDataSourceH hDS = OGROpen(
TO8F( datasetName ), TRUE, &hDriver );
3156 QString drvName = OGR_Dr_GetName( hDriver );
3157 QgsVectorFileWriter::EditionCapabilities caps = 0;
3158 if ( OGR_DS_TestCapability( hDS, ODsCCreateLayer ) )
3163 if ( !( drvName ==
"ESRI Shapefile" &&
QFile::exists( datasetName ) ) )
3166 if ( OGR_DS_TestCapability( hDS, ODsCDeleteLayer ) )
3170 int layer_count = OGR_DS_GetLayerCount( hDS );
3173 OGRLayerH hLayer = OGR_DS_GetLayer( hDS, 0 );
3176 if ( OGR_L_TestCapability( hLayer, OLCSequentialWrite ) )
3179 if ( OGR_L_TestCapability( hLayer, OLCCreateField ) )
3186 OGR_DS_Destroy( hDS );
3193 OGRSFDriverH hDriver =
nullptr;
3194 OGRDataSourceH hDS = OGROpen(
TO8F( datasetName ), TRUE, &hDriver );
3202 bool ret = OGR_DS_GetLayerByName( hDS,
TO8F( layerName ) );
3203 OGR_DS_Destroy( hDS );
3213 OGRSFDriverH hDriver =
nullptr;
3214 OGRDataSourceH hDS = OGROpen(
TO8F( datasetName ), TRUE, &hDriver );
3217 OGRLayerH hLayer = OGR_DS_GetLayerByName( hDS,
TO8F( layerName ) );
3220 OGR_DS_Destroy( hDS );
3224 OGRFeatureDefnH defn = OGR_L_GetLayerDefn( hLayer );
3225 Q_FOREACH (
int idx, attributes )
3228 if ( OGR_FD_GetFieldIndex( defn,
TO8F( fld.
name() ) ) < 0 )
3234 OGR_DS_Destroy( hDS );
qlonglong toLongLong(bool *ok) const
Append features to existing layer, but do not create new fields.
Wrapper for iterator of features from vector data provider or vector layer.
Flag to indicate that a new layer can be added to the dataset.
QString toString(Qt::DateFormat format) const
QByteArray fromUnicode(const QString &str) const
int indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
A rectangle specified with double values.
static QMap< QString, QString > supportedFiltersAndFormats()
Returns map with format filter string as key and OGR format key as value.
QString cap(int nth) const
QGis::WkbType wkbType() const
Returns the WKBType or WKBUnknown in case of error.
QString & append(QChar ch)
iterator insert(const Key &key, const T &value)
virtual ~FieldValueConverter()
Destructor.
OutputUnit
The unit of the output.
int size() const
Return number of items.
static OGRwkbGeometryType ogrTypeFromWkbType(QgsWKBTypes::Type type)
Get the ogr geometry type from an internal QGIS wkb type enum.
const Key key(const T &value) const
Flag to indicate that new features can be added to an existing layer.
SymbologyExport symbologyExport
Symbology to export.
WriterError mError
Contains error value if construction was not successful.
static bool deleteShapeFile(const QString &theFileName)
Delete a shapefile (and its accompanying shx / dbf / prf)
rendering with symbol levels (i.e. implements symbols(), symbolForFeature())
void push_back(const T &value)
QVariant maximumValue(int index)
Returns the maximum value for an attribute column or an invalid variant in case of error...
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
bool forceMulti
Set to true to force creation of multi* geometries.
static QString fileFilterString()
Returns filter string that can be used for dialogs.
static Type addZ(Type type)
Adds the z dimension to a WKB type and returns the new type.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
QStringList split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
QDateTime toDateTime() const
SymbologyExport mSymbologyExport
double mSymbologyScaleDenominator
Scale for symbology export (e.g.
virtual QVariant convert(int fieldIdxInLayer, const QVariant &value)
Convert the provided value, for field fieldIdxInLayer.
static void warning(const QString &msg)
Goes to qWarning.
QgsAttributeList attributes
Attributes to export (empty means all unless skipAttributeCreation is set)
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest())
Query the provider for features specified in request.
static Type multiType(Type type)
Returns the multi type for a WKB type.
const_iterator constBegin() const
void setRendererScale(double scale)
const T & at(int i) const
const QgsCoordinateReferenceSystem & crs() const
Returns layer's spatial reference system.
static bool isMultiType(Type type)
Returns true if the WKB type is a multi type.
bool contains(const QString &str, Qt::CaseSensitivity cs) const
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
static void registerOgrDrivers()
Register OGR drivers ensuring this only happens once.
Container of fields for a vector layer.
A geometry is the spatial representation of a feature.
bool addFeature(QgsFeature &feature, QgsFeatureRendererV2 *renderer=nullptr, QGis::UnitType outputUnit=QGis::Meters)
Add feature to the currently opened data source.
WkbType
Used for symbology operations.
const QgsGeometry * constGeometry() const
Gets a const pointer to the geometry object associated with this feature.
QStringList layerOptions
List of OGR layer creation options.
The QGis class provides global constants for use throughout the application.
virtual QList< QString > usedAttributes()=0
Returns a set of attributes required for this renderer.
QString join(const QString &separator) const
A convenience class for writing vector files to disk.
const_iterator insert(const T &value)
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
QString & remove(int position, int n)
static bool hasZ(Type type)
Tests whether a WKB type contains the z-dimension.
QVariant minimumValue(int index)
Returns the minimum value for an attribute column or an invalid variant in case of error...
int wkbSize() const
Returns the size of the WKB in asWkb().
int count() const
Return number of items.
QString tr(const char *sourceText, const char *disambiguation, int n)
QgsVectorFileWriter(const QString &vectorFileName, const QString &fileEncoding, const QgsFields &fields, QGis::WkbType geometryType, const QgsCoordinateReferenceSystem *srs, const QString &driverName="ESRI Shapefile", const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QString *newFilename=nullptr, SymbologyExport symbologyExport=NoSymbology)
Create a new vector file writer.
QTextCodec * codecForLocale()
static EditionCapabilities editionCapabilities(const QString &datasetName)
Return edition capabilites for an existing dataset name.
const QgsField & at(int i) const
Get field at particular index (must be in range 0..N-1)
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)=0
Needs to be called when a new render cycle is started.
QgsFields fields() const
Returns the list of fields of this layer.
virtual void stopRender(QgsRenderContext &context)=0
Needs to be called when a render cycle has finished to clean up.
Create or overwrite file.
double ANALYSIS_EXPORT max(double x, double y)
Returns the maximum of two doubles or the first argument if both are equal.
Flag to indicate that new fields can be added to an existing layer.
bool onlySelectedFeatures
Write only selected features of layer.
int renderingPass() const
static QgsWKBTypes::Type fromOldWkbType(QGis::WkbType type)
Converts from old (pre 2.10) WKB type (OGR) to new WKB type.
Options to pass to writeAsVectorFormat()
QgsFeatureRendererV2 * rendererV2()
Return renderer V2.
The output shall be in millimeters.
QString number(int n, int base)
int count(const T &value) const
virtual Q_DECL_DEPRECATED QgsSymbolV2 * symbolForFeature(QgsFeature &feature)
To be overridden.
void append(const T &value)
QString fromUtf8(const char *str, int size)
static QgsExpressionContextScope * globalScope()
Creates a new scope which contains variables and functions relating to the global QGIS context...
bool rmdir(const QString &dirName) const
int toInt(bool *ok) const
const QgsCoordinateTransform * ct
Transform to reproject exported geometries with, or invalid transform for no transformation.
QString typeName() const
Gets the field type.
#define FID_TO_NUMBER(fid)
static bool 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...
void initAttributes(int fieldCount)
Initialize this feature with the given number of fields.
int toInt(bool *ok, int base) const
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QFileInfoList entryInfoList(QFlags< QDir::Filter > filters, QFlags< QDir::SortFlag > sort) const
QString absoluteFilePath() const
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Get the data source specification.
const_iterator constEnd() const
QStringList datasourceOptions
List of OGR data source creation options.
QGis::UnitType mapUnits() const
Returns the units for the projection used by the CRS.
const char * constData() const
QgsWKBTypes::Type mWkbType
Geometry type which is being used.
The output shall be in map unitx.
static void logMessage(const QString &message, const QString &tag=QString::null, MessageLevel level=WARNING)
add a message to the instance (and create it if necessary)
This class wraps a request for features to a vector layer (or directly its vector data provider)...
~QgsVectorFileWriter()
Close opened shapefile for writing.
FieldValueConverter * mFieldValueConverter
Field value converter.
int symbolLayerCount()
Returns total number of symbol layers contained in the symbol.
bool isEmpty() const
Returns true if the geometry is empty (ie, contains no underlying geometry accessible via geometry)...
Create or overwrite layer.
bool endsWith(const QString &s, Qt::CaseSensitivity cs) const
bool append(const QgsField &field, FieldOrigin origin=OriginProvider, int originIndex=-1)
Append a field. The field must have unique name, otherwise it is rejected (returns false) ...
const unsigned char * asWkb() const
Returns the buffer containing this geometry in WKB format.
ActionOnExistingFile
Combination of CanAddNewLayer, CanAppendToExistingLayer, CanAddNewFieldsToExistingLayer or CanDeleteL...
QgsAttributeList attributeList() const
Returns list of attribute indexes.
QgsFeatureRequest & setFlags(const QgsFeatureRequest::Flags &flags)
Set flags that affect how features will be fetched.
QString driverName
OGR driver to use.
bool usingSymbolLevels() const
Encapsulate a field in an attribute table or data source.
virtual Q_DECL_DEPRECATED QgsSymbolV2List symbols()
For symbol levels.
virtual bool open(QFlags< QIODevice::OpenModeFlag > mode)
FieldValueConverter * fieldValueConverter
Field value converter.
QMap< int, int > mAttrIdxToOgrIdx
Map attribute indizes to OGR field indexes.
QgsRectangle filterExtent
If not empty, only features intersecting the extent will be saved.
OGRSpatialReferenceH mOgrRef
const T value(const Key &key) const
QgsFeatureId id() const
Get the feature ID for this feature.
QByteArray toLocal8Bit() const
iterator find(const Key &key)
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometryV2 *geometry)
Creates and returns a new geometry engine.
bool contains(QChar ch, Qt::CaseSensitivity cs) const
Append features to existing layer, and create new fields if needed.
static WriterError writeAsVectorFormat(QgsVectorLayer *layer, const QString &fileName, const QString &fileEncoding, const QgsCoordinateReferenceSystem *destCRS, const QString &driverName="ESRI Shapefile", bool onlySelected=false, QString *errorMessage=nullptr, const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), bool skipAttributeCreation=false, QString *newFilename=nullptr, SymbologyExport symbologyExport=NoSymbology, double symbologyScale=1.0, const QgsRectangle *filterExtent=nullptr, QgsWKBTypes::Type overrideGeometryType=QgsWKBTypes::Unknown, bool forceMulti=false, bool includeZ=false, QgsAttributeList attributes=QgsAttributeList(), FieldValueConverter *fieldValueConverter=nullptr)
Write contents of vector layer to an (OGR supported) vector formt.
FieldValueConverter()
Constructor.
QgsExpressionContext & expressionContext()
Gets the expression context.
QgsGeometry * geometry()
Get the geometry object associated with this feature.
static QMap< QString, QString > ogrDriverList()
Returns driver list that can be used for dialogs.
QgsWKBTypes::Type overrideGeometryType
Set to a valid geometry type to override the default geometry type for the layer. ...
bool contains(const T &value) const
const char * typeToName(Type typ)
QString errorMessage()
Retrieves error message.
const QgsFeatureIds & selectedFeaturesIds() const
Return reference to identifiers of selected features.
const Key key(const T &value) const
static Type dropM(Type type)
Drops the m dimension (if present) for a WKB type and returns the new type.
QVariant value(const QString &key, const QVariant &defaultValue) const
static QString convertCodecNameForEncodingOption(const QString &codecName)
Converts codec name to string passed to ENCODING layer creation option of OGR Shapefile.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
WriterError hasError()
Checks whether there were any errors in constructor.
QgsAbstractGeometryV2 * geometry() const
Returns the underlying geometry store.
QString fileEncoding
Encoding to use.
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Set feature IDs that should be fetched.
bool skipAttributeCreation
Only write geometries.
double symbologyScale
Scale of symbology.
virtual ~SaveVectorOptions()
Destructor.
Handles storage of information regarding WKB types and their properties.
virtual Q_DECL_DEPRECATED QgsSymbolV2List symbolsForFeature(QgsFeature &feat)
Returns list of symbols used for rendering the feature.
QgsWKBTypes::Type wkbType() const
Returns the WKB type of the geometry.
void setSymbologyScaleDenominator(double d)
QStringList entryList(QFlags< QDir::Filter > filters, QFlags< QDir::SortFlag > sort) const
QTextCodec * codecForName(const QByteArray &name)
const char * typeName() const
Class for storing a coordinate reference system (CRS)
QString toWkt() const
Returns a WKT representation of this CRS.
bool isNull() const
test if the rectangle is null (all coordinates zero or after call to setMinimal()).
static QgsGeometry * fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
ActionOnExistingFile actionOnExistingFile
Action on existing file.
UnitType
Map units that qgis supports.
int transform(const QgsCoordinateTransform &ct)
Transform this geometry as described by CoordinateTransform ct.
Flag to indicate that an existing layer can be deleted.
QString left(int n) const
QString completeBaseName() const
Interface to convert raw field values to their user-friendly value.
QString canonicalPath() const
static Type flatType(Type type)
Returns the flat type for a WKB type.
int indexOf(const QRegExp &rx, int from) const
bool includeZ
Set to true to include z dimension in output.
double toDouble(bool *ok) const
iterator insert(const Key &key, const T &value)
Custom exception class for Coordinate Reference System related exceptions.
static QgsExpressionContextScope * projectScope()
Creates a new scope which contains variables and functions relating to the current QGIS project...
SaveVectorOptions()
Constructor.
QgsSymbolLayerV2 * symbolLayer(int layer)
Returns a specific symbol layers contained in the symbol.
QgsVectorDataProvider * dataProvider()
Returns the data provider.
double ANALYSIS_EXPORT min(double x, double y)
Returns the minimum of two doubles or the first argument if both are equal.
static bool targetLayerExists(const QString &datasetName, const QString &layerName)
Returns whether the target layer already exists.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
QString providerType() const
Return the provider type for this layer.
const_iterator constEnd() const
virtual int capabilities()
returns bitwise OR-ed capabilities of the renderer
QString layerName
Layer name.
bool nextFeature(QgsFeature &f)
const_iterator constBegin() const
static Type to25D(Type type)
Will convert the 25D version of the flat type if supported or Unknown if not supported.
virtual QgsField fieldDefinition(const QgsField &field)
Return a possibly modified field definition.
Geometry is not required. It may still be returned if e.g. required for a filter condition.
SymbologyExport symbologyExport() const
OGRGeometryH createEmptyGeometry(QgsWKBTypes::Type wkbType)
Represents a vector layer which manages a vector based data sets.
QVariant::Type type() const
Gets variant type of the field as it will be retrieved from data source.
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
int compare(const QString &other) const
bool exactMatch(const QString &str) const
QString arg(qlonglong a, int fieldWidth, int base, const QChar &fillChar) const
iterator find(const Key &key)
static QString filterForDriver(const QString &driverName)
Creates a filter for an OGR driver key.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rect)
Set rectangle from which features will be taken.
int fieldNameIndex(const QString &fieldName) const
Returns the index of a field name or -1 if the field does not exist.
static Type singleType(Type type)
Returns the single type for a WKB type.
const T value(const Key &key) const
static bool driverMetadata(const QString &driverName, MetaData &driverMetadata)