1 2 /*************************************************************************** 3 ------------------- 4 begin : Oct 29, 2003 5 copyright : (C) 2003 by Gary E.Sherman 6 email : sherman at mrcc.com 7 ***************************************************************************/ 8 9 /*************************************************************************** 10 * * 11 * This program is free software; you can redistribute it and/or modify * 12 * it under the terms of the GNU General Public License as published by * 13 * the Free Software Foundation; either version 2 of the License, or * 14 * (at your option) any later version. * 15 * * 16 ***************************************************************************/ 17 18 #ifndef QGSVECTORLAYER_H 19 #define QGSVECTORLAYER_H 20 21 22 #include "qgis_core.h" 23 #include <QMap> 24 #include <QSet> 25 #include <QList> 26 #include <QStringList> 27 #include <QFont> 28 #include <QMutex> 29 30 #include "qgis.h" 31 #include "qgsmaplayer.h" 32 #include "qgsfeature.h" 33 #include "qgsfeaturerequest.h" 34 #include "qgsfeaturesource.h" 35 #include "qgsfields.h" 36 #include "qgsvectordataprovider.h" 37 #include "qgsvectorsimplifymethod.h" 38 #include "qgsvectorlayerserverproperties.h" 39 #include "qgseditformconfig.h" 40 #include "qgsattributetableconfig.h" 41 #include "qgsaggregatecalculator.h" 42 #include "qgsfeatureiterator.h" 43 #include "qgsexpressioncontextgenerator.h" 44 #include "qgsexpressioncontextscopegenerator.h" 45 #include "qgsexpressioncontext.h" 46 47 class QPainter; 48 class QImage; 49 50 class QgsAbstractGeometrySimplifier; 51 class QgsActionManager; 52 class QgsConditionalLayerStyles; 53 class QgsCurve; 54 class QgsDiagramLayerSettings; 55 class QgsDiagramRenderer; 56 class QgsEditorWidgetWrapper; 57 class QgsExpressionFieldBuffer; 58 class QgsFeatureRenderer; 59 class QgsGeometry; 60 class QgsGeometryVertexIndex; 61 class QgsMapToPixel; 62 class QgsRectangle; 63 class QgsRectangle; 64 class QgsRelation; 65 class QgsWeakRelation; 66 class QgsRelationManager; 67 class QgsSingleSymbolRenderer; 68 class QgsStoredExpressionManager; 69 class QgsSymbol; 70 class QgsVectorLayerJoinInfo; 71 class QgsVectorLayerEditBuffer; 72 class QgsVectorLayerJoinBuffer; 73 class QgsVectorLayerFeatureCounter; 74 class QgsAbstractVectorLayerLabeling; 75 class QgsPalLayerSettings; 76 class QgsPoint; 77 class QgsFeedback; 78 class QgsAuxiliaryStorage; 79 class QgsAuxiliaryLayer; 80 class QgsGeometryOptions; 81 class QgsStyleEntityVisitorInterface; 82 class QgsVectorLayerTemporalProperties; 83 84 typedef QList<int> QgsAttributeList; 85 typedef QSet<int> QgsAttributeIds; 86 87 // TODO QGIS4: Remove virtual from non-inherited methods (like isModified) 88 89 /** 90 * \ingroup core 91 * \brief Represents a vector layer which manages a vector based data sets. 92 * 93 * The QgsVectorLayer is instantiated by specifying the name of a data provider, 94 * such as postgres or wfs, and url defining the specific data set to connect to. 95 * The vector layer constructor in turn instantiates a QgsVectorDataProvider subclass 96 * corresponding to the provider type, and passes it the url. The data provider 97 * connects to the data source. 98 * 99 * The QgsVectorLayer provides a common interface to the different data types. It also 100 * manages editing transactions. 101 * 102 * Sample usage of the QgsVectorLayer class: 103 * 104 * \code{.py} 105 * uri = "point?crs=epsg:4326&field=id:integer" 106 * scratchLayer = QgsVectorLayer(uri, "Scratch point layer", "memory") 107 * \endcode 108 * 109 * The main data providers supported by QGIS are listed below. 110 * 111 * \section providers Vector data providers 112 * 113 * \subsection memory Memory data providerType (memory) 114 * 115 * The memory data provider is used to construct in memory data, for example scratch 116 * data or data generated from spatial operations such as contouring. There is no 117 * inherent persistent storage of the data. The data source uri is constructed. The 118 * url specifies the geometry type ("point", "linestring", "polygon", 119 * "multipoint","multilinestring","multipolygon"), optionally followed by url parameters 120 * as follows: 121 * 122 * - crs=definition 123 * Defines the coordinate reference system to use for the layer. 124 * definition is any string accepted by QgsCoordinateReferenceSystem::createFromString() 125 * - index=yes 126 * Specifies that the layer will be constructed with a spatial index 127 * - field=name:type(length,precision) 128 * Defines an attribute of the layer. Multiple field parameters can be added 129 * to the data provider definition. type is one of "integer", "double", "string". 130 * 131 * An example url is "Point?crs=epsg:4326&field=id:integer&field=name:string(20)&index=yes" 132 * 133 * Since QGIS 3.4 when closing a project, the application shows a warning about potential data 134 * loss if there are any non-empty memory layers present. If your memory layer should not 135 * trigger such warning, it is possible to suppress that by setting the following custom variable: 136 * 137 * \code{.py} 138 * layer.setCustomProperty("skipMemoryLayersCheck", 1) 139 * \endcode 140 * 141 * 142 * \subsection ogr OGR data provider (ogr) 143 * 144 * Accesses data using the OGR drivers (https://gdal.org/drivers/vector/index.html). The url 145 * is the OGR connection string. A wide variety of data formats can be accessed using this 146 * driver, including file based formats used by many GIS systems, database formats, and 147 * web services. Some of these formats are also supported by custom data providers listed 148 * below. 149 * 150 * \subsection spatialite SpatiaLite data provider (spatialite) 151 * 152 * Access data in a SpatiaLite database. The url defines the connection parameters, table, 153 * geometry column, and other attributes. The url can be constructed using the 154 * QgsDataSourceUri class. 155 * 156 * \subsection postgres PostgreSQL data provider (postgres) 157 * 158 * Connects to a PostgreSQL database. The url defines the connection parameters, table, 159 * geometry column, and other attributes. The url can be constructed using the 160 * QgsDataSourceUri class. 161 * 162 * \subsection mssql Microsoft SQL server data provider (mssql) 163 * 164 * Connects to a Microsoft SQL server database. The url defines the connection parameters, table, 165 * geometry column, and other attributes. The url can be constructed using the 166 * QgsDataSourceUri class. 167 * 168 * \subsection wfs WFS (web feature service) data provider (wfs) 169 * 170 * Used to access data provided by a web feature service. 171 * 172 * The url can be a HTTP url to a WFS server (legacy, e.g. http://foobar/wfs?TYPENAME=xxx&SRSNAME=yyy[&FILTER=zzz]), or, 173 * starting with QGIS 2.16, a URI constructed using the QgsDataSourceUri class with the following parameters : 174 * 175 * - url=string (mandatory): HTTP url to a WFS server endpoint. e.g http://foobar/wfs 176 * - typename=string (mandatory): WFS typename 177 * - srsname=string (recommended): SRS like 'EPSG:XXXX' 178 * - username=string 179 * - password=string 180 * - authcfg=string 181 * - version=auto/1.0.0/1.1.0/2.0.0 182 * - sql=string: full SELECT SQL statement with optional WHERE, ORDER BY and possibly with JOIN if supported on server 183 * - filter=string: QGIS expression or OGC/FES filter 184 * - restrictToRequestBBOX=1: to download only features in the view extent (or more generally 185 * in the bounding box of the feature iterator) 186 * - pageSize=number: number of features to retrieve in a single request (WFS 2) 187 * - maxNumFeatures=number: maximum number of features to retrieve (possibly across several multiple paging requests) 188 * - IgnoreAxisOrientation=1: to ignore EPSG axis order for WFS 1.1 or 2.0 189 * - InvertAxisOrientation=1: to invert axis order 190 * - hideDownloadProgressDialog=1: to hide the download progress dialog 191 * 192 * The ‘FILTER’ query string parameter can be used to filter 193 * the WFS feature type. The ‘FILTER’ key value can either be a QGIS expression 194 * or an OGC XML filter. If the value is set to a QGIS expression the driver will 195 * turn it into OGC XML filter before passing it to the WFS server. Beware the 196 * QGIS expression filter only supports” =, !=, <, >, <=, >=, AND, OR, NOT, LIKE, IS NULL” 197 * attribute operators, “BBOX, Disjoint, Intersects, Touches, Crosses, Contains, Overlaps, Within” 198 * spatial binary operators and the QGIS local “geomFromWKT, geomFromGML” 199 * geometry constructor functions. 200 * 201 * \subsection oapif OGC API - Features data provider (oapif) 202 * 203 * Used to access data provided by a OGC API - Features server. 204 * 205 * The URI should be constructed using the QgsDataSourceUri class with the following parameters: 206 * 207 * - url=string (mandatory): HTTP url to a OGC API - Features landing page. 208 * - typename=string (mandatory): Collection id 209 * - username=string 210 * - password=string 211 * - authcfg=string 212 * - filter=string: QGIS expression (only datetime filtering is forwarded to the server) 213 * - restrictToRequestBBOX=1: to download only features in the view extent (or more generally 214 * in the bounding box of the feature iterator) 215 * - pageSize=number: number of features to retrieve in a single request 216 * - maxNumFeatures=number: maximum number of features to retrieve (possibly across several multiple paging requests) 217 * - hideDownloadProgressDialog=1: to hide the download progress dialog. 218 * 219 * Also note: 220 * 221 * - You can use various functions available in the QGIS Expression list, 222 * however the function must exist server side and have the same name and arguments to work. 223 * - Use the special $geometry parameter to provide the layer geometry column as input 224 * into the spatial binary operators e.g intersects($geometry, geomFromWKT('POINT (5 6)')) 225 * 226 * \subsection delimitedtext Delimited text file data provider (delimitedtext) 227 * 228 * Accesses data in a delimited text file, for example CSV files generated by 229 * spreadsheets. The contents of the file are split into columns based on specified 230 * delimiter characters. Each record may be represented spatially either by an 231 * X and Y coordinate column, or by a WKT (well known text) formatted columns. 232 * 233 * The url defines the filename, the formatting options (how the 234 * text in the file is divided into data fields, and which fields contain the 235 * X,Y coordinates or WKT text definition. The options are specified as url query 236 * items. 237 * 238 * At its simplest the url can just be the filename, in which case it will be loaded 239 * as a CSV formatted file. 240 * 241 * The url may include the following items: 242 * 243 * - encoding=UTF-8 244 * 245 * Defines the character encoding in the file. The default is UTF-8. To use 246 * the default encoding for the operating system use "System". 247 * 248 * - type=(csv|regexp|whitespace|plain) 249 * 250 * Defines the algorithm used to split records into columns. Records are 251 * defined by new lines, except for csv format files for which quoted fields 252 * may span multiple records. The default type is csv. 253 * 254 * - "csv" splits the file based on three sets of characters: 255 * delimiter characters, quote characters, 256 * and escape characters. Delimiter characters mark the end 257 * of a field. Quote characters enclose a field which can contain 258 * delimiter characters, and newlines. Escape characters cause the 259 * following character to be treated literally (including delimiter, 260 * quote, and newline characters). Escape and quote characters must 261 * be different from delimiter characters. Escape characters that are 262 * also quote characters are treated specially - they can only 263 * escape themselves within quotes. Elsewhere they are treated as 264 * quote characters. The defaults for delimiter, quote, and escape 265 * are ',', '"', '"'. 266 * - "regexp" splits each record using a regular expression (see QRegExp 267 * documentation for details). 268 * - "whitespace" splits each record based on whitespace (on or more whitespace 269 * characters. Leading whitespace in the record is ignored. 270 * - "plain" is provided for backwards compatibility. It is equivalent to 271 * CSV except that the default quote characters are single and double quotes, 272 * and there is no escape characters. 273 * - delimiter=characters 274 * 275 * Defines the delimiter characters used for csv and plain type files, or the 276 * regular expression for regexp type files. It is a literal string of characters 277 * except that "\t" may be used to represent a tab character. 278 * 279 * - quote=characters 280 * 281 * Defines the characters that are used as quote characters for csv and plain type 282 * files. 283 * 284 * - escape=characters 285 * 286 * Defines the characters used to escape delimiter, quote, and newline characters. 287 * 288 * - skipLines=n 289 * 290 * Defines the number of lines to ignore at the beginning of the file (default 0) 291 * 292 * - useHeader=(yes|no) 293 * 294 * Defines whether the first record in the file (after skipped lines) contains 295 * column names (default yes) 296 * 297 * - trimFields=(yes|no) 298 * 299 * If yes then leading and trailing whitespace will be removed from fields 300 * 301 * - skipEmptyFields=(yes|no) 302 * 303 * If yes then empty fields will be discarded (equivalent to concatenating consecutive 304 * delimiters) 305 * 306 * - maxFields=# 307 * 308 * Specifies the maximum number of fields to load for each record. Additional 309 * fields will be discarded. Default is 0 - load all fields. 310 * 311 * - decimalPoint=c 312 * 313 * Defines a character that is used as a decimal point in the numeric columns 314 * The default is '.'. 315 * 316 * - xField=column yField=column 317 * 318 * Defines the name of the columns holding the x and y coordinates for XY point geometries. 319 * If the useHeader is no (ie there are no column names), then this is the column 320 * number (with the first column as 1). 321 * 322 * - xyDms=(yes|no) 323 * 324 * If yes then the X and Y coordinates are interpreted as 325 * degrees/minutes/seconds format (fairly permissively), 326 * or degree/minutes format. 327 * 328 * - wktField=column 329 * 330 * Defines the name of the columns holding the WKT geometry definition for WKT geometries. 331 * If the useHeader is no (ie there are no column names), then this is the column 332 * number (with the first column as 1). 333 * 334 * - geomType=(point|line|polygon|none) 335 * 336 * Defines the geometry type for WKT type geometries. QGIS will only display one 337 * type of geometry for the layer - any others will be ignored when the file is 338 * loaded. By default the provider uses the type of the first geometry in the file. 339 * Use geomType to override this type. 340 * 341 * geomType can also be set to none, in which case the layer is loaded without 342 * geometries. 343 * 344 * - subset=expression 345 * 346 * Defines an expression that will identify a subset of records to display 347 * 348 * - crs=crsstring 349 * 350 * Defines the coordinate reference system used for the layer. This can be 351 * any string accepted by QgsCoordinateReferenceSystem::createFromString() 352 * 353 * - subsetIndex=(yes|no) 354 * 355 * Determines whether the provider generates an index to improve the efficiency 356 * of subsets. The default is yes 357 * 358 * - spatialIndex=(yes|no) 359 * 360 * Determines whether the provider generates a spatial index. The default is no. 361 * 362 * - watchFile=(yes|no) 363 * 364 * Defines whether the file will be monitored for changes. The default is 365 * to monitor for changes. 366 * 367 * - quiet 368 * 369 * Errors encountered loading the file will not be reported in a user dialog if 370 * quiet is included (They will still be shown in the output log). 371 * 372 * \subsection gpx GPX data provider (gpx) 373 * 374 * Provider reads tracks, routes, and waypoints from a GPX file. The url 375 * defines the name of the file, and the type of data to retrieve from it 376 * ("track", "route", or "waypoint"). 377 * 378 * An example url is "/home/user/data/holiday.gpx?type=route" 379 * 380 * \subsection grass Grass data provider (grass) 381 * 382 * Provider to display vector data in a GRASS GIS layer. 383 * 384 * \see QgsVectorLayerUtils() 385 */ 386 class CORE_EXPORT QgsVectorLayer : public QgsMapLayer, public QgsExpressionContextGenerator, public QgsExpressionContextScopeGenerator, public QgsFeatureSink, public QgsFeatureSource 387 { 388 Q_OBJECT 389 390 Q_PROPERTY( QString subsetString READ subsetString WRITE setSubsetString NOTIFY subsetStringChanged ) 391 Q_PROPERTY( QString displayExpression READ displayExpression WRITE setDisplayExpression NOTIFY displayExpressionChanged ) 392 Q_PROPERTY( QString mapTipTemplate READ mapTipTemplate WRITE setMapTipTemplate NOTIFY mapTipTemplateChanged ) 393 Q_PROPERTY( QgsEditFormConfig editFormConfig READ editFormConfig WRITE setEditFormConfig NOTIFY editFormConfigChanged ) 394 Q_PROPERTY( bool readOnly READ isReadOnly WRITE setReadOnly NOTIFY readOnlyChanged ) 395 Q_PROPERTY( double opacity READ opacity WRITE setOpacity NOTIFY opacityChanged ) 396 397 public: 398 399 //! Result of an edit operation 400 enum EditResult 401 { 402 Success = 0, //!< Edit operation was successful 403 EmptyGeometry = 1, //!< Edit operation resulted in an empty geometry 404 EditFailed = 2, //!< Edit operation failed 405 FetchFeatureFailed = 3, //!< Unable to fetch requested feature 406 InvalidLayer = 4, //!< Edit failed due to invalid layer 407 }; 408 Q_ENUM( EditResult ) 409 410 //! Selection behavior 411 enum SelectBehavior 412 { 413 SetSelection, //!< Set selection, removing any existing selection 414 AddToSelection, //!< Add selection to current selection 415 IntersectSelection, //!< Modify current selection to include only select features which match 416 RemoveFromSelection, //!< Remove from current selection 417 }; 418 Q_ENUM( SelectBehavior ) 419 420 /** 421 * Setting options for loading vector layers. 422 * \since QGIS 3.0 423 */ 424 struct LayerOptions 425 { 426 427 /** 428 * Constructor for LayerOptions. 429 */ 430 explicit LayerOptions( bool loadDefaultStyle = true, 431 bool readExtentFromXml = false ) loadDefaultStyleLayerOptions432 : loadDefaultStyle( loadDefaultStyle ) 433 , readExtentFromXml( readExtentFromXml ) 434 {} 435 436 /** 437 * Constructor for LayerOptions. 438 * \since QGIS 3.8 439 */ 440 explicit LayerOptions( const QgsCoordinateTransformContext &transformContext, 441 bool loadDefaultStyle = true, 442 bool readExtentFromXml = false 443 ) loadDefaultStyleLayerOptions444 : loadDefaultStyle( loadDefaultStyle ) 445 , readExtentFromXml( readExtentFromXml ) 446 , transformContext( transformContext ) 447 {} 448 449 //! Set to TRUE if the default layer style should be loaded 450 bool loadDefaultStyle = true; 451 452 /** 453 * If TRUE, the layer extent will be read from XML (i.e. stored in the 454 * project file). If FALSE, the extent will be determined by the provider on layer load. 455 */ 456 bool readExtentFromXml = false; 457 458 /** 459 * Coordinate transform context 460 * \since QGIS 3.8 461 */ 462 QgsCoordinateTransformContext transformContext = QgsCoordinateTransformContext(); 463 464 /** 465 * Fallback geometry type. 466 * 467 * This may be set for layers where the geometry type is known in advance, and where 468 * the layer path may not be initially resolvable. (E.g. layers with a URI pointing 469 * to a non-existent file). It is only ever used if the layer cannot be resolved, 470 * otherwise the actual layer geometry type will be detected and used for the layer. 471 * 472 * \see fallbackCrs 473 * \since QGIS 3.8 474 */ 475 QgsWkbTypes::Type fallbackWkbType = QgsWkbTypes::Unknown; 476 477 /** 478 * Fallback layer coordinate reference system. 479 * 480 * This may be set for layers where the coordinate reference system is known in advance, and where 481 * the layer path may not be initially resolvable. (E.g. layers with a URI pointing 482 * to a non-existent file). It is only ever used if the layer cannot be resolved, 483 * otherwise the actual layer CRS will be detected and used for the layer. 484 * 485 * \see fallbackWkbType 486 * \since QGIS 3.8 487 */ 488 QgsCoordinateReferenceSystem fallbackCrs; 489 490 /** 491 * Controls whether the layer is allowed to have an invalid/unknown CRS. 492 * 493 * If TRUE, then no validation will be performed on the layer's CRS and the layer 494 * layer's crs() may be invalid() (i.e. the layer will have no georeferencing available 495 * and will be treated as having purely numerical coordinates). 496 * 497 * If FALSE (the default), the layer's CRS will be validated using QgsCoordinateReferenceSystem::validate(), 498 * which may cause a blocking, user-facing dialog asking users to manually select the correct CRS for the 499 * layer. 500 * 501 * \since QGIS 3.10 502 */ 503 bool skipCrsValidation = false; 504 505 }; 506 507 /** 508 * Context for cascade delete features 509 * \since QGIS 3.14 510 */ 511 struct CORE_EXPORT DeleteContext 512 { 513 514 /** 515 * Constructor for DeleteContext. 516 */ cascadeDeleteContext517 explicit DeleteContext( bool cascade = false, QgsProject *project = nullptr ): cascade( cascade ), project( project ) {} 518 519 /** 520 * Returns a list of all layers affected by the delete operation. 521 * 522 * If \a includeAuxiliaryLayers is FALSE then auxiliary layers will not be included in the 523 * returned list. 524 */ 525 QList<QgsVectorLayer *> handledLayers( bool includeAuxiliaryLayers = true ) const; 526 527 /** 528 * Returns a list of feature IDs from the specified \a layer affected by the delete operation. 529 */ 530 QgsFeatureIds handledFeatures( QgsVectorLayer *layer ) const; 531 532 QMap<QgsVectorLayer *, QgsFeatureIds> mHandledFeatures SIP_SKIP; 533 bool cascade; 534 QgsProject *project; 535 }; 536 537 /** 538 * Constructor - creates a vector layer 539 * 540 * The QgsVectorLayer is constructed by instantiating a data provider. The provider 541 * interprets the supplied path (url) of the data source to connect to and access the 542 * data. 543 * 544 * \param path The path or url of the parameter. Typically this encodes 545 * parameters used by the data provider as url query items. 546 * \param baseName The name used to represent the layer in the legend 547 * \param providerLib The name of the data provider, e.g., "memory", "postgres" 548 * \param options layer load options 549 */ 550 explicit QgsVectorLayer( const QString &path = QString(), const QString &baseName = QString(), 551 const QString &providerLib = "ogr", const QgsVectorLayer::LayerOptions &options = QgsVectorLayer::LayerOptions() ); 552 553 ~QgsVectorLayer() override; 554 555 //! QgsVectorLayer cannot be copied. 556 QgsVectorLayer( const QgsVectorLayer &rhs ) = delete; 557 //! QgsVectorLayer cannot be copied. 558 QgsVectorLayer &operator=( QgsVectorLayer const &rhs ) = delete; 559 560 #ifdef SIP_RUN 561 SIP_PYOBJECT __repr__(); 562 % MethodCode 563 QString str = QStringLiteral( "<QgsVectorLayer: '%1' (%2)>" ).arg( sipCpp->name(), sipCpp->dataProvider() ? sipCpp->dataProvider()->name() : QStringLiteral( "Invalid" ) ); 564 sipRes = PyUnicode_FromString( str.toUtf8().constData() ); 565 % End 566 #endif 567 568 /** 569 * Returns a new instance equivalent to this one. A new provider is 570 * created for the same data source and renderers for features and diagrams 571 * are cloned too. Moreover, each attributes (transparency, extent, selected 572 * features and so on) are identicals. 573 * \returns a new layer instance 574 * \since QGIS 3.0 575 */ 576 QgsVectorLayer *clone() const override SIP_FACTORY; 577 578 /** 579 * Returns the permanent storage type for this layer as a friendly name. 580 * This is obtained from the data provider and does not follow any standard. 581 */ 582 QString storageType() const; 583 584 /** 585 * Capabilities for this layer, comma separated and translated. 586 */ 587 QString capabilitiesString() const; 588 589 /** 590 * Returns a description for this layer as defined in the data provider. 591 */ 592 QString dataComment() const; 593 594 /** 595 * This is a shorthand for accessing the displayExpression if it is a simple field. 596 * If the displayExpression is more complex than a simple field, a null string will 597 * be returned. 598 * 599 * \see displayExpression 600 */ 601 QString displayField() const; 602 603 /** 604 * Set the preview expression, used to create a human readable preview string. 605 * Used e.g. in the attribute table feature list. Uses QgsExpression. 606 * 607 * \param displayExpression The expression which will be used to preview features 608 * for this layer 609 */ 610 void setDisplayExpression( const QString &displayExpression ); 611 612 /** 613 * Returns the preview expression, used to create a human readable preview string. 614 * Uses QgsExpression 615 * 616 * \returns The expression which will be used to preview features for this layer 617 */ 618 QString displayExpression() const; 619 620 QgsVectorDataProvider *dataProvider() FINAL; 621 const QgsVectorDataProvider *dataProvider() const FINAL SIP_SKIP; 622 623 /** 624 * Returns temporal properties associated with the vector layer. 625 */ 626 QgsMapLayerTemporalProperties *temporalProperties() override; 627 628 /** 629 * Sets the text \a encoding of the data provider. 630 * 631 * An empty \a encoding string indicates that the provider should automatically 632 * select the most appropriate encoding. 633 * 634 * \warning Support for setting the provider encoding depends on the underlying data 635 * provider. Check dataProvider().capabilities() for the QgsVectorDataProvider::SelectEncoding 636 * capability in order to determine if the provider supports this ability. 637 */ 638 void setProviderEncoding( const QString &encoding ); 639 640 //! Setup the coordinate system transformation for the layer 641 void setCoordinateSystem(); 642 643 /** 644 * Joins another vector layer to this layer 645 * \param joinInfo join object containing join layer id, target and source field 646 * \note since 2.6 returns bool indicating whether the join can be added 647 */ 648 bool addJoin( const QgsVectorLayerJoinInfo &joinInfo ); 649 650 /** 651 * Removes a vector layer join 652 * \returns TRUE if join was found and successfully removed 653 */ 654 bool removeJoin( const QString &joinLayerId ); 655 656 /** 657 * Returns the join buffer object. 658 * \since QGIS 2.14.7 659 */ joinBuffer()660 QgsVectorLayerJoinBuffer *joinBuffer() { return mJoinBuffer; } 661 662 /** 663 * Returns a const pointer on join buffer object. 664 * \since QGIS 3.10 665 */ joinBuffer()666 const QgsVectorLayerJoinBuffer *joinBuffer() const { return mJoinBuffer; } SIP_SKIP; 667 668 const QList<QgsVectorLayerJoinInfo> vectorJoins() const; 669 670 /** 671 * Sets the list of dependencies. 672 * \see dependencies() 673 * 674 * \param layers set of QgsMapLayerDependency. Only user-defined dependencies will be added 675 * \returns FALSE if a dependency cycle has been detected 676 * \since QGIS 3.0 677 */ 678 bool setDependencies( const QSet<QgsMapLayerDependency> &layers ) FINAL; 679 680 /** 681 * Gets the list of dependencies. This includes data dependencies set by the user (\see setDataDependencies) 682 * as well as dependencies given by the provider 683 * 684 * \returns a set of QgsMapLayerDependency 685 * \since QGIS 3.0 686 */ 687 QSet<QgsMapLayerDependency> dependencies() const FINAL; 688 689 /** 690 * Add a new field which is calculated by the expression specified 691 * 692 * \param exp The expression which calculates the field 693 * \param fld The field to calculate 694 * 695 * \returns The index of the new field 696 * 697 * \since QGIS 2.9 698 */ 699 int addExpressionField( const QString &exp, const QgsField &fld ); 700 701 /** 702 * Removes an expression field 703 * 704 * \param index The index of the field 705 * 706 * \since QGIS 2.6 707 */ 708 void removeExpressionField( int index ); 709 710 /** 711 * Returns the expression used for a given expression field 712 * 713 * \param index An index of an epxression based (virtual) field 714 * 715 * \returns The expression for the field at index 716 * 717 * \since QGIS 2.9 718 */ 719 QString expressionField( int index ) const; 720 721 /** 722 * Changes the expression used to define an expression based (virtual) field 723 * 724 * \param index The index of the expression to change 725 * 726 * \param exp The new expression to set 727 * 728 * \since QGIS 2.9 729 */ 730 void updateExpressionField( int index, const QString &exp ); 731 732 /** 733 * Returns all layer actions defined on this layer. 734 * 735 * The pointer which is returned directly points to the actions object 736 * which is used by the layer, so any changes are immediately applied. 737 */ actions()738 QgsActionManager *actions() { return mActions; } 739 740 /** 741 * Returns all layer actions defined on this layer. 742 * 743 * The pointer which is returned is const. 744 */ actions()745 const QgsActionManager *actions() const SIP_SKIP { return mActions; } 746 747 /** 748 * Returns QGIS Server Properties of the vector layer 749 * \since QGIS 3.10 750 */ serverProperties()751 QgsVectorLayerServerProperties *serverProperties() const { return mServerProperties.get(); } 752 753 /** 754 * Returns the number of features that are selected in this layer. 755 * 756 * \see selectedFeatureIds() 757 */ 758 int selectedFeatureCount() const; 759 760 /** 761 * Selects features found within the search rectangle (in layer's coordinates) 762 * \param rect search rectangle 763 * \param behavior selection type, allows adding to current selection, removing 764 * from selection, etc. 765 * \see invertSelectionInRectangle(QgsRectangle & rect) 766 * \see selectByExpression() 767 * \see selectByIds() 768 */ 769 Q_INVOKABLE void selectByRect( QgsRectangle &rect, QgsVectorLayer::SelectBehavior behavior = QgsVectorLayer::SetSelection ); 770 771 /** 772 * Selects matching features using an expression. 773 * \param expression expression to evaluate to select features 774 * \param behavior selection type, allows adding to current selection, removing 775 * from selection, etc. 776 * \see selectByRect() 777 * \see selectByIds() 778 * \since QGIS 2.16 779 */ 780 Q_INVOKABLE void selectByExpression( const QString &expression, QgsVectorLayer::SelectBehavior behavior = QgsVectorLayer::SetSelection ); 781 782 /** 783 * Selects matching features using a list of feature IDs. Will emit the 784 * selectionChanged() signal with the clearAndSelect flag set. 785 * \param ids feature IDs to select 786 * \param behavior selection type, allows adding to current selection, removing 787 * from selection, etc. 788 * \see selectByRect() 789 * \see selectByExpression() 790 * \since QGIS 2.16 791 */ 792 Q_INVOKABLE void selectByIds( const QgsFeatureIds &ids, QgsVectorLayer::SelectBehavior behavior = QgsVectorLayer::SetSelection ); 793 794 /** 795 * Modifies the current selection on this layer 796 * 797 * \param selectIds Select these ids 798 * \param deselectIds Deselect these ids 799 * 800 * \see selectByIds 801 * \see deselect(const QgsFeatureIds&) 802 * \see deselect(const QgsFeatureId) 803 * \see selectByExpression() 804 */ 805 Q_INVOKABLE void modifySelection( const QgsFeatureIds &selectIds, const QgsFeatureIds &deselectIds ); 806 807 //! Selects not selected features and deselects selected ones 808 Q_INVOKABLE void invertSelection(); 809 810 //! Select all the features 811 Q_INVOKABLE void selectAll(); 812 813 /** 814 * Inverts selection of features found within the search rectangle (in layer's coordinates) 815 * 816 * \param rect The rectangle in which the selection of features will be inverted 817 * 818 * \see invertSelection() 819 */ 820 Q_INVOKABLE void invertSelectionInRectangle( QgsRectangle &rect ); 821 822 /** 823 * Returns a copy of the user-selected features. 824 * 825 * \warning Calling this method triggers a request for all attributes and geometry for the selected features. 826 * Consider using the much more efficient selectedFeatureIds() or selectedFeatureCount() if you do not 827 * require access to the feature attributes or geometry. 828 * 829 * \returns A list of QgsFeature 830 * 831 * \see selectedFeatureIds() 832 * \see getSelectedFeatures() which is more memory friendly when handling large selections 833 */ 834 Q_INVOKABLE QgsFeatureList selectedFeatures() const; 835 836 /** 837 * Returns an iterator of the selected features. 838 * 839 * \param request You may specify a request, e.g. to limit the set of requested attributes. 840 * Any filter on the request will be discarded. 841 * 842 * \returns Iterator over the selected features 843 * 844 * \warning Calling this method returns an iterator for all attributes and geometry for the selected features. 845 * Consider using the much more efficient selectedFeatureIds() or selectedFeatureCount() if you do not 846 * require access to the feature attributes or geometry. 847 * 848 * \see selectedFeatureIds() 849 * \see selectedFeatures() 850 */ 851 QgsFeatureIterator getSelectedFeatures( QgsFeatureRequest request = QgsFeatureRequest() ) const; 852 853 /** 854 * Returns a list of the selected features IDs in this layer. 855 * 856 * \see selectedFeatures() 857 * \see selectedFeatureCount() 858 * \see selectByIds() 859 */ 860 Q_INVOKABLE const QgsFeatureIds &selectedFeatureIds() const; 861 862 //! Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,0,0,0) is returned 863 Q_INVOKABLE QgsRectangle boundingBoxOfSelected() const; 864 865 /** 866 * Returns whether the layer contains labels which are enabled and should be drawn. 867 * \returns TRUE if layer contains enabled labels 868 * 869 * \see setLabelsEnabled() 870 * \since QGIS 2.9 871 */ 872 bool labelsEnabled() const; 873 874 /** 875 * Sets whether labels should be \a enabled for the layer. 876 * 877 * \note Labels will only be rendered if labelsEnabled() is TRUE and a labeling 878 * object is returned by labeling(). 879 * 880 * \see labelsEnabled() 881 * \see labeling() 882 */ 883 void setLabelsEnabled( bool enabled ); 884 885 /** 886 * Returns whether the layer contains diagrams which are enabled and should be drawn. 887 * \returns TRUE if layer contains enabled diagrams 888 * \since QGIS 2.9 889 */ 890 bool diagramsEnabled() const; 891 892 //! Sets diagram rendering object (takes ownership) 893 void setDiagramRenderer( QgsDiagramRenderer *r SIP_TRANSFER ); diagramRenderer()894 const QgsDiagramRenderer *diagramRenderer() const { return mDiagramRenderer; } 895 896 void setDiagramLayerSettings( const QgsDiagramLayerSettings &s ); diagramLayerSettings()897 const QgsDiagramLayerSettings *diagramLayerSettings() const { return mDiagramLayerSettings; } 898 899 //! Returns renderer. renderer()900 QgsFeatureRenderer *renderer() { return mRenderer; } 901 902 /** 903 * Returns const renderer. 904 * \note not available in Python bindings 905 */ renderer()906 const QgsFeatureRenderer *renderer() const SIP_SKIP { return mRenderer; } 907 908 /** 909 * Sets renderer which will be invoked to represent this layer. 910 * Ownership is transferred. 911 */ 912 void setRenderer( QgsFeatureRenderer *r SIP_TRANSFER ); 913 914 //! Returns point, line or polygon 915 Q_INVOKABLE QgsWkbTypes::GeometryType geometryType() const; 916 917 //! Returns the WKBType or WKBUnknown in case of error 918 Q_INVOKABLE QgsWkbTypes::Type wkbType() const FINAL; 919 920 QgsCoordinateReferenceSystem sourceCrs() const FINAL; 921 QString sourceName() const FINAL; 922 923 /** 924 * Reads vector layer specific state from project file Dom node. 925 * \note Called by QgsMapLayer::readXml(). 926 */ 927 bool readXml( const QDomNode &layer_node, QgsReadWriteContext &context ) FINAL; 928 929 /** 930 * Writes vector layer specific state to project file Dom node. 931 * \note Called by QgsMapLayer::writeXml(). 932 */ 933 bool writeXml( QDomNode &layer_node, QDomDocument &doc, const QgsReadWriteContext &context ) const FINAL; 934 935 QString encodedSource( const QString &source, const QgsReadWriteContext &context ) const FINAL; 936 QString decodedSource( const QString &source, const QString &provider, const QgsReadWriteContext &context ) const FINAL; 937 938 /** 939 * Resolves references to other layers (kept as layer IDs after reading XML) into layer objects. 940 * \since QGIS 3.0 941 */ 942 void resolveReferences( QgsProject *project ) FINAL; 943 944 /** 945 * Saves named and sld style of the layer to the style table in the db. 946 * \param name Style name 947 * \param description A description of the style 948 * \param useAsDefault Set to TRUE if style should be used as the default style for the layer 949 * \param uiFileContent 950 * \param msgError will be set to a descriptive error message if any occurs 951 */ 952 virtual void saveStyleToDatabase( const QString &name, const QString &description, 953 bool useAsDefault, const QString &uiFileContent, 954 QString &msgError SIP_OUT ); 955 956 /** 957 * Lists all the style in db split into related to the layer and not related to 958 * \param ids the list in which will be stored the style db ids 959 * \param names the list in which will be stored the style names 960 * \param descriptions the list in which will be stored the style descriptions 961 * \param msgError will be set to a descriptive error message if any occurs 962 * \returns the number of styles related to current layer (-1 on not implemented) 963 * \note Since QGIS 3.2 Styles related to the layer are ordered with the default style first then by update time for Postgres, MySQL and Spatialite. 964 */ 965 virtual int listStylesInDatabase( QStringList &ids SIP_OUT, QStringList &names SIP_OUT, 966 QStringList &descriptions SIP_OUT, QString &msgError SIP_OUT ); 967 968 /** 969 * Returns the named style corresponding to style id provided 970 */ 971 virtual QString getStyleFromDatabase( const QString &styleId, QString &msgError SIP_OUT ); 972 973 /** 974 * Deletes a style from the database 975 * \param styleId the provider's layer_styles table id of the style to delete 976 * \param msgError will be set to a descriptive error message if any occurs 977 * \returns TRUE in case of success 978 * \since QGIS 3.0 979 */ 980 virtual bool deleteStyleFromDatabase( const QString &styleId, QString &msgError SIP_OUT ); 981 982 /** 983 * Loads a named style from file/local db/datasource db 984 * \param theURI the URI of the style or the URI of the layer 985 * \param resultFlag will be set to TRUE if a named style is correctly loaded 986 * \param loadFromLocalDb if TRUE forces to load from local db instead of datasource one 987 * \param categories the style categories to be loaded. 988 */ 989 virtual QString loadNamedStyle( const QString &theURI, bool &resultFlag SIP_OUT, bool loadFromLocalDb, 990 QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories ); 991 992 /** 993 * Calls loadNamedStyle( theURI, resultFlag, FALSE ); 994 * Retained for backward compatibility 995 */ 996 QString loadNamedStyle( const QString &theURI, bool &resultFlag SIP_OUT, 997 QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories ) FINAL; 998 999 /** 1000 * Loads the auxiliary layer for this vector layer. If there's no 1001 * corresponding table in the database, then nothing happens and FALSE is 1002 * returned. The key is optional because if this layer has been read from 1003 * a XML document, then the key read in this document is used by default. 1004 * 1005 * \param storage The auxiliary storage where to look for the table 1006 * \param key The key to use for joining. 1007 * 1008 * \returns TRUE if the auxiliary layer is well loaded, FALSE otherwise 1009 * 1010 * \since QGIS 3.0 1011 */ 1012 bool loadAuxiliaryLayer( const QgsAuxiliaryStorage &storage, const QString &key = QString() ); 1013 1014 /** 1015 * Sets the current auxiliary layer. The auxiliary layer is automatically 1016 * put in editable mode and fields are updated. Moreover, a join is created 1017 * between the current layer and the auxiliary layer. Ownership is 1018 * transferred. 1019 * 1020 * 1021 * \since QGIS 3.0 1022 */ 1023 void setAuxiliaryLayer( QgsAuxiliaryLayer *layer SIP_TRANSFER = nullptr ); 1024 1025 /** 1026 * Returns the current auxiliary layer. 1027 * 1028 * \since QGIS 3.0 1029 */ 1030 QgsAuxiliaryLayer *auxiliaryLayer(); 1031 1032 /** 1033 * Returns the current const auxiliary layer. 1034 * 1035 * \since QGIS 3.0 1036 */ 1037 const QgsAuxiliaryLayer *auxiliaryLayer() const SIP_SKIP; 1038 1039 /** 1040 * Reads the symbology for the current layer from the Dom node supplied. 1041 * \param layerNode node that will contain the symbology definition for this layer. 1042 * \param errorMessage reference to string that will be updated with any error messages 1043 * \param context reading context (used for transform from relative to absolute paths) 1044 * \param categories the style categories to be read 1045 * \returns TRUE in case of success. 1046 */ 1047 bool readSymbology( const QDomNode &layerNode, QString &errorMessage, 1048 QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories ) FINAL; 1049 1050 /** 1051 * Reads the style for the current layer from the Dom node supplied. 1052 * \param node node that will contain the style definition for this layer. 1053 * \param errorMessage reference to string that will be updated with any error messages 1054 * \param context reading context (used for transform from relative to absolute paths) 1055 * \param categories the style categories to be read 1056 * \returns TRUE in case of success. 1057 */ 1058 bool readStyle( const QDomNode &node, QString &errorMessage, 1059 QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories ) FINAL; 1060 1061 /** 1062 * Writes the symbology for the layer into the document provided. 1063 * \param node the node that will have the style element added to it. 1064 * \param doc the document that will have the QDomNode added. 1065 * \param errorMessage reference to string that will be updated with any error messages 1066 * \param context writing context (used for transform from absolute to relative paths) 1067 * \param categories the style categories to be written 1068 * \returns TRUE in case of success. 1069 */ 1070 bool writeSymbology( QDomNode &node, QDomDocument &doc, QString &errorMessage, 1071 const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories ) const FINAL; 1072 1073 /** 1074 * Writes just the style information for the layer into the document 1075 * \param node the node that will have the style element added to it. 1076 * \param doc the document that will have the QDomNode added. 1077 * \param errorMessage reference to string that will be updated with any error messages 1078 * \param context writing context (used for transform from absolute to relative paths) 1079 * \param categories the style categories to be written 1080 * \returns TRUE in case of success. 1081 */ 1082 bool writeStyle( QDomNode &node, QDomDocument &doc, QString &errorMessage, 1083 const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories = QgsMapLayer::AllStyleCategories ) const FINAL; 1084 1085 /** 1086 * Writes the symbology of the layer into the document provided in SLD 1.1 format 1087 * \param node the node that will have the style element added to it. 1088 * \param doc the document that will have the QDomNode added. 1089 * \param errorMessage reference to string that will be updated with any error messages 1090 * \param props a open ended set of properties that can drive/inform the SLD encoding 1091 * \returns TRUE in case of success 1092 */ 1093 bool writeSld( QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsStringMap &props = QgsStringMap() ) const; 1094 1095 bool readSld( const QDomNode &node, QString &errorMessage ) FINAL; 1096 1097 /** 1098 * Number of features rendered with specified legend key. Features must be first 1099 * calculated by countSymbolFeatures() 1100 * \returns number of features rendered by symbol or -1 if failed or counts are not available 1101 */ 1102 long featureCount( const QString &legendKey ) const; 1103 1104 /** 1105 * Ids of features rendered with specified legend key. Features must be first 1106 * calculated by countSymbolFeatures() 1107 * \returns Ids of features rendered by symbol or -1 if failed or Ids are not available 1108 * \since QGIS 3.10 1109 */ 1110 QgsFeatureIds symbolFeatureIds( const QString &legendKey ) const; 1111 1112 /** 1113 * Determines if this vector layer has features. 1114 * 1115 * \warning when a layer is editable and some features 1116 * have been deleted, this will return 1117 * QgsFeatureSource::FeatureAvailability::FeaturesMayBeAvailable 1118 * to avoid a potentially expensive call to the dataprovider. 1119 * 1120 * \since QGIS 3.4 1121 */ 1122 FeatureAvailability hasFeatures() const FINAL; 1123 1124 /** 1125 * Update the data source of the layer. The layer's renderer and legend will be preserved only 1126 * if the geometry type of the new data source matches the current geometry type of the layer. 1127 * \param dataSource new layer data source 1128 * \param baseName base name of the layer 1129 * \param provider provider string 1130 * \param loadDefaultStyleFlag set to TRUE to reset the layer's style to the default for the 1131 * data source 1132 * \since QGIS 2.10 1133 * \deprecated Use version with ProviderOptions argument instead 1134 */ 1135 Q_DECL_DEPRECATED void setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, bool loadDefaultStyleFlag = false ) SIP_DEPRECATED; 1136 1137 /** 1138 * Updates the data source of the layer. The layer's renderer and legend will be preserved only 1139 * if the geometry type of the new data source matches the current geometry type of the layer. 1140 * \param dataSource new layer data source 1141 * \param baseName base name of the layer 1142 * \param provider provider string 1143 * \param options provider options 1144 * \param loadDefaultStyleFlag set to TRUE to reset the layer's style to the default for the 1145 * data source 1146 * \see dataSourceChanged() 1147 * \since QGIS 3.2 1148 */ 1149 void setDataSource( const QString &dataSource, const QString &baseName, const QString &provider, const QgsDataProvider::ProviderOptions &options, bool loadDefaultStyleFlag = false ) override; 1150 1151 QString loadDefaultStyle( bool &resultFlag SIP_OUT ) FINAL; 1152 1153 /** 1154 * Count features for symbols. 1155 * The method will return the feature counter task. You will need to 1156 * connect to the symbolFeatureCountMapChanged() signal to be 1157 * notified when the freshly updated feature counts are ready. 1158 * 1159 * \param storeSymbolFids If TRUE will gather the feature ids (fids) per symbol, otherwise only the count. Default FALSE. 1160 * \note If the count features for symbols has been already done a 1161 * NULLPTR is returned. If you need to wait for the results, 1162 * you can call waitForFinished() on the feature counter. 1163 * 1164 * \since This is asynchronous since QGIS 3.0 1165 */ 1166 QgsVectorLayerFeatureCounter *countSymbolFeatures( bool storeSymbolFids = false ); 1167 1168 /** 1169 * Sets the string (typically sql) used to define a subset of the layer 1170 * \param subset The subset string. This may be the where clause of a sql statement 1171 * or other definition string specific to the underlying dataprovider 1172 * and data store. 1173 * \returns TRUE, when setting the subset string was successful, FALSE otherwise 1174 */ 1175 virtual bool setSubsetString( const QString &subset ); 1176 1177 /** 1178 * Returns the string (typically sql) used to define a subset of the layer. 1179 * \returns The subset string or null QString if not implemented by the provider 1180 */ 1181 virtual QString subsetString() const; 1182 1183 /** 1184 * Queries the layer for features specified in request. 1185 * \param request feature request describing parameters of features to return 1186 * \returns iterator for matching features from provider 1187 */ 1188 QgsFeatureIterator getFeatures( const QgsFeatureRequest &request = QgsFeatureRequest() ) const FINAL; 1189 1190 /** 1191 * Queries the layer for features matching a given expression. 1192 */ getFeatures(const QString & expression)1193 inline QgsFeatureIterator getFeatures( const QString &expression ) 1194 { 1195 return getFeatures( QgsFeatureRequest( expression ) ); 1196 } 1197 1198 /** 1199 * Queries the layer for the feature with the given id. 1200 * If there is no such feature, the returned feature will be invalid. 1201 */ getFeature(QgsFeatureId fid)1202 inline QgsFeature getFeature( QgsFeatureId fid ) const 1203 { 1204 QgsFeature feature; 1205 getFeatures( QgsFeatureRequest( fid ) ).nextFeature( feature ); 1206 return feature; 1207 } 1208 1209 /** 1210 * Queries the layer for the geometry at the given id. 1211 * If there is no such feature, the returned geometry will be invalid. 1212 */ 1213 QgsGeometry getGeometry( QgsFeatureId fid ) const; 1214 1215 /** 1216 * Queries the layer for the features with the given ids. 1217 */ getFeatures(const QgsFeatureIds & fids)1218 inline QgsFeatureIterator getFeatures( const QgsFeatureIds &fids ) 1219 { 1220 return getFeatures( QgsFeatureRequest( fids ) ); 1221 } 1222 1223 /** 1224 * Queries the layer for the features which intersect the specified rectangle. 1225 */ getFeatures(const QgsRectangle & rectangle)1226 inline QgsFeatureIterator getFeatures( const QgsRectangle &rectangle ) 1227 { 1228 return getFeatures( QgsFeatureRequest( rectangle ) ); 1229 } 1230 1231 bool addFeature( QgsFeature &feature, QgsFeatureSink::Flags flags = QgsFeatureSink::Flags() ) FINAL; 1232 1233 /** 1234 * Updates an existing \a feature in the layer, replacing the attributes and geometry for the feature 1235 * with matching QgsFeature::id() with the attributes and geometry from \a feature. 1236 * Changes are not immediately committed to the layer. 1237 * 1238 * If \a skipDefaultValue is set to TRUE, default field values will not 1239 * be updated. This can be used to override default field value expressions. 1240 * 1241 * Returns TRUE if the feature's attribute was successfully changed. 1242 * 1243 * \note Calls to updateFeature() are only valid for layers in which edits have been enabled 1244 * by a call to startEditing(). Changes made to features using this method are not committed 1245 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1246 * changes can be discarded by calling rollBack(). 1247 * 1248 * \warning This method needs to query the underlying data provider to fetch the feature 1249 * with matching QgsFeature::id() on every call. Depending on the underlying data source this 1250 * can be slow to execute. Consider using the more efficient changeAttributeValue() or 1251 * changeGeometry() methods instead. 1252 * 1253 * \see startEditing() 1254 * \see commitChanges() 1255 * \see changeGeometry() 1256 * \see changeAttributeValue() 1257 */ 1258 bool updateFeature( QgsFeature &feature, bool skipDefaultValues = false ); 1259 1260 /** 1261 * Inserts a new vertex before the given vertex number, 1262 * in the given ring, item (first number is index 0), and feature. 1263 * 1264 * Not meaningful for Point geometries 1265 * 1266 * \note Calls to insertVertex() are only valid for layers in which edits have been enabled 1267 * by a call to startEditing(). Changes made to features using this method are not committed 1268 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1269 * changes can be discarded by calling rollBack(). 1270 */ 1271 bool insertVertex( double x, double y, QgsFeatureId atFeatureId, int beforeVertex ); 1272 1273 /** 1274 * Inserts a new vertex before the given vertex number, 1275 * in the given ring, item (first number is index 0), and feature. 1276 * 1277 * Not meaningful for Point geometries 1278 * 1279 * \note Calls to insertVertex() are only valid for layers in which edits have been enabled 1280 * by a call to startEditing(). Changes made to features using this method are not committed 1281 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1282 * changes can be discarded by calling rollBack(). 1283 */ 1284 bool insertVertex( const QgsPoint &point, QgsFeatureId atFeatureId, int beforeVertex ); 1285 1286 /** 1287 * Moves the vertex at the given position number, 1288 * ring and item (first number is index 0), and feature 1289 * to the given coordinates. 1290 * 1291 * \note Calls to moveVertex() are only valid for layers in which edits have been enabled 1292 * by a call to startEditing(). Changes made to features using this method are not committed 1293 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1294 * changes can be discarded by calling rollBack(). 1295 */ 1296 bool moveVertex( double x, double y, QgsFeatureId atFeatureId, int atVertex ); 1297 1298 /** 1299 * Moves the vertex at the given position number, 1300 * ring and item (first number is index 0), and feature 1301 * to the given coordinates. 1302 * \note available in Python as moveVertexV2 1303 * \note Calls to moveVertex() are only valid for layers in which edits have been enabled 1304 * by a call to startEditing(). Changes made to features using this method are not committed 1305 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1306 * changes can be discarded by calling rollBack(). 1307 */ 1308 bool moveVertex( const QgsPoint &p, QgsFeatureId atFeatureId, int atVertex ) SIP_PYNAME( moveVertexV2 ); 1309 1310 /** 1311 * Deletes a vertex from a feature. 1312 * \param featureId ID of feature to remove vertex from 1313 * \param vertex index of vertex to delete 1314 * \note Calls to deleteVertex() are only valid for layers in which edits have been enabled 1315 * by a call to startEditing(). Changes made to features using this method are not committed 1316 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1317 * changes can be discarded by calling rollBack(). 1318 * \since QGIS 2.14 1319 */ 1320 EditResult deleteVertex( QgsFeatureId featureId, int vertex ); 1321 1322 /** 1323 * Deletes the selected features 1324 * \param deletedCount The number of successfully deleted features 1325 * \param context The chain of features who will be deleted for feedback and to avoid endless recursions 1326 * 1327 * \returns TRUE in case of success and FALSE otherwise 1328 */ 1329 Q_INVOKABLE bool deleteSelectedFeatures( int *deletedCount = nullptr, DeleteContext *context = nullptr ); 1330 1331 /** 1332 * Adds a ring to polygon/multipolygon features 1333 * \param ring ring to add 1334 * \param featureId if specified, feature ID for feature ring was added to will be stored in this parameter 1335 * \returns QgsGeometry::OperationResult 1336 * 1337 * - Success 1338 * - LayerNotEditable 1339 * - AddRingNotInExistingFeature 1340 * - InvalidInputGeometryType 1341 * - AddRingNotClosed 1342 * - AddRingNotValid 1343 * - AddRingCrossesExistingRings 1344 * 1345 * \note Calls to addRing() are only valid for layers in which edits have been enabled 1346 * by a call to startEditing(). Changes made to features using this method are not committed 1347 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1348 * changes can be discarded by calling rollBack(). 1349 * \deprecated since QGIS 3.12 - will be removed in QGIS 4.0. Use the variant which accepts QgsPoint objects instead of QgsPointXY. 1350 */ 1351 Q_DECL_DEPRECATED QgsGeometry::OperationResult addRing( const QVector<QgsPointXY> &ring, QgsFeatureId *featureId = nullptr ) SIP_DEPRECATED; 1352 1353 1354 /** 1355 * Adds a ring to polygon/multipolygon features 1356 * \param ring ring to add 1357 * \param featureId if specified, feature ID for feature ring was added to will be stored in this parameter 1358 * \returns QgsGeometry::OperationResult 1359 * 1360 * - Success 1361 * - LayerNotEditable 1362 * - AddRingNotInExistingFeature 1363 * - InvalidInputGeometryType 1364 * - AddRingNotClosed 1365 * - AddRingNotValid 1366 * - AddRingCrossesExistingRings 1367 * 1368 * \note Calls to addRing() are only valid for layers in which edits have been enabled 1369 * by a call to startEditing(). Changes made to features using this method are not committed 1370 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1371 * changes can be discarded by calling rollBack(). 1372 */ 1373 Q_INVOKABLE QgsGeometry::OperationResult addRing( const QgsPointSequence &ring, QgsFeatureId *featureId = nullptr ); 1374 1375 /** 1376 * Adds a ring to polygon/multipolygon features (takes ownership) 1377 * \param ring ring to add 1378 * \param featureId if specified, feature ID for feature ring was added to will be stored in this parameter 1379 * \returns QgsGeometry::OperationResult 1380 * 1381 * - Success 1382 * - LayerNotEditable 1383 * - AddRingNotInExistingFeature 1384 * - InvalidInputGeometryType 1385 * - AddRingNotClosed 1386 * - AddRingNotValid 1387 * - AddRingCrossesExistingRings 1388 * 1389 * \note available in Python as addCurvedRing 1390 * \note Calls to addRing() are only valid for layers in which edits have been enabled 1391 * by a call to startEditing(). Changes made to features using this method are not committed 1392 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1393 * changes can be discarded by calling rollBack(). 1394 */ 1395 Q_INVOKABLE QgsGeometry::OperationResult addRing( QgsCurve *ring SIP_TRANSFER, QgsFeatureId *featureId = nullptr ) SIP_PYNAME( addCurvedRing ); 1396 1397 /** 1398 * Adds a new part polygon to a multipart feature 1399 * \returns QgsGeometry::OperationResult 1400 * 1401 * - Success 1402 * - LayerNotEditable 1403 * - SelectionIsEmpty 1404 * - SelectionIsGreaterThanOne 1405 * - AddPartSelectedGeometryNotFound 1406 * - AddPartNotMultiGeometry 1407 * - InvalidBaseGeometry 1408 * - InvalidInputGeometryType 1409 * 1410 * \note Calls to addPart() are only valid for layers in which edits have been enabled 1411 * by a call to startEditing(). Changes made to features using this method are not committed 1412 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1413 * changes can be discarded by calling rollBack(). 1414 * \deprecated since QGIS 3.12 - will be removed in QGIS 4.0. Use the variant which accepts QgsPoint objects instead of QgsPointXY. 1415 */ 1416 Q_DECL_DEPRECATED QgsGeometry::OperationResult addPart( const QList<QgsPointXY> &ring ) SIP_DEPRECATED; 1417 1418 /** 1419 * Adds a new part polygon to a multipart feature 1420 * \returns QgsGeometry::OperationResult 1421 * 1422 * - Success 1423 * - LayerNotEditable 1424 * - SelectionIsEmpty 1425 * - SelectionIsGreaterThanOne 1426 * - AddPartSelectedGeometryNotFound 1427 * - AddPartNotMultiGeometry 1428 * - InvalidBaseGeometry 1429 * - InvalidInputGeometryType 1430 * 1431 * \note available in Python bindings as addPartV2 1432 * \note Calls to addPart() are only valid for layers in which edits have been enabled 1433 * by a call to startEditing(). Changes made to features using this method are not committed 1434 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1435 * changes can be discarded by calling rollBack(). 1436 * \deprecated since QGIS 3.12 - will be removed in QGIS 4.0. Use the variant which accepts QgsPoint objects instead of QgsPointXY. 1437 */ 1438 Q_DECL_DEPRECATED QgsGeometry::OperationResult addPart( const QVector<QgsPointXY> &ring ) SIP_PYNAME( addPartV2 ) SIP_DEPRECATED; 1439 1440 /** 1441 * Adds a new part polygon to a multipart feature 1442 * \returns QgsGeometry::OperationResult 1443 * 1444 * - Success 1445 * - LayerNotEditable 1446 * - SelectionIsEmpty 1447 * - SelectionIsGreaterThanOne 1448 * - AddPartSelectedGeometryNotFound 1449 * - AddPartNotMultiGeometry 1450 * - InvalidBaseGeometry 1451 * - InvalidInputGeometryType 1452 * 1453 * \note available in Python bindings as addPartV2 1454 * \note Calls to addPart() are only valid for layers in which edits have been enabled 1455 * by a call to startEditing(). Changes made to features using this method are not committed 1456 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1457 * changes can be discarded by calling rollBack(). 1458 */ 1459 Q_INVOKABLE QgsGeometry::OperationResult addPart( const QgsPointSequence &ring ) SIP_PYNAME( addPartV2 ); 1460 1461 /** 1462 * \note available in Python as addCurvedPart 1463 * \note Calls to addPart() are only valid for layers in which edits have been enabled 1464 * by a call to startEditing(). Changes made to features using this method are not committed 1465 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1466 * changes can be discarded by calling rollBack(). 1467 */ 1468 Q_INVOKABLE QgsGeometry::OperationResult addPart( QgsCurve *ring SIP_TRANSFER ) SIP_PYNAME( addCurvedPart ); 1469 1470 /** 1471 * Translates feature by dx, dy 1472 * \param featureId id of the feature to translate 1473 * \param dx translation of x-coordinate 1474 * \param dy translation of y-coordinate 1475 * \returns 0 in case of success 1476 * \note Calls to translateFeature() are only valid for layers in which edits have been enabled 1477 * by a call to startEditing(). Changes made to features using this method are not committed 1478 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1479 * changes can be discarded by calling rollBack(). 1480 */ 1481 Q_INVOKABLE int translateFeature( QgsFeatureId featureId, double dx, double dy ); 1482 1483 /** 1484 * Splits parts cut by the given line 1485 * \param splitLine line that splits the layer features 1486 * \param topologicalEditing TRUE if topological editing is enabled 1487 * \returns QgsGeometry::OperationResult 1488 * 1489 * - Success 1490 * - NothingHappened 1491 * - LayerNotEditable 1492 * - InvalidInputGeometryType 1493 * - InvalidBaseGeometry 1494 * - GeometryEngineError 1495 * - SplitCannotSplitPoint 1496 * 1497 * \note Calls to splitParts() are only valid for layers in which edits have been enabled 1498 * by a call to startEditing(). Changes made to features using this method are not committed 1499 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1500 * changes can be discarded by calling rollBack(). 1501 * \deprecated since QGIS 3.12 - will be removed in QGIS 4.0. Use the variant which accepts QgsPoint objects instead of QgsPointXY. 1502 */ 1503 Q_DECL_DEPRECATED QgsGeometry::OperationResult splitParts( const QVector<QgsPointXY> &splitLine, bool topologicalEditing = false ) SIP_DEPRECATED; 1504 1505 /** 1506 * Splits parts cut by the given line 1507 * \param splitLine line that splits the layer features 1508 * \param topologicalEditing TRUE if topological editing is enabled 1509 * \returns QgsGeometry::OperationResult 1510 * 1511 * - Success 1512 * - NothingHappened 1513 * - LayerNotEditable 1514 * - InvalidInputGeometryType 1515 * - InvalidBaseGeometry 1516 * - GeometryEngineError 1517 * - SplitCannotSplitPoint 1518 * 1519 * \note Calls to splitParts() are only valid for layers in which edits have been enabled 1520 * by a call to startEditing(). Changes made to features using this method are not committed 1521 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1522 * changes can be discarded by calling rollBack(). 1523 */ 1524 Q_INVOKABLE QgsGeometry::OperationResult splitParts( const QgsPointSequence &splitLine, bool topologicalEditing = false ); 1525 1526 /** 1527 * Splits features cut by the given line 1528 * \param splitLine line that splits the layer features 1529 * \param topologicalEditing TRUE if topological editing is enabled 1530 * \returns QgsGeometry::OperationResult 1531 * 1532 * - Success 1533 * - NothingHappened 1534 * - LayerNotEditable 1535 * - InvalidInputGeometryType 1536 * - InvalidBaseGeometry 1537 * - GeometryEngineError 1538 * - SplitCannotSplitPoint 1539 * 1540 * \note Calls to splitFeatures() are only valid for layers in which edits have been enabled 1541 * by a call to startEditing(). Changes made to features using this method are not committed 1542 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1543 * changes can be discarded by calling rollBack(). 1544 * \deprecated since QGIS 3.12 - will be removed in QGIS 4.0. Use the variant which accepts QgsPoint objects instead of QgsPointXY. 1545 */ 1546 Q_DECL_DEPRECATED QgsGeometry::OperationResult splitFeatures( const QVector<QgsPointXY> &splitLine, bool topologicalEditing = false ) SIP_DEPRECATED; 1547 1548 /** 1549 * Splits features cut by the given line 1550 * \param splitLine line that splits the layer features 1551 * \param topologicalEditing TRUE if topological editing is enabled 1552 * \returns QgsGeometry::OperationResult 1553 * 1554 * - Success 1555 * - NothingHappened 1556 * - LayerNotEditable 1557 * - InvalidInputGeometryType 1558 * - InvalidBaseGeometry 1559 * - GeometryEngineError 1560 * - SplitCannotSplitPoint 1561 * 1562 * \note Calls to splitFeatures() are only valid for layers in which edits have been enabled 1563 * by a call to startEditing(). Changes made to features using this method are not committed 1564 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1565 * changes can be discarded by calling rollBack(). 1566 */ 1567 Q_INVOKABLE QgsGeometry::OperationResult splitFeatures( const QgsPointSequence &splitLine, bool topologicalEditing = false ); 1568 1569 /** 1570 * Splits features cut by the given curve 1571 * \param curve curve that splits the layer features 1572 * \param[out] topologyTestPoints topological points to be tested against other layers 1573 * \param preserveCircular whether circular strings are preserved after splitting 1574 * \param topologicalEditing TRUE if topological editing is enabled 1575 * \returns QgsGeometry::OperationResult 1576 * 1577 * - Success 1578 * - NothingHappened 1579 * - LayerNotEditable 1580 * - InvalidInputGeometryType 1581 * - InvalidBaseGeometry 1582 * - GeometryEngineError 1583 * - SplitCannotSplitPoint 1584 * 1585 * \note Calls to splitFeatures() are only valid for layers in which edits have been enabled 1586 * by a call to startEditing(). Changes made to features using this method are not committed 1587 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1588 * changes can be discarded by calling rollBack(). 1589 * \since QGIS 3.16 1590 */ 1591 Q_INVOKABLE QgsGeometry::OperationResult splitFeatures( const QgsCurve *curve, QgsPointSequence &topologyTestPoints SIP_OUT, bool preserveCircular = false, bool topologicalEditing = false ); 1592 1593 /** 1594 * Adds topological points for every vertex of the geometry. 1595 * \param geom the geometry where each vertex is added to segments of other features 1596 * \returns -1 in case of layer error (invalid or non editable) 1597 * \returns 0 in case of success 1598 * \returns 1 in case of geometry error (non spatial or null geometry) 1599 * \returns 2 in case no vertices needed to be added 1600 * \note geom is not going to be modified by the function 1601 * \note Calls to addTopologicalPoints() are only valid for layers in which edits have been enabled 1602 * by a call to startEditing(). Changes made to features using this method are not committed 1603 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1604 * changes can be discarded by calling rollBack(). 1605 */ 1606 int addTopologicalPoints( const QgsGeometry &geom ); 1607 1608 /** 1609 * Adds a vertex to segments which intersect point \a p but don't 1610 * already have a vertex there. If a feature already has a vertex at position \a p, 1611 * no additional vertex is inserted. This method is useful for topological 1612 * editing. 1613 * \param p position of the vertex 1614 * \returns -1 in case of layer error (invalid or non editable) 1615 * \returns 0 in case of success 1616 * \returns 1 in case of geometry error (non spatial or null geometry) 1617 * \returns 2 in case no vertices needed to be added 1618 * \note Calls to addTopologicalPoints() are only valid for layers in which edits have been enabled 1619 * by a call to startEditing(). Changes made to features using this method are not committed 1620 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1621 * changes can be discarded by calling rollBack(). 1622 * \deprecated since QGIS 3.12 - will be removed in QGIS 4.0. Use the variant which accepts QgsPoint objects instead of QgsPointXY. 1623 */ 1624 Q_DECL_DEPRECATED int addTopologicalPoints( const QgsPointXY &p ) SIP_DEPRECATED; 1625 1626 /** 1627 * Adds a vertex to segments which intersect point \a p but don't 1628 * already have a vertex there. If a feature already has a vertex at position \a p, 1629 * no additional vertex is inserted. This method is useful for topological 1630 * editing. 1631 * \param p position of the vertex 1632 * \returns -1 in case of layer error (invalid or non editable) 1633 * \returns 0 in case of success 1634 * \returns 1 in case of geometry error (non spatial or null geometry) 1635 * \returns 2 in case no vertices needed to be added 1636 * \note Calls to addTopologicalPoints() are only valid for layers in which edits have been enabled 1637 * by a call to startEditing(). Changes made to features using this method are not committed 1638 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1639 * changes can be discarded by calling rollBack(). 1640 * \since 3.10 1641 */ 1642 int addTopologicalPoints( const QgsPoint &p ); 1643 1644 /** 1645 * Adds a vertex to segments which intersect any of the points \a p but don't 1646 * already have a vertex there. If a feature already has a vertex at position \a p, 1647 * no additional vertex is inserted. This method is useful for topological 1648 * editing. 1649 * \param ps point sequence of the vertices 1650 * \returns -1 in case of layer error (invalid or non editable) 1651 * \returns 0 in case of success 1652 * \returns 1 in case of geometry error (non spatial or null geometry) 1653 * \returns 2 in case no vertices needed to be added 1654 * \note Calls to addTopologicalPoints() are only valid for layers in which edits have been enabled 1655 * by a call to startEditing(). Changes made to features using this method are not committed 1656 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1657 * changes can be discarded by calling rollBack(). 1658 * \since 3.16 1659 */ 1660 int addTopologicalPoints( const QgsPointSequence &ps ); 1661 1662 /** 1663 * Access to const labeling configuration. May be NULLPTR if labeling is not used. 1664 * \note Labels will only be rendered if labelsEnabled() returns TRUE. 1665 * \see labelsEnabled() 1666 * \since QGIS 3.0 1667 */ labeling()1668 const QgsAbstractVectorLayerLabeling *labeling() const SIP_SKIP { return mLabeling; } 1669 1670 /** 1671 * Access to labeling configuration. May be NULLPTR if labeling is not used. 1672 * \note Labels will only be rendered if labelsEnabled() returns TRUE. 1673 * \see labelsEnabled() 1674 * \since QGIS 3.0 1675 */ labeling()1676 QgsAbstractVectorLayerLabeling *labeling() { return mLabeling; } 1677 1678 /** 1679 * Sets labeling configuration. Takes ownership of the object. 1680 * \since QGIS 3.0 1681 */ 1682 void setLabeling( QgsAbstractVectorLayerLabeling *labeling SIP_TRANSFER ); 1683 1684 //! Returns TRUE if the provider is in editing mode 1685 bool isEditable() const FINAL; 1686 1687 //! Returns TRUE if this is a geometry layer and FALSE in case of NoGeometry (table only) or UnknownGeometry 1688 bool isSpatial() const FINAL; 1689 1690 //! Returns TRUE if the provider has been modified since the last commit 1691 virtual bool isModified() const; 1692 1693 /** 1694 * Returns TRUE if the field comes from the auxiliary layer, 1695 * FALSE otherwise. 1696 * 1697 * \since QGIS 3.0 1698 */ 1699 bool isAuxiliaryField( int index, int &srcIndex ) const; 1700 1701 //! Synchronises with changes in the datasource 1702 void reload() FINAL; 1703 1704 /** 1705 * Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context 1706 * \since QGIS 2.4 1707 */ 1708 QgsMapLayerRenderer *createMapRenderer( QgsRenderContext &rendererContext ) FINAL SIP_FACTORY; 1709 1710 QgsRectangle extent() const FINAL; 1711 QgsRectangle sourceExtent() const FINAL; 1712 1713 /** 1714 * Returns the list of fields of this layer. 1715 * This also includes fields which have not yet been saved to the provider. 1716 * 1717 * \returns A list of fields 1718 */ 1719 QgsFields fields() const FINAL; 1720 1721 /** 1722 * Returns list of attribute indexes. i.e. a list from 0 ... fieldCount() 1723 */ attributeList()1724 inline QgsAttributeList attributeList() const { return mFields.allAttributesList(); } 1725 1726 /** 1727 * Returns the list of attributes which make up the layer's primary keys. 1728 */ 1729 QgsAttributeList primaryKeyAttributes() const; 1730 1731 /** 1732 * Returns feature count including changes which have not yet been committed 1733 * If you need only the count of committed features call this method on this layer's provider. 1734 * \returns the number of features on this layer or -1 if unknown. 1735 */ 1736 long featureCount() const FINAL; 1737 1738 /** 1739 * Makes layer read-only (editing disabled) or not 1740 * \returns FALSE if the layer is in editing yet 1741 */ 1742 bool setReadOnly( bool readonly = true ); 1743 1744 /** 1745 * Changes a feature's \a geometry within the layer's edit buffer 1746 * (but does not immediately commit the changes). The \a fid argument 1747 * specifies the ID of the feature to be changed. 1748 * 1749 * If \a skipDefaultValue is set to TRUE, default field values will not 1750 * be updated. This can be used to override default field value expressions. 1751 * 1752 * \returns TRUE if the feature's geometry was successfully changed. 1753 * 1754 * \note Calls to changeGeometry() are only valid for layers in which edits have been enabled 1755 * by a call to startEditing(). Changes made to features using this method are not committed 1756 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1757 * changes can be discarded by calling rollBack(). 1758 * 1759 * \see startEditing() 1760 * \see commitChanges() 1761 * \see changeAttributeValue() 1762 * \see updateFeature() 1763 */ 1764 bool changeGeometry( QgsFeatureId fid, QgsGeometry &geometry, bool skipDefaultValue = false ); 1765 1766 /** 1767 * Changes an attribute value for a feature (but does not immediately commit the changes). 1768 * The \a fid argument specifies the ID of the feature to be changed. 1769 * 1770 * The \a field argument must specify a valid field index for the layer (where an index of 0 1771 * corresponds to the first field). 1772 * 1773 * The new value to be assigned to the field is given by \a newValue. 1774 * 1775 * If a valid QVariant is specified for \a oldValue, it will be used as the field value in the 1776 * case of an undo operation corresponding to this attribute value change. If an invalid 1777 * QVariant is used (the default behavior), then the feature's current value will be automatically 1778 * retrieved and used. Note that this involves a feature request to the underlying data provider, 1779 * so it is more efficient to explicitly pass an \a oldValue if it is already available. 1780 * 1781 * If \a skipDefaultValues is set to TRUE, default field values will not 1782 * be updated. This can be used to override default field value expressions. 1783 * 1784 * \returns TRUE if the feature's attribute was successfully changed. 1785 * 1786 * \note Calls to changeAttributeValue() are only valid for layers in which edits have been enabled 1787 * by a call to startEditing(). Changes made to features using this method are not committed 1788 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1789 * changes can be discarded by calling rollBack(). 1790 * 1791 * \see startEditing() 1792 * \see commitChanges() 1793 * \see changeGeometry() 1794 * \see updateFeature() 1795 */ 1796 bool changeAttributeValue( QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue = QVariant(), bool skipDefaultValues = false ); 1797 1798 /** 1799 * Changes attributes' values for a feature (but does not immediately 1800 * commit the changes). 1801 * The \a fid argument specifies the ID of the feature to be changed. 1802 * 1803 * The new values to be assigned to the fields are given by \a newValues. 1804 * 1805 * If a valid QVariant is specified for a field in \a oldValues, it will be 1806 * used as the field value in the case of an undo operation corresponding 1807 * to this attribute value change. If an invalid QVariant is used (the 1808 * default behavior), then the feature's current value will be 1809 * automatically retrieved and used. Note that this involves a feature 1810 * request to the underlying data provider, so it is more efficient to 1811 * explicitly pass an oldValue if it is already available. 1812 * 1813 * If \a skipDefaultValues is set to TRUE, default field values will not 1814 * be updated. This can be used to override default field value 1815 * expressions. 1816 * 1817 * \returns TRUE if feature's attributes was successfully changed. 1818 * 1819 * \note Calls to changeAttributeValues() are only valid for layers in 1820 * which edits have been enabled by a call to startEditing(). Changes made 1821 * to features using this method are not committed to the underlying data 1822 * provider until a commitChanges() call is made. Any uncommitted changes 1823 * can be discarded by calling rollBack(). 1824 * 1825 * \see startEditing() 1826 * \see commitChanges() 1827 * \see changeGeometry() 1828 * \see updateFeature() 1829 * \see changeAttributeValue() 1830 * 1831 * \since QGIS 3.0 1832 */ 1833 bool changeAttributeValues( QgsFeatureId fid, const QgsAttributeMap &newValues, const QgsAttributeMap &oldValues = QgsAttributeMap(), bool skipDefaultValues = false ); 1834 1835 /** 1836 * Add an attribute field (but does not commit it) 1837 * returns TRUE if the field was added 1838 * 1839 * \note Calls to addAttribute() are only valid for layers in which edits have been enabled 1840 * by a call to startEditing(). Changes made to features using this method are not committed 1841 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1842 * changes can be discarded by calling rollBack(). 1843 */ 1844 bool addAttribute( const QgsField &field ); 1845 1846 /** 1847 * Sets an alias (a display name) for attributes to display in dialogs 1848 * 1849 * \since QGIS 3.0 1850 */ 1851 void setFieldAlias( int index, const QString &aliasString ); 1852 1853 /** 1854 * Removes an alias (a display name) for attributes to display in dialogs 1855 * 1856 * \since QGIS 3.0 1857 */ 1858 void removeFieldAlias( int index ); 1859 1860 /** 1861 * Renames an attribute field (but does not commit it). 1862 * \param index attribute index 1863 * \param newName new name of field 1864 * \note Calls to renameAttribute() are only valid for layers in which edits have been enabled 1865 * by a call to startEditing(). Changes made to features using this method are not committed 1866 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1867 * changes can be discarded by calling rollBack(). 1868 * \since QGIS 2.16 1869 */ 1870 bool renameAttribute( int index, const QString &newName ); 1871 1872 /** 1873 * Returns the alias of an attribute name or a null string if there is no alias. 1874 * 1875 * \see {attributeDisplayName( int attributeIndex )} which returns the field name 1876 * if no alias is defined. 1877 */ 1878 QString attributeAlias( int index ) const; 1879 1880 //! Convenience function that returns the attribute alias if defined or the field name else 1881 QString attributeDisplayName( int index ) const; 1882 1883 //! Returns a map of field name to attribute alias 1884 QgsStringMap attributeAliases() const; 1885 1886 /** 1887 * A set of attributes that are not advertised in WMS requests with QGIS server. 1888 * \deprecated since QGIS 3.16, use fields().configurationFlags() instead 1889 */ 1890 Q_DECL_DEPRECATED QSet<QString> excludeAttributesWms() const SIP_DEPRECATED; 1891 1892 /** 1893 * A set of attributes that are not advertised in WMS requests with QGIS server. 1894 * \deprecated since QGIS 3.16, use setFieldConfigurationFlag instead 1895 */ 1896 Q_DECL_DEPRECATED void setExcludeAttributesWms( const QSet<QString> &att ) SIP_DEPRECATED; 1897 1898 /** 1899 * A set of attributes that are not advertised in WFS requests with QGIS server. 1900 * \deprecated since QGIS 3.16, use fields().configurationFlags() instead 1901 */ 1902 Q_DECL_DEPRECATED QSet<QString> excludeAttributesWfs() const SIP_DEPRECATED; 1903 1904 /** 1905 * A set of attributes that are not advertised in WFS requests with QGIS server. 1906 * \deprecated since QGIS 3.16, use setFieldConfigurationFlag instead 1907 */ 1908 Q_DECL_DEPRECATED void setExcludeAttributesWfs( const QSet<QString> &att ) SIP_DEPRECATED; 1909 1910 /** 1911 * Deletes an attribute field (but does not commit it). 1912 * 1913 * \note Calls to deleteAttribute() are only valid for layers in which edits have been enabled 1914 * by a call to startEditing(). Changes made to features using this method are not committed 1915 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1916 * changes can be discarded by calling rollBack(). 1917 */ 1918 virtual bool deleteAttribute( int attr ); 1919 1920 /** 1921 * Deletes a list of attribute fields (but does not commit it) 1922 * 1923 * \param attrs the indices of the attributes to delete 1924 * \returns TRUE if at least one attribute has been deleted 1925 * 1926 */ 1927 bool deleteAttributes( const QList<int> &attrs ); 1928 1929 bool addFeatures( QgsFeatureList &features, QgsFeatureSink::Flags flags = QgsFeatureSink::Flags() ) FINAL; 1930 1931 /** 1932 * Deletes a feature from the layer (but does not commit it). 1933 * \param fid The feature id to delete 1934 * \param context The chain of features who will be deleted for feedback and to avoid endless recursions 1935 * 1936 * \note Calls to deleteFeature() are only valid for layers in which edits have been enabled 1937 * by a call to startEditing(). Changes made to features using this method are not committed 1938 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1939 * changes can be discarded by calling rollBack(). 1940 */ 1941 bool deleteFeature( QgsFeatureId fid, DeleteContext *context = nullptr ); 1942 1943 /** 1944 * Deletes a set of features from the layer (but does not commit it) 1945 * \param fids The feature ids to delete 1946 * \param context The chain of features who will be deleted for feedback and to avoid endless recursions 1947 * 1948 * \returns FALSE if the layer is not in edit mode or does not support deleting 1949 * in case of an active transaction depends on the provider implementation 1950 * 1951 * \note Calls to deleteFeatures() are only valid for layers in which edits have been enabled 1952 * by a call to startEditing(). Changes made to features using this method are not committed 1953 * to the underlying data provider until a commitChanges() call is made. Any uncommitted 1954 * changes can be discarded by calling rollBack(). 1955 */ 1956 bool deleteFeatures( const QgsFeatureIds &fids, DeleteContext *context = nullptr ); 1957 1958 /** 1959 * Attempts to commit to the underlying data provider any buffered changes made since the 1960 * last to call to startEditing(). 1961 * 1962 * Returns the result of the attempt. If a commit fails (i.e. FALSE is returned), the 1963 * in-memory changes are left untouched and are not discarded. This allows editing to 1964 * continue if the commit failed on e.g. a disallowed value in a Postgres 1965 * database - the user can re-edit and try again. 1966 * 1967 * The commits occur in distinct stages, 1968 * (add attributes, add features, change attribute values, change 1969 * geometries, delete features, delete attributes) 1970 * so if a stage fails, it can be difficult to roll back cleanly. 1971 * Therefore any error message returned by commitErrors() also includes which stage failed so 1972 * that the user has some chance of repairing the damage cleanly. 1973 * 1974 * By setting \a stopEditing to FALSE, the layer will stay in editing mode. 1975 * Otherwise the layer editing mode will be disabled if the commit is successful. 1976 * 1977 * \see startEditing() 1978 * \see commitErrors() 1979 * \see rollBack() 1980 */ 1981 Q_INVOKABLE bool commitChanges( bool stopEditing = true ); 1982 1983 /** 1984 * Returns a list containing any error messages generated when attempting 1985 * to commit changes to the layer. 1986 * \see commitChanges() 1987 */ 1988 QStringList commitErrors() const; 1989 1990 /** 1991 * Stops a current editing operation and discards any uncommitted edits. 1992 * 1993 * If \a deleteBuffer is TRUE the editing buffer will be completely deleted (the default 1994 * behavior). 1995 * 1996 * \see startEditing() 1997 * \see commitChanges() 1998 */ 1999 Q_INVOKABLE bool rollBack( bool deleteBuffer = true ); 2000 2001 /** 2002 * Returns the layer's relations, where the foreign key is on this layer. 2003 * 2004 * \param idx Only get relations, where idx forms part of the foreign key 2005 * \returns A list of relations 2006 */ 2007 QList<QgsRelation> referencingRelations( int idx ) const; 2008 2009 /** 2010 * Returns the layer's weak relations as specified in the layer's style. 2011 * \returns A list of weak relations 2012 * \note not available in Python bindings 2013 * \since QGIS 3.12 2014 */ 2015 QList<QgsWeakRelation> weakRelations( ) const SIP_SKIP; 2016 2017 2018 //! Buffer with uncommitted editing operations. Only valid after editing has been turned on. editBuffer()2019 Q_INVOKABLE QgsVectorLayerEditBuffer *editBuffer() { return mEditBuffer; } 2020 2021 /** 2022 * Buffer with uncommitted editing operations. Only valid after editing has been turned on. 2023 * \note not available in Python bindings 2024 */ editBuffer()2025 const QgsVectorLayerEditBuffer *editBuffer() const SIP_SKIP { return mEditBuffer; } 2026 2027 /** 2028 * Create edit command for undo/redo operations 2029 * \param text text which is to be displayed in undo window 2030 */ 2031 void beginEditCommand( const QString &text ); 2032 2033 //! Finish edit command and add it to undo/redo stack 2034 void endEditCommand(); 2035 2036 //! Destroy active command and reverts all changes in it 2037 void destroyEditCommand(); 2038 2039 //! Editing vertex markers 2040 enum VertexMarkerType 2041 { 2042 SemiTransparentCircle, 2043 Cross, 2044 NoMarker 2045 }; 2046 2047 /** 2048 * Draws a vertex symbol at (screen) coordinates x, y. (Useful to assist vertex editing.) 2049 * \deprecated Use the equivalent QgsSymbolLayerUtils::drawVertexMarker function instead 2050 */ 2051 Q_DECL_DEPRECATED static void drawVertexMarker( double x, double y, QPainter &p, QgsVectorLayer::VertexMarkerType type, int vertexSize ); 2052 2053 /** 2054 * Will regenerate the `fields` property of this layer by obtaining all fields 2055 * from the dataProvider, joined fields and virtual fields. It will also 2056 * take any changes made to default values into consideration. 2057 * 2058 * \note Unless the fields on the provider have directly been modified, there is 2059 * no reason to call this method. 2060 */ 2061 void updateFields(); 2062 2063 /** 2064 * Returns the calculated default value for the specified field index. The default 2065 * value may be taken from a client side default value expression (see setDefaultValueDefinition()) 2066 * or taken from the underlying data provider. 2067 * \param index field index 2068 * \param feature optional feature to use for default value evaluation. If passed, 2069 * then properties from the feature (such as geometry) can be used when calculating 2070 * the default value. 2071 * \param context optional expression context to evaluate expressions again. If not 2072 * specified, a default context will be created 2073 * \returns calculated default value 2074 * \see setDefaultValueDefinition() 2075 * \since QGIS 3.0 2076 */ 2077 QVariant defaultValue( int index, const QgsFeature &feature = QgsFeature(), 2078 QgsExpressionContext *context = nullptr ) const; 2079 2080 /** 2081 * Sets the definition of the expression to use when calculating the default value for a field. 2082 * \param index field index 2083 * \param definition default value definition to use and evaluate 2084 * when calculating default values for field. Pass 2085 * an empty expression to clear the default. 2086 * 2087 * \see defaultValue() 2088 * \see defaultValueDefinition() 2089 * \since QGIS 3.0 2090 */ 2091 void setDefaultValueDefinition( int index, const QgsDefaultValue &definition ); 2092 2093 /** 2094 * Returns the definition of the expression used when calculating the default value for a field. 2095 * \param index field index 2096 * \returns definition of the default value with the expression evaluated 2097 * when calculating default values for field, or definition with an 2098 * empty string if no default is set 2099 * \see defaultValue() 2100 * \see setDefaultValueDefinition() 2101 * \since QGIS 3.0 2102 */ 2103 QgsDefaultValue defaultValueDefinition( int index ) const; 2104 2105 /** 2106 * Returns any constraints which are present for a specified 2107 * field index. These constraints may be inherited from the layer's data provider 2108 * or may be set manually on the vector layer from within QGIS. 2109 * \see setFieldConstraint() 2110 * \since QGIS 3.0 2111 */ 2112 QgsFieldConstraints::Constraints fieldConstraints( int fieldIndex ) const; 2113 2114 /** 2115 * Returns a map of constraint with their strength for a specific field of the layer. 2116 * \param fieldIndex field index 2117 * \since QGIS 3.0 2118 */ 2119 QMap< QgsFieldConstraints::Constraint, QgsFieldConstraints::ConstraintStrength> fieldConstraintsAndStrength( int fieldIndex ) const; 2120 2121 /** 2122 * Sets a constraint for a specified field index. Any constraints inherited from the layer's 2123 * data provider will be kept intact and cannot be modified. Ie, calling this method only allows for new 2124 * constraints to be added on top of the existing provider constraints. 2125 * \see fieldConstraints() 2126 * \see removeFieldConstraint() 2127 * \since QGIS 3.0 2128 */ 2129 void setFieldConstraint( int index, QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength = QgsFieldConstraints::ConstraintStrengthHard ); 2130 2131 /** 2132 * Removes a constraint for a specified field index. Any constraints inherited from the layer's 2133 * data provider will be kept intact and cannot be removed. 2134 * \see fieldConstraints() 2135 * \see setFieldConstraint() 2136 * \since QGIS 3.0 2137 */ 2138 void removeFieldConstraint( int index, QgsFieldConstraints::Constraint constraint ); 2139 2140 /** 2141 * Returns the constraint expression for for a specified field index, if set. 2142 * \see fieldConstraints() 2143 * \see constraintDescription() 2144 * \see setConstraintExpression() 2145 * \since QGIS 3.0 2146 */ 2147 QString constraintExpression( int index ) const; 2148 2149 /** 2150 * Returns the descriptive name for the constraint expression for a specified field index. 2151 * \see fieldConstraints() 2152 * \see constraintExpression() 2153 * \see setConstraintExpression() 2154 * \since QGIS 3.0 2155 */ 2156 QString constraintDescription( int index ) const; 2157 2158 /** 2159 * Sets the constraint expression for the specified field index. An optional descriptive name for the constraint 2160 * can also be set. Setting an empty expression will clear any existing expression constraint. 2161 * \see constraintExpression() 2162 * \see constraintDescription() 2163 * \see fieldConstraints() 2164 * \since QGIS 3.0 2165 */ 2166 void setConstraintExpression( int index, const QString &expression, const QString &description = QString() ); 2167 2168 /** 2169 * Sets the configuration flags of the field at given index 2170 * \see QgsField::ConfigurationFlag 2171 * \since QGIS 3.16 2172 */ 2173 void setFieldConfigurationFlags( int index, QgsField::ConfigurationFlags flags ) SIP_SKIP; 2174 2175 /** 2176 * Sets the given configuration \a flag for the field at given \a index to be \a active or not. 2177 * \since QGIS 3.16 2178 */ 2179 void setFieldConfigurationFlag( int index, QgsField::ConfigurationFlag flag, bool active ) SIP_SKIP; 2180 2181 /** 2182 * Returns the configuration flags of the field at given index 2183 * \see QgsField::ConfigurationFlag 2184 * \since QGIS 3.16 2185 */ 2186 QgsField::ConfigurationFlags fieldConfigurationFlags( int index ) const SIP_SKIP; 2187 2188 /** 2189 * \copydoc editorWidgetSetup 2190 */ 2191 void setEditorWidgetSetup( int index, const QgsEditorWidgetSetup &setup ); 2192 2193 /** 2194 * The editor widget setup defines which QgsFieldFormatter and editor widget will be used 2195 * for the field at `index`. 2196 * 2197 * \since QGIS 3.0 2198 */ 2199 QgsEditorWidgetSetup editorWidgetSetup( int index ) const; 2200 2201 /** 2202 * Calculates a list of unique values contained within an attribute in the layer. Note that 2203 * in some circumstances when unsaved changes are present for the layer then the returned list 2204 * may contain outdated values (for instance when the attribute value in a saved feature has 2205 * been changed inside the edit buffer then the previous saved value will be included in the 2206 * returned list). 2207 * \param fieldIndex column index for attribute 2208 * \param limit maximum number of values to return (or -1 if unlimited) 2209 * \see minimumValue() 2210 * \see maximumValue() 2211 */ 2212 QSet<QVariant> uniqueValues( int fieldIndex, int limit = -1 ) const FINAL; 2213 2214 /** 2215 * Returns unique string values of an attribute which contain a specified subset string. Subset 2216 * matching is done in a case-insensitive manner. Note that 2217 * in some circumstances when unsaved changes are present for the layer then the returned list 2218 * may contain outdated values (for instance when the attribute value in a saved feature has 2219 * been changed inside the edit buffer then the previous saved value will be included in the 2220 * returned list). 2221 * \param index column index for attribute 2222 * \param substring substring to match (case insensitive) 2223 * \param limit maxmum number of the values to return, or -1 to return all unique values 2224 * \param feedback optional feedback object for canceling request 2225 * \returns list of unique strings containing substring 2226 */ 2227 QStringList uniqueStringsMatching( int index, const QString &substring, int limit = -1, 2228 QgsFeedback *feedback = nullptr ) const; 2229 2230 /** 2231 * Returns the minimum value for an attribute column or an invalid variant in case of error. 2232 * Note that in some circumstances when unsaved changes are present for the layer then the 2233 * returned value may be outdated (for instance when the attribute value in a saved feature has 2234 * been changed inside the edit buffer then the previous saved value may be returned as the minimum). 2235 * \see maximumValue() 2236 * \see uniqueValues() 2237 */ 2238 QVariant minimumValue( int index ) const FINAL; 2239 2240 /** 2241 * Returns the maximum value for an attribute column or an invalid variant in case of error. 2242 * Note that in some circumstances when unsaved changes are present for the layer then the 2243 * returned value may be outdated (for instance when the attribute value in a saved feature has 2244 * been changed inside the edit buffer then the previous saved value may be returned as the maximum). 2245 * \see minimumValue() 2246 * \see uniqueValues() 2247 */ 2248 QVariant maximumValue( int index ) const FINAL; 2249 2250 /** 2251 * Calculates an aggregated value from the layer's features. 2252 * Currently any filtering expression provided will override filters in the FeatureRequest. 2253 * \param aggregate aggregate to calculate 2254 * \param fieldOrExpression source field or expression to use as basis for aggregated values. 2255 * \param parameters parameters controlling aggregate calculation 2256 * \param context expression context for expressions and filters 2257 * \param ok if specified, will be set to TRUE if aggregate calculation was successful 2258 * \param fids list of fids to filter, otherwise will use all fids 2259 * \returns calculated aggregate value 2260 * \since QGIS 2.16 2261 */ 2262 QVariant aggregate( QgsAggregateCalculator::Aggregate aggregate, 2263 const QString &fieldOrExpression, 2264 const QgsAggregateCalculator::AggregateParameters ¶meters = QgsAggregateCalculator::AggregateParameters(), 2265 QgsExpressionContext *context = nullptr, 2266 bool *ok = nullptr, 2267 QgsFeatureIds *fids = nullptr ) const; 2268 2269 //! Sets the blending mode used for rendering each feature 2270 void setFeatureBlendMode( QPainter::CompositionMode blendMode ); 2271 //! Returns the current blending mode for features 2272 QPainter::CompositionMode featureBlendMode() const; 2273 2274 /** 2275 * Sets the \a opacity for the vector layer, where \a opacity is a value between 0 (totally transparent) 2276 * and 1.0 (fully opaque). 2277 * \see opacity() 2278 * \see opacityChanged() 2279 * \since QGIS 3.0 2280 */ 2281 void setOpacity( double opacity ); 2282 2283 /** 2284 * Returns the opacity for the vector layer, where opacity is a value between 0 (totally transparent) 2285 * and 1.0 (fully opaque). 2286 * \see setOpacity() 2287 * \see opacityChanged() 2288 * \since QGIS 3.0 2289 */ 2290 double opacity() const; 2291 2292 QString htmlMetadata() const FINAL; 2293 2294 /** 2295 * Sets the simplification settings for fast rendering of features 2296 * \since QGIS 2.2 2297 */ setSimplifyMethod(const QgsVectorSimplifyMethod & simplifyMethod)2298 void setSimplifyMethod( const QgsVectorSimplifyMethod &simplifyMethod ) { mSimplifyMethod = simplifyMethod; } 2299 2300 /** 2301 * Returns the simplification settings for fast rendering of features 2302 * \since QGIS 2.2 2303 */ simplifyMethod()2304 inline const QgsVectorSimplifyMethod &simplifyMethod() const { return mSimplifyMethod; } 2305 2306 /** 2307 * Returns whether the VectorLayer can apply the specified simplification hint 2308 * \note Do not use in 3rd party code - may be removed in future version! 2309 * \since QGIS 2.2 2310 */ 2311 bool simplifyDrawingCanbeApplied( const QgsRenderContext &renderContext, QgsVectorSimplifyMethod::SimplifyHint simplifyHint ) const; 2312 2313 /** 2314 * Returns the conditional styles that are set for this layer. Style information is 2315 * used to render conditional formatting in the attribute table. 2316 * \returns Return a QgsConditionalLayerStyles object holding the conditional attribute 2317 * style information. Style information is generic and can be used for anything. 2318 * \since QGIS 2.12 2319 */ 2320 QgsConditionalLayerStyles *conditionalStyles() const; 2321 2322 /** 2323 * Returns the attribute table configuration object. 2324 * This defines the appearance of the attribute table. 2325 */ 2326 QgsAttributeTableConfig attributeTableConfig() const; 2327 2328 /** 2329 * Sets the attribute table configuration object. 2330 * This defines the appearance of the attribute table. 2331 */ 2332 void setAttributeTableConfig( const QgsAttributeTableConfig &attributeTableConfig ); 2333 2334 /** 2335 * The mapTip is a pretty, html representation for feature information. 2336 * 2337 * It may also contain embedded expressions. 2338 * 2339 * \since QGIS 3.0 2340 */ 2341 QString mapTipTemplate() const; 2342 2343 /** 2344 * The mapTip is a pretty, html representation for feature information. 2345 * 2346 * It may also contain embedded expressions. 2347 * 2348 * \since QGIS 3.0 2349 */ 2350 void setMapTipTemplate( const QString &mapTipTemplate ); 2351 2352 QgsExpressionContext createExpressionContext() const FINAL; 2353 2354 QgsExpressionContextScope *createExpressionContextScope() const FINAL SIP_FACTORY; 2355 2356 /** 2357 * Returns the configuration of the form used to represent this vector layer. 2358 * 2359 * \returns The configuration of this layers' form 2360 * 2361 * \since QGIS 2.14 2362 */ 2363 QgsEditFormConfig editFormConfig() const; 2364 2365 /** 2366 * Sets the \a editFormConfig (configuration) of the form used to represent this vector layer. 2367 * 2368 * \see editFormConfig() 2369 * \since QGIS 3.0 2370 */ 2371 void setEditFormConfig( const QgsEditFormConfig &editFormConfig ); 2372 2373 /** 2374 * Flag allowing to indicate if the extent has to be read from the XML 2375 * document when data source has no metadata or if the data provider has 2376 * to determine it. 2377 * 2378 * \since QGIS 3.0 2379 */ 2380 void setReadExtentFromXml( bool readExtentFromXml ); 2381 2382 /** 2383 * Returns TRUE if the extent is read from the XML document when data 2384 * source has no metadata, FALSE if it's the data provider which determines 2385 * it. 2386 * 2387 * \since QGIS 3.0 2388 */ 2389 bool readExtentFromXml() const; 2390 2391 /** 2392 * Tests if an edit command is active 2393 * 2394 * \since QGIS 3.0 2395 */ isEditCommandActive()2396 bool isEditCommandActive() const { return mEditCommandActive; } 2397 2398 /** 2399 * Configuration and logic to apply automatically on any edit happening on this layer. 2400 * 2401 * \since QGIS 3.4 2402 */ 2403 QgsGeometryOptions *geometryOptions() const; 2404 2405 /** 2406 * Controls, if the layer is allowed to commit changes. If this is set to FALSE 2407 * it will not be possible to commit changes on this layer. This can be used to 2408 * define checks on a layer that need to be pass before the layer can be saved. 2409 * If you use this API, make sure that: 2410 * 2411 * - the user is visibly informed that his changes were not saved and what he needs 2412 * to do in order to be able to save the changes. 2413 * - to set the property back to TRUE, once the user has fixed his data. 2414 * 2415 * When calling \see commitChanges() this flag is checked just after the 2416 * \see beforeCommitChanges() signal is emitted, so it's possible to adjust it from there. 2417 * 2418 * \note Not available in Python bindings 2419 * 2420 * \since QGIS 3.4 2421 */ 2422 bool allowCommit() const SIP_SKIP; 2423 2424 /** 2425 * Controls, if the layer is allowed to commit changes. If this is set to FALSE 2426 * it will not be possible to commit changes on this layer. This can be used to 2427 * define checks on a layer that need to be pass before the layer can be saved. 2428 * If you use this API, make sure that: 2429 * 2430 * - the user is visibly informed that his changes were not saved and what he needs 2431 * to do in order to be able to save the changes. 2432 * - to set the property back to TRUE, once the user has fixed his data. 2433 * 2434 * When calling \see commitChanges() this flag is checked just after the 2435 * \see beforeCommitChanges() signal is emitted, so it's possible to adjust it from there. 2436 * 2437 * \note Not available in Python bindings 2438 * 2439 * \since QGIS 3.4 2440 */ 2441 void setAllowCommit( bool allowCommit ) SIP_SKIP; 2442 2443 /** 2444 * Returns the manager of the stored expressions for this layer. 2445 * 2446 * \since QGIS 3.10 2447 */ storedExpressionManager()2448 QgsStoredExpressionManager *storedExpressionManager() { return mStoredExpressionManager; } 2449 2450 public slots: 2451 2452 /** 2453 * Selects feature by its ID 2454 * 2455 * \param featureId The id of the feature to select 2456 * 2457 * \see select( const QgsFeatureIds& ) 2458 */ 2459 void select( QgsFeatureId featureId ); 2460 2461 /** 2462 * Selects features by their ID 2463 * 2464 * \param featureIds The ids of the features to select 2465 * 2466 * \see select(QgsFeatureId) 2467 */ 2468 Q_INVOKABLE void select( const QgsFeatureIds &featureIds ); 2469 2470 /** 2471 * Deselects feature by its ID 2472 * 2473 * \param featureId The id of the feature to deselect 2474 * 2475 * \see deselect(const QgsFeatureIds&) 2476 */ 2477 void deselect( QgsFeatureId featureId ); 2478 2479 /** 2480 * Deselects features by their ID 2481 * 2482 * \param featureIds The ids of the features to deselect 2483 * 2484 * \see deselect(const QgsFeatureId) 2485 */ 2486 Q_INVOKABLE void deselect( const QgsFeatureIds &featureIds ); 2487 2488 /** 2489 * Clear selection 2490 * 2491 * \see selectByIds() 2492 * \see reselect() 2493 */ 2494 Q_INVOKABLE void removeSelection(); 2495 2496 /** 2497 * Reselects the previous set of selected features. This is only applicable 2498 * after a prior call to removeSelection(). 2499 * 2500 * Any other modifications to the selection following a call to removeSelection() clears 2501 * memory of the previous selection and consequently calling reselect() has no impact. 2502 * 2503 * \see removeSelection() 2504 * \since QGIS 3.10 2505 */ 2506 void reselect(); 2507 2508 /** 2509 * Update the extents for the layer. This is necessary if features are 2510 * added/deleted or the layer has been subsetted. 2511 * 2512 * \param force TRUE to update layer extent even if it's read from xml by default, FALSE otherwise 2513 */ 2514 virtual void updateExtents( bool force = false ); 2515 2516 /** 2517 * Makes the layer editable. 2518 * 2519 * This starts an edit session on this layer. Changes made in this edit session will not 2520 * be made persistent until commitChanges() is called, and can be reverted by calling 2521 * rollBack(). 2522 * 2523 * \returns TRUE if the layer was successfully made editable, or FALSE if the operation 2524 * failed (e.g. due to an underlying read-only data source, or lack of edit support 2525 * by the backend data provider). 2526 * 2527 * \see commitChanges() 2528 * \see rollBack() 2529 */ 2530 Q_INVOKABLE bool startEditing(); 2531 2532 /** 2533 * Sets the coordinate transform context to \a transformContext 2534 * 2535 * \since QGIS 3.8 2536 */ 2537 virtual void setTransformContext( const QgsCoordinateTransformContext &transformContext ) override; 2538 2539 SpatialIndexPresence hasSpatialIndex() const override; 2540 2541 bool accept( QgsStyleEntityVisitorInterface *visitor ) const override; 2542 2543 signals: 2544 2545 /** 2546 * Emitted when selection was changed 2547 * 2548 * \param selected Newly selected feature ids 2549 * \param deselected Ids of all features which have previously been selected but are not any more 2550 * \param clearAndSelect In case this is set to TRUE, the old selection was dismissed and the new selection corresponds to selected 2551 */ 2552 void selectionChanged( const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect ); 2553 2554 //! Emitted when modifications has been done on layer 2555 void layerModified(); 2556 2557 /** 2558 * Emitted whenever the allowCommitChanged() property of this layer changes. 2559 * 2560 * \since QGIS 3.4 2561 */ 2562 void allowCommitChanged(); 2563 2564 //! Emitted when the layer is checked for modifications. Use for last-minute additions. 2565 void beforeModifiedCheck() const; 2566 2567 //! Emitted before editing on this layer is started. 2568 void beforeEditingStarted(); 2569 2570 //! Emitted when editing on this layer has started. 2571 void editingStarted(); 2572 2573 //! Emitted when edited changes have been successfully written to the data provider. 2574 void editingStopped(); 2575 2576 /** 2577 * Emitted before changes are committed to the data provider. 2578 * 2579 * The \a stopEditing flag specifies if the editing mode shall be left after this commit. 2580 */ 2581 void beforeCommitChanges( bool stopEditing ); 2582 2583 //! Emitted before changes are rolled back. 2584 void beforeRollBack(); 2585 2586 /** 2587 * Emitted after changes are committed to the data provider. 2588 * \since QGIS 3.16 2589 */ 2590 void afterCommitChanges(); 2591 2592 /** 2593 * Emitted after changes are rolled back. 2594 * \since QGIS 3.4 2595 */ 2596 void afterRollBack(); 2597 2598 /** 2599 * Will be emitted, when a new attribute has been added to this vector layer. 2600 * Applies only to types QgsFields::OriginEdit, QgsFields::OriginProvider and QgsFields::OriginExpression 2601 * 2602 * \param idx The index of the new attribute 2603 * 2604 * \see updatedFields() 2605 */ 2606 void attributeAdded( int idx ); 2607 2608 /** 2609 * Will be emitted, when an expression field is going to be added to this vector layer. 2610 * Applies only to types QgsFields::OriginExpression 2611 * 2612 * \param fieldName The name of the attribute to be added 2613 */ 2614 void beforeAddingExpressionField( const QString &fieldName ); 2615 2616 /** 2617 * Will be emitted, when an attribute has been deleted from this vector layer. 2618 * Applies only to types QgsFields::OriginEdit, QgsFields::OriginProvider and QgsFields::OriginExpression 2619 * 2620 * \param idx The index of the deleted attribute 2621 * 2622 * \see updatedFields() 2623 */ 2624 void attributeDeleted( int idx ); 2625 2626 /** 2627 * Will be emitted, when an expression field is going to be deleted from this vector layer. 2628 * Applies only to types QgsFields::OriginExpression 2629 * 2630 * \param idx The index of the attribute to be deleted 2631 */ 2632 void beforeRemovingExpressionField( int idx ); 2633 2634 /** 2635 * Emitted when a new feature has been added to the layer 2636 * 2637 * \param fid The id of the new feature 2638 */ 2639 void featureAdded( QgsFeatureId fid ); 2640 2641 /** 2642 * Emitted when a feature has been deleted. 2643 * 2644 * If you do expensive operations in a slot connected to this, you should prefer to use 2645 * featuresDeleted( const QgsFeatureIds& ). 2646 * 2647 * \param fid The id of the feature which has been deleted 2648 */ 2649 void featureDeleted( QgsFeatureId fid ); 2650 2651 /** 2652 * Emitted when features have been deleted. 2653 * 2654 * If features are deleted within an edit command, this will only be emitted once at the end 2655 * to allow connected slots to minimize the overhead. 2656 * If features are deleted outside of an edit command, this signal will be emitted once per feature. 2657 * 2658 * \param fids The feature ids that have been deleted. 2659 */ 2660 void featuresDeleted( const QgsFeatureIds &fids ); 2661 2662 /** 2663 * Emitted whenever the fields available from this layer have been changed. 2664 * This can be due to manually adding attributes or due to a join. 2665 */ 2666 void updatedFields(); 2667 2668 /** 2669 * Emitted when the layer's subset string has changed. 2670 * \since QGIS 3.2 2671 */ 2672 void subsetStringChanged(); 2673 2674 /** 2675 * Emitted whenever an attribute value change is done in the edit buffer. 2676 * Note that at this point the attribute change is not yet saved to the provider. 2677 * 2678 * \param fid The id of the changed feature 2679 * \param idx The attribute index of the changed attribute 2680 * \param value The new value of the attribute 2681 */ 2682 void attributeValueChanged( QgsFeatureId fid, int idx, const QVariant &value ); 2683 2684 /** 2685 * Emitted whenever a geometry change is done in the edit buffer. 2686 * Note that at this point the geometry change is not yet saved to the provider. 2687 * 2688 * \param fid The id of the changed feature 2689 * \param geometry The new geometry 2690 */ 2691 void geometryChanged( QgsFeatureId fid, const QgsGeometry &geometry ); 2692 2693 //! Emitted when attributes are deleted from the provider 2694 void committedAttributesDeleted( const QString &layerId, const QgsAttributeList &deletedAttributes ); 2695 //! Emitted when attributes are added to the provider 2696 void committedAttributesAdded( const QString &layerId, const QList<QgsField> &addedAttributes ); 2697 //! Emitted when features are added to the provider 2698 void committedFeaturesAdded( const QString &layerId, const QgsFeatureList &addedFeatures ); 2699 //! Emitted when features are deleted from the provider 2700 void committedFeaturesRemoved( const QString &layerId, const QgsFeatureIds &deletedFeatureIds ); 2701 //! Emitted when attribute value changes are saved to the provider 2702 void committedAttributeValuesChanges( const QString &layerId, const QgsChangedAttributesMap &changedAttributesValues ); 2703 //! Emitted when geometry changes are saved to the provider 2704 void committedGeometriesChanges( const QString &layerId, const QgsGeometryMap &changedGeometries ); 2705 2706 //! Emitted when the font family defined for labeling layer is not found on system 2707 void labelingFontNotFound( QgsVectorLayer *layer, const QString &fontfamily ); 2708 2709 //! Signal emitted when setFeatureBlendMode() is called 2710 void featureBlendModeChanged( QPainter::CompositionMode blendMode ); 2711 2712 /** 2713 * Emitted when the layer's opacity is changed, where \a opacity is a value between 0 (transparent) 2714 * and 1 (opaque). 2715 * \see setOpacity() 2716 * \see opacity() 2717 * \since QGIS 3.0 2718 */ 2719 void opacityChanged( double opacity ); 2720 2721 /** 2722 * Signal emitted when a new edit command has been started 2723 * 2724 * \param text Description for this edit command 2725 */ 2726 void editCommandStarted( const QString &text ); 2727 2728 /** 2729 * Signal emitted, when an edit command successfully ended 2730 * \note This does not mean it is also committed, only that it is written 2731 * to the edit buffer. See beforeCommitChanges() 2732 */ 2733 void editCommandEnded(); 2734 2735 /** 2736 * Signal emitted, when an edit command is destroyed 2737 * \note This is not a rollback, it is only related to the current edit command. 2738 * See beforeRollBack() 2739 */ 2740 void editCommandDestroyed(); 2741 2742 /** 2743 * Signal emitted whenever the symbology (QML-file) for this layer is being read. 2744 * If there is custom style information saved in the file, you can connect to this signal 2745 * and update the layer style accordingly. 2746 * 2747 * \param element The XML layer style element. 2748 * 2749 * \param errorMessage Write error messages into this string. 2750 */ 2751 void readCustomSymbology( const QDomElement &element, QString &errorMessage ); 2752 2753 /** 2754 * Signal emitted whenever the symbology (QML-file) for this layer is being written. 2755 * If there is custom style information you want to save to the file, you can connect 2756 * to this signal and update the element accordingly. 2757 * 2758 * \param element The XML element where you can add additional style information to. 2759 * \param doc The XML document that you can use to create new XML nodes. 2760 * \param errorMessage Write error messages into this string. 2761 */ 2762 void writeCustomSymbology( QDomElement &element, QDomDocument &doc, QString &errorMessage ) const; 2763 2764 /** 2765 * Emitted when the map tip changes 2766 * 2767 * \since QGIS 3.0 2768 */ 2769 void mapTipTemplateChanged(); 2770 2771 /** 2772 * Emitted when the display expression changes 2773 * 2774 * \since QGIS 3.0 2775 */ 2776 void displayExpressionChanged(); 2777 2778 /** 2779 * Signals an error related to this vector layer. 2780 */ 2781 void raiseError( const QString &msg ); 2782 2783 /** 2784 * Will be emitted whenever the edit form configuration of this layer changes. 2785 * 2786 * \since QGIS 3.0 2787 */ 2788 void editFormConfigChanged(); 2789 2790 /** 2791 * Emitted when the read only state of this layer is changed. 2792 * Only applies to manually set readonly state, not to the edit mode. 2793 * 2794 * \since QGIS 3.0 2795 */ 2796 void readOnlyChanged(); 2797 2798 /** 2799 * Emitted when the feature count for symbols on this layer has been recalculated. 2800 * 2801 * \since QGIS 3.0 2802 */ 2803 void symbolFeatureCountMapChanged(); 2804 2805 protected: 2806 //! Sets the extent 2807 void setExtent( const QgsRectangle &rect ) FINAL; 2808 2809 private slots: 2810 void invalidateSymbolCountedFlag(); 2811 void onFeatureCounterCompleted(); 2812 void onFeatureCounterTerminated(); 2813 void onJoinedFieldsChanged(); 2814 void onFeatureDeleted( QgsFeatureId fid ); 2815 void onRelationsLoaded(); 2816 void onSymbolsCounted(); 2817 void onDirtyTransaction( const QString &sql, const QString &name ); 2818 void emitDataChanged(); 2819 void onAfterCommitChangesDependency(); 2820 2821 private: 2822 void updateDefaultValues( QgsFeatureId fid, QgsFeature feature = QgsFeature() ); 2823 2824 /** 2825 * Returns TRUE if the provider is in read-only mode 2826 */ 2827 bool isReadOnly() const FINAL; 2828 2829 /** 2830 * Bind layer to a specific data provider 2831 * \param provider provider key string, must match a valid QgsVectorDataProvider key. E.g. "postgres", "ogr", etc. 2832 * \param options provider options 2833 * \param flags provider flags, since QGIS 3.16 2834 */ 2835 bool setDataProvider( QString const &provider, const QgsDataProvider::ProviderOptions &options, QgsDataProvider::ReadFlags flags = QgsDataProvider::ReadFlags() ); 2836 2837 //! Read labeling from SLD 2838 void readSldLabeling( const QDomNode &node ); 2839 2840 //! Read settings from SLD TextSymbolizer element 2841 bool readSldTextSymbolizer( const QDomNode &node, QgsPalLayerSettings &settings ) const; 2842 2843 //! Read simple labeling from layer's custom properties (QGIS 2.x projects) 2844 QgsAbstractVectorLayerLabeling *readLabelingFromCustomProperties(); 2845 2846 bool deleteFeatureCascade( QgsFeatureId fid, DeleteContext *context = nullptr ); 2847 2848 #ifdef SIP_RUN 2849 QgsVectorLayer( const QgsVectorLayer &rhs ); 2850 #endif 2851 //! Returns the minimum or maximum value 2852 QVariant minimumOrMaximumValue( int index, bool minimum ) const; 2853 2854 private: // Private attributes 2855 QgsConditionalLayerStyles *mConditionalStyles = nullptr; 2856 2857 //! Pointer to data provider derived from the abastract base class QgsDataProvider 2858 QgsVectorDataProvider *mDataProvider = nullptr; 2859 2860 //! Pointer to temporal properties 2861 QgsVectorLayerTemporalProperties *mTemporalProperties = nullptr; 2862 2863 //! The preview expression used to generate a human readable preview string for features 2864 QString mDisplayExpression; 2865 2866 QString mMapTipTemplate; 2867 2868 //! The user-defined actions that are accessed from the Identify Results dialog box 2869 QgsActionManager *mActions = nullptr; 2870 2871 //! Flag indicating whether the layer is in read-only mode (editing disabled) or not 2872 bool mReadOnly = false; 2873 2874 /** 2875 * Set holding the feature IDs that are activated. Note that if a feature 2876 subsequently gets deleted (i.e. by its addition to mDeletedFeatureIds), 2877 it always needs to be removed from mSelectedFeatureIds as well. 2878 */ 2879 QgsFeatureIds mSelectedFeatureIds; 2880 2881 /** 2882 * Stores the previous set of selected features, to allow for "reselect" operations. 2883 */ 2884 QgsFeatureIds mPreviousSelectedFeatureIds; 2885 2886 //! Field map to commit 2887 QgsFields mFields; 2888 2889 //! Map that stores the aliases for attributes. Key is the attribute name and value the alias for that attribute 2890 QgsStringMap mAttributeAliasMap; 2891 2892 //! Map which stores default value expressions for fields 2893 QMap<QString, QgsDefaultValue> mDefaultExpressionMap; 2894 2895 //! An internal structure to keep track of fields that have a defaultValueOnUpdate 2896 QSet<int> mDefaultValueOnUpdateFields; 2897 2898 //! Map which stores constraints for fields 2899 QMap< QString, QgsFieldConstraints::Constraints > mFieldConstraints; 2900 2901 //! Map which stores constraint strength for fields 2902 QMap< QPair< QString, QgsFieldConstraints::Constraint >, QgsFieldConstraints::ConstraintStrength > mFieldConstraintStrength; 2903 2904 //! Map which stores expression constraints for fields. Value is a pair of expression/description. 2905 QMap< QString, QPair< QString, QString > > mFieldConstraintExpressions; 2906 2907 QMap< QString, QgsField::ConfigurationFlags > mFieldConfigurationFlags; 2908 QMap< QString, QgsEditorWidgetSetup > mFieldWidgetSetups; 2909 2910 //! Holds the configuration for the edit form 2911 QgsEditFormConfig mEditFormConfig; 2912 2913 //! Geometry type as defined in enum WkbType (qgis.h) 2914 QgsWkbTypes::Type mWkbType = QgsWkbTypes::Unknown; 2915 2916 //! Renderer object which holds the information about how to display the features 2917 QgsFeatureRenderer *mRenderer = nullptr; 2918 2919 //! Simplification object which holds the information about how to simplify the features for fast rendering 2920 QgsVectorSimplifyMethod mSimplifyMethod; 2921 2922 //! Labeling configuration 2923 QgsAbstractVectorLayerLabeling *mLabeling = nullptr; 2924 2925 //! True if labels are enabled 2926 bool mLabelsEnabled = false; 2927 2928 //! Whether 'labeling font not found' has be shown for this layer (only show once in QgsMessageBar, on first rendering) 2929 bool mLabelFontNotFoundNotified = false; 2930 2931 //! Blend mode for features 2932 QPainter::CompositionMode mFeatureBlendMode = QPainter::CompositionMode_SourceOver; 2933 2934 //! Layer opacity 2935 double mLayerOpacity = 1.0; 2936 2937 //! Flag if the vertex markers should be drawn only for selection (TRUE) or for all features (FALSE) 2938 bool mVertexMarkerOnlyForSelection = false; 2939 2940 QStringList mCommitErrors; 2941 2942 //! stores information about uncommitted changes to layer 2943 QgsVectorLayerEditBuffer *mEditBuffer = nullptr; 2944 friend class QgsVectorLayerEditBuffer; 2945 friend class QgsVectorLayerEditPassthrough; 2946 2947 //stores information about joined layers 2948 QgsVectorLayerJoinBuffer *mJoinBuffer = nullptr; 2949 2950 //!stores information about server properties 2951 std::unique_ptr< QgsVectorLayerServerProperties > mServerProperties; 2952 2953 //! stores information about expression fields on this layer 2954 QgsExpressionFieldBuffer *mExpressionFieldBuffer = nullptr; 2955 2956 //diagram rendering object. 0 if diagram drawing is disabled 2957 QgsDiagramRenderer *mDiagramRenderer = nullptr; 2958 2959 //stores infos about diagram placement (placement type, priority, position distance) 2960 QgsDiagramLayerSettings *mDiagramLayerSettings = nullptr; 2961 2962 mutable bool mValidExtent = false; 2963 mutable bool mLazyExtent = true; 2964 2965 //! Auxiliary layer 2966 std::unique_ptr<QgsAuxiliaryLayer> mAuxiliaryLayer; 2967 2968 //! Key to use to join auxiliary layer 2969 QString mAuxiliaryLayerKey; 2970 2971 // Features in renderer classes counted 2972 bool mSymbolFeatureCounted = false; 2973 2974 // Feature counts for each renderer legend key 2975 QHash<QString, long> mSymbolFeatureCountMap; 2976 QHash<QString, QgsFeatureIds> mSymbolFeatureIdMap; 2977 2978 //! True while an undo command is active 2979 bool mEditCommandActive = false; 2980 2981 bool mReadExtentFromXml; 2982 QgsRectangle mXmlExtent; 2983 2984 QgsFeatureIds mDeletedFids; 2985 2986 QgsAttributeTableConfig mAttributeTableConfig; 2987 2988 mutable QMutex mFeatureSourceConstructorMutex; 2989 2990 QgsVectorLayerFeatureCounter *mFeatureCounter = nullptr; 2991 2992 std::unique_ptr<QgsGeometryOptions> mGeometryOptions; 2993 2994 bool mAllowCommit = true; 2995 2996 //! Stored expression used for e.g. filter 2997 QgsStoredExpressionManager *mStoredExpressionManager = nullptr; 2998 2999 friend class QgsVectorLayerFeatureSource; 3000 3001 //! To avoid firing multiple time dataChanged signal on circular layer circular dependencies 3002 bool mDataChangedFired = false; 3003 3004 QList<QgsWeakRelation> mWeakRelations; 3005 3006 bool mSetLegendFromStyle = false; 3007 }; 3008 3009 3010 3011 // clazy:excludeall=qstring-allocations 3012 3013 #endif 3014