30 #include <QPainterPath> 32 #include <QProgressDialog> 36 #include <QStringBuilder> 38 #if QT_VERSION >= 0x050900 39 #include <QUndoCommand> 102 #ifdef TESTPROVIDERLIB 108 const QString &qmlStyle,
109 const QString &sldStyle,
110 const QString &styleName,
111 const QString &styleDescription,
112 const QString &uiFileContent,
126 QStringList &descriptions,
144 const QString &baseName,
145 const QString &providerKey,
147 :
QgsMapLayer( VectorLayer, baseName, vectorLayerPath )
148 , mProviderKey( providerKey )
149 , mAuxiliaryLayer( nullptr )
150 , mAuxiliaryLayerKey( QString() )
151 , mReadExtentFromXml( options.readExtentFromXml )
153 mGeometryOptions = qgis::make_unique<QgsGeometryOptions>();
158 mJoinBuffer->setParent(
this );
163 if ( !vectorLayerPath.isEmpty() && !mProviderKey.isEmpty() )
178 mSimplifyMethod.
setThreshold( settings.
value( QStringLiteral(
"qgis/simplifyDrawingTol" ), mSimplifyMethod.
threshold() ).toFloat() );
191 delete mDataProvider;
194 delete mExpressionFieldBuffer;
196 delete mDiagramLayerSettings;
197 delete mDiagramRenderer;
202 delete mConditionalStyles;
204 if ( mFeatureCounter )
205 mFeatureCounter->
cancel();
213 QList<QgsVectorLayerJoinInfo> joins =
vectorJoins();
270 auto constraintIt = constraints.constBegin();
271 for ( ; constraintIt != constraints.constEnd(); ++ constraintIt )
353 p.setPen( QColor( 50, 100, 120, 200 ) );
354 p.setBrush( QColor( 200, 200, 210, 120 ) );
355 p.drawEllipse( x - m, y - m, m * 2 + 1, m * 2 + 1 );
359 p.setPen( QColor( 255, 0, 0 ) );
360 p.drawLine( x - m, y + m, x + m, y - m );
361 p.drawLine( x - m, y - m, x + m, y + m );
367 mSelectedFeatureIds.insert( fid );
374 mSelectedFeatureIds.unite( featureIds );
381 mSelectedFeatureIds.remove( fid );
388 mSelectedFeatureIds.subtract( featureIds );
401 .setFilterRect( rect )
403 .setNoAttributes() );
408 newSelection << feat.
id();
437 newSelection << feat.
id();
459 bool matches = exp.
evaluate( &context ).toBool();
463 newSelection << feat.
id();
467 newSelection << feat.
id();
486 newSelection = mSelectedFeatureIds + ids;
490 newSelection = mSelectedFeatureIds - ids;
494 newSelection = mSelectedFeatureIds.intersect( ids );
498 QgsFeatureIds deselectedFeatures = mSelectedFeatureIds - newSelection;
499 mSelectedFeatureIds = newSelection;
507 if ( !intersectingIds.isEmpty() )
509 QgsDebugMsgLevel( QStringLiteral(
"Trying to select and deselect the same item at the same time. Unsure what to do. Selecting dubious items." ), 3 );
512 mSelectedFeatureIds -= deselectIds;
513 mSelectedFeatureIds += selectIds;
521 ids.subtract( mSelectedFeatureIds );
536 .setFilterRect( rect )
538 .setNoAttributes() );
546 if ( mSelectedFeatureIds.contains( fet.
id() ) )
548 deselectIds << fet.
id();
552 selectIds << fet.
id();
561 if ( mSelectedFeatureIds.isEmpty() )
569 return mDataProvider;
574 return mDataProvider;
579 if (
mValid && mDataProvider && mDataProvider->
encoding() != encoding )
588 delete mDiagramRenderer;
589 mDiagramRenderer = r;
596 if (
mValid && mDataProvider )
602 QgsDebugMsgLevel( QStringLiteral(
"invalid layer or pointer to mDataProvider is null" ), 3 );
612 QgsDebugMsg( QStringLiteral(
"WARNING: This code should never be reached. Problems may occur..." ) );
636 .setFilterFids( mSelectedFeatureIds )
637 .setNoAttributes() );
650 .setNoAttributes() );
654 if ( mSelectedFeatureIds.contains( fet.
id() ) )
665 if ( retval.
width() == 0.0 || retval.
height() == 0.0 )
674 retval.
set( -1.0, -1.0, 1.0, 1.0 );
683 return mLabelsEnabled &&
static_cast< bool >( mLabeling );
688 mLabelsEnabled = enabled;
693 if ( !mDiagramRenderer || !mDiagramLayerSettings )
696 QList<QgsDiagramSettings> settingList = mDiagramRenderer->
diagramSettings();
697 if ( !settingList.isEmpty() )
699 return settingList.at( 0 ).enabled;
706 if ( !mSymbolFeatureCounted )
709 return mSymbolFeatureCountMap.value( legendKey );
716 if ( mSymbolFeatureCounted || mFeatureCounter )
717 return mFeatureCounter;
719 mSymbolFeatureCountMap.clear();
724 return mFeatureCounter;
726 if ( !mDataProvider )
729 return mFeatureCounter;
734 return mFeatureCounter;
737 if ( !mFeatureCounter )
746 return mFeatureCounter;
752 if ( force || !mReadExtentFromXml || ( mReadExtentFromXml && mXmlExtent.
isNull() ) )
753 mValidExtent =
false;
764 if ( !mDefaultValueOnUpdateFields.isEmpty() )
769 int size = mFields.
size();
770 for (
int idx : qgis::as_const( mDefaultValueOnUpdateFields ) )
772 if ( idx < 0 || idx >= size )
790 if ( !mValidExtent && mLazyExtent && mDataProvider && !mDataProvider->
hasMetadata() && mReadExtentFromXml && !mXmlExtent.
isNull() )
797 if ( !mValidExtent && mLazyExtent && mDataProvider )
814 if ( !
mValid || !mDataProvider )
816 QgsDebugMsgLevel( QStringLiteral(
"invoked with invalid layer or null mDataProvider" ), 3 );
838 if ( it->hasGeometry() )
849 .setNoAttributes() );
884 if ( !
mValid || !mDataProvider )
886 QgsDebugMsgLevel( QStringLiteral(
"invoked with invalid layer or null mDataProvider" ), 3 );
894 if ( !
mValid || !mDataProvider )
896 QgsDebugMsgLevel( QStringLiteral(
"invoked with invalid layer or null mDataProvider" ), 3 );
923 double maximumSimplificationScale = mSimplifyMethod.
maximumScale();
926 return !( maximumSimplificationScale > 1 && renderContext.
rendererScale() <= maximumSimplificationScale );
933 return mConditionalStyles;
938 if ( !
mValid || !mDataProvider )
956 if ( !
mValid || !mEditBuffer || !mDataProvider )
960 if ( mGeometryOptions->isActive() )
963 mGeometryOptions->apply( geom );
967 bool success = mEditBuffer->
addFeature( feature );
982 if ( !mEditBuffer || !mDataProvider )
988 if ( currentFeature.
isValid() )
990 bool hasChanged =
false;
991 bool hasError =
false;
1003 QgsDebugMsgLevel( QStringLiteral(
"geometry of feature %1 could not be changed." ).arg( updatedFeature.
id() ), 3 );
1010 for (
int attr = 0; attr < fa.count(); ++attr )
1012 if ( fa.at( attr ) != ca.at( attr ) )
1020 QgsDebugMsgLevel( QStringLiteral(
"attribute %1 of feature %2 could not be changed." ).arg( attr ).arg( updatedFeature.
id() ), 3 );
1025 if ( hasChanged && !mDefaultValueOnUpdateFields.isEmpty() && !skipDefaultValues )
1026 updateDefaultValues( updatedFeature.
id(), updatedFeature );
1032 QgsDebugMsgLevel( QStringLiteral(
"feature %1 could not be retrieved" ).arg( updatedFeature.
id() ), 3 );
1040 if ( !
mValid || !mEditBuffer || !mDataProvider )
1044 bool result = utils.
insertVertex( x, y, atFeatureId, beforeVertex );
1053 if ( !
mValid || !mEditBuffer || !mDataProvider )
1057 bool result = utils.
insertVertex( point, atFeatureId, beforeVertex );
1066 if ( !
mValid || !mEditBuffer || !mDataProvider )
1070 bool result = utils.
moveVertex( x, y, atFeatureId, atVertex );
1079 if ( !
mValid || !mEditBuffer || !mDataProvider )
1083 bool result = utils.
moveVertex( p, atFeatureId, atVertex );
1092 if ( !
mValid || !mEditBuffer || !mDataProvider )
1117 int count = mSelectedFeatureIds.size();
1130 *deletedCount = deleted;
1133 return deleted == count;
1138 if ( !
mValid || !mEditBuffer || !mDataProvider )
1139 return QgsGeometry::OperationResult::LayerNotEditable;
1145 if ( !mSelectedFeatureIds.isEmpty() )
1147 result = utils.
addRing( ring, mSelectedFeatureIds, featureId );
1150 if ( result != QgsGeometry::OperationResult::Success )
1161 if ( !
mValid || !mEditBuffer || !mDataProvider )
1164 return QgsGeometry::OperationResult::LayerNotEditable;
1169 return QgsGeometry::OperationResult::InvalidInputGeometryType;
1175 return QgsGeometry::OperationResult::AddRingNotClosed;
1182 if ( !mSelectedFeatureIds.isEmpty() )
1184 result = utils.
addRing( static_cast< QgsCurve * >( ring->
clone() ), mSelectedFeatureIds, featureId );
1187 if ( result != QgsGeometry::OperationResult::Success )
1199 if ( !
mValid || !mEditBuffer || !mDataProvider )
1200 return QgsGeometry::OperationResult::LayerNotEditable;
1204 if ( mSelectedFeatureIds.empty() )
1206 QgsDebugMsgLevel( QStringLiteral(
"Number of selected features < 1" ), 3 );
1207 return QgsGeometry::OperationResult::SelectionIsEmpty;
1209 else if ( mSelectedFeatureIds.size() > 1 )
1211 QgsDebugMsgLevel( QStringLiteral(
"Number of selected features > 1" ), 3 );
1212 return QgsGeometry::OperationResult::SelectionIsGreaterThanOne;
1218 if ( result == QgsGeometry::OperationResult::Success )
1225 if ( !
mValid || !mEditBuffer || !mDataProvider )
1226 return QgsGeometry::OperationResult::LayerNotEditable;
1230 if ( mSelectedFeatureIds.empty() )
1233 return QgsGeometry::OperationResult::SelectionIsEmpty;
1235 else if ( mSelectedFeatureIds.size() > 1 )
1238 return QgsGeometry::OperationResult::SelectionIsGreaterThanOne;
1244 if ( result == QgsGeometry::OperationResult::Success )
1251 if ( !
mValid || !mEditBuffer || !mDataProvider )
1252 return QgsGeometry::OperationResult::LayerNotEditable;
1256 if ( mSelectedFeatureIds.empty() )
1259 return QgsGeometry::OperationResult::SelectionIsEmpty;
1261 else if ( mSelectedFeatureIds.size() > 1 )
1264 return QgsGeometry::OperationResult::SelectionIsGreaterThanOne;
1270 if ( result == QgsGeometry::OperationResult::Success )
1277 if ( !
mValid || !mEditBuffer || !mDataProvider )
1278 return QgsGeometry::OperationResult::LayerNotEditable;
1283 if ( result == QgsGeometry::OperationResult::Success )
1290 if ( !
mValid || !mEditBuffer || !mDataProvider )
1291 return QgsGeometry::OperationResult::LayerNotEditable;
1294 return utils.
splitParts( splitLine, topologicalEditing );
1299 if ( !
mValid || !mEditBuffer || !mDataProvider )
1300 return QgsGeometry::OperationResult::LayerNotEditable;
1303 return utils.
splitFeatures( splitLine, topologicalEditing );
1308 if ( !
mValid || !mEditBuffer || !mDataProvider )
1317 if ( !
mValid || !mEditBuffer || !mDataProvider )
1326 if ( mLabeling == labeling )
1335 if ( !
mValid || !mDataProvider )
1400 QDomNode pkeyNode = layer_node.namedItem( QStringLiteral(
"provider" ) );
1402 if ( pkeyNode.isNull() )
1404 mProviderKey.clear();
1408 QDomElement pkeyElt = pkeyNode.toElement();
1409 mProviderKey = pkeyElt.text();
1413 if ( !mProviderKey.isNull() )
1418 else if (
mDataSource.contains( QLatin1String(
"dbname=" ) ) )
1420 mProviderKey = QStringLiteral(
"postgres" );
1424 mProviderKey = QStringLiteral(
"ogr" );
1428 if ( !setDataProvider( mProviderKey, options ) )
1433 QDomElement pkeyElem = pkeyNode.toElement();
1434 if ( !pkeyElem.isNull() )
1436 QString encodingString = pkeyElem.attribute( QStringLiteral(
"encoding" ) );
1437 if ( !encodingString.isEmpty() )
1444 mJoinBuffer->
readXml( layer_node );
1456 QDomNode depsNode = layer_node.namedItem( QStringLiteral(
"dataDependencies" ) );
1457 QDomNodeList depsNodes = depsNode.childNodes();
1458 QSet<QgsMapLayerDependency> sources;
1459 for (
int i = 0; i < depsNodes.count(); i++ )
1461 QString
source = depsNodes.at( i ).toElement().attribute( QStringLiteral(
"id" ) );
1467 QDomElement legendElem = layer_node.firstChildElement( QStringLiteral(
"legend" ) );
1468 if ( !legendElem.isNull() )
1469 legend->
readXml( legendElem, context );
1473 if ( mReadExtentFromXml )
1475 QDomNode extentNode = layer_node.namedItem( QStringLiteral(
"extent" ) );
1476 if ( !extentNode.isNull() )
1483 const QDomNode asNode = layer_node.namedItem( QStringLiteral(
"auxiliaryLayer" ) );
1484 const QDomElement asElem = asNode.toElement();
1485 if ( !asElem.isNull() )
1487 mAuxiliaryLayerKey = asElem.attribute( QStringLiteral(
"key" ) );
1498 setDataSource( dataSource, baseName, provider, options, loadDefaultStyleFlag );
1507 setDataProvider( provider, options );
1521 bool defaultLoadedFlag =
false;
1526 std::unique_ptr< QgsFeatureRenderer > defaultRenderer( mDataProvider->
createRenderer() );
1527 if ( defaultRenderer )
1529 defaultLoadedFlag =
true;
1536 if ( !defaultLoadedFlag && loadDefaultStyleFlag )
1542 if ( !defaultLoadedFlag &&
isSpatial() )
1560 std::unique_ptr< QgsFeatureRenderer > defaultRenderer( mDataProvider->
createRenderer() );
1561 if ( defaultRenderer )
1575 mProviderKey = provider;
1576 delete mDataProvider;
1583 if ( provider.compare( QLatin1String(
"postgres" ) ) == 0 )
1585 const QString checkUnicityKey { QStringLiteral(
"checkPrimaryKeyUnicity" ) };
1587 if ( ! uri.
hasParam( checkUnicityKey ) )
1589 uri.
setParam( checkUnicityKey, mReadExtentFromXml ?
"0" :
"1" );
1595 if ( !mDataProvider )
1601 mDataProvider->setParent(
this );
1604 QgsDebugMsgLevel( QStringLiteral(
"Instantiated the data provider plugin" ), 2 );
1616 QgsDebugMsgLevel( QStringLiteral(
"Set Data provider QgsLayerMetadata identifier[%1]" ).arg(
metadata().identifier() ), 4 );
1623 mWkbType = mDataProvider->
wkbType();
1627 if ( mProviderKey == QLatin1String(
"postgres" ) )
1635 QRegExp reg( R
"lit("[^"]+"\."([^"] + )"( \([^)]+\))?)lit" ); 1636 if ( reg.indexIn(
name() ) >= 0 )
1638 QStringList stuff = reg.capturedTexts();
1639 QString lName = stuff[1];
1643 QMap<QString, QgsMapLayer *>::const_iterator it;
1644 for ( it = layers.constBegin(); it != layers.constEnd() && ( *it )->name() != lName; ++it )
1647 if ( it != layers.constEnd() && stuff.size() > 2 )
1649 lName +=
'.' + stuff[2].mid( 2, stuff[2].length() - 3 );
1652 if ( !lName.isEmpty() )
1657 else if ( mProviderKey == QLatin1String(
"osm" ) )
1662 else if ( provider == QLatin1String(
"ogr" ) )
1666 if (
mDataSource.right( 10 ) == QLatin1String(
"|layerid=0" ) )
1669 else if ( provider == QStringLiteral(
"memory" ) )
1686 QDomDocument &document,
1691 QDomElement mapLayerNode = layer_node.toElement();
1693 if ( mapLayerNode.isNull() || (
"maplayer" != mapLayerNode.nodeName() ) )
1699 mapLayerNode.setAttribute( QStringLiteral(
"type" ), QStringLiteral(
"vector" ) );
1705 if ( mDataProvider )
1707 QDomElement provider = document.createElement( QStringLiteral(
"provider" ) );
1708 provider.setAttribute( QStringLiteral(
"encoding" ), mDataProvider->
encoding() );
1709 QDomText providerText = document.createTextNode(
providerType() );
1710 provider.appendChild( providerText );
1711 layer_node.appendChild( provider );
1715 mJoinBuffer->
writeXml( layer_node, document );
1718 QDomElement dependenciesElement = document.createElement( QStringLiteral(
"layerDependencies" ) );
1723 QDomElement depElem = document.createElement( QStringLiteral(
"layer" ) );
1724 depElem.setAttribute( QStringLiteral(
"id" ), dep.
layerId() );
1725 dependenciesElement.appendChild( depElem );
1727 layer_node.appendChild( dependenciesElement );
1730 QDomElement dataDependenciesElement = document.createElement( QStringLiteral(
"dataDependencies" ) );
1735 QDomElement depElem = document.createElement( QStringLiteral(
"layer" ) );
1736 depElem.setAttribute( QStringLiteral(
"id" ), dep.
layerId() );
1737 dataDependenciesElement.appendChild( depElem );
1739 layer_node.appendChild( dataDependenciesElement );
1744 QDomElement legendElement =
legend()->
writeXml( document, context );
1745 if ( !legendElement.isNull() )
1746 layer_node.appendChild( legendElement );
1750 mExpressionFieldBuffer->
writeXml( layer_node, document );
1755 QDomElement asElem = document.createElement( QStringLiteral(
"auxiliaryLayer" ) );
1756 if ( mAuxiliaryLayer )
1758 const QString pkField = mAuxiliaryLayer->joinInfo().targetFieldName();
1759 asElem.setAttribute( QStringLiteral(
"key" ), pkField );
1761 layer_node.appendChild( asElem );
1765 return writeSymbology( layer_node, document, errorMsg, context );
1770 QString src( source );
1782 QStringList theURIParts = src.split(
'|' );
1784 src = theURIParts.join( QStringLiteral(
"|" ) );
1788 QStringList theURIParts = src.split(
'?' );
1790 src = theURIParts.join( QStringLiteral(
"?" ) );
1792 else if (
providerType() == QLatin1String(
"delimitedtext" ) )
1794 QUrl urlSource = QUrl::fromEncoded( src.toLatin1() );
1796 urlDest.setQueryItems( urlSource.queryItems() );
1797 src = QString::fromLatin1( urlDest.toEncoded() );
1799 else if (
providerType() == QLatin1String(
"memory" ) )
1814 QString src( source );
1816 if ( provider == QLatin1String(
"spatialite" ) )
1822 else if ( provider == QLatin1String(
"ogr" ) )
1824 QStringList theURIParts = src.split(
'|' );
1826 src = theURIParts.join( QStringLiteral(
"|" ) );
1828 else if ( provider == QLatin1String(
"gpx" ) )
1830 QStringList theURIParts = src.split(
'?' );
1832 src = theURIParts.join( QStringLiteral(
"?" ) );
1834 else if ( provider == QLatin1String(
"delimitedtext" ) )
1836 QUrl urlSource = QUrl::fromEncoded( src.toLatin1() );
1838 if ( !src.startsWith( QLatin1String(
"file:" ) ) )
1840 QUrl file = QUrl::fromLocalFile( src.left( src.indexOf(
'?' ) ) );
1841 urlSource.setScheme( QStringLiteral(
"file" ) );
1842 urlSource.setPath( file.path() );
1845 QUrl urlDest = QUrl::fromLocalFile( context.
pathResolver().
readPath( urlSource.toLocalFile() ) );
1846 urlDest.setQueryItems( urlSource.queryItems() );
1847 src = QString::fromLatin1( urlDest.toEncoded() );
1871 if ( categories.testFlag(
Fields ) )
1873 if ( !mExpressionFieldBuffer )
1875 mExpressionFieldBuffer->
readXml( layerNode );
1880 QDomElement layerElement = layerNode.toElement();
1884 readStyle( layerNode, errorMessage, context, categories );
1886 if ( categories.testFlag(
MapTips ) )
1887 mMapTipTemplate = layerNode.namedItem( QStringLiteral(
"mapTip" ) ).toElement().text();
1890 mDisplayExpression = layerNode.namedItem( QStringLiteral(
"previewExpression" ) ).toElement().text();
1893 QString
displayField = layerNode.namedItem( QStringLiteral(
"displayfield" ) ).toElement().text();
1897 if ( mMapTipTemplate.isEmpty() && categories.testFlag(
MapTips ) )
1898 mMapTipTemplate = displayField;
1907 if ( categories.testFlag(
Actions ) )
1908 mActions->
readXml( layerNode );
1910 if ( categories.testFlag(
Fields ) )
1912 mAttributeAliasMap.clear();
1913 QDomNode aliasesNode = layerNode.namedItem( QStringLiteral(
"aliases" ) );
1914 if ( !aliasesNode.isNull() )
1916 QDomElement aliasElem;
1918 QDomNodeList aliasNodeList = aliasesNode.toElement().elementsByTagName( QStringLiteral(
"alias" ) );
1919 for (
int i = 0; i < aliasNodeList.size(); ++i )
1921 aliasElem = aliasNodeList.at( i ).toElement();
1924 if ( aliasElem.hasAttribute( QStringLiteral(
"field" ) ) )
1926 field = aliasElem.attribute( QStringLiteral(
"field" ) );
1930 int index = aliasElem.attribute( QStringLiteral(
"index" ) ).toInt();
1932 if ( index >= 0 && index <
fields().count() )
1938 if ( !aliasElem.attribute( QStringLiteral(
"name" ) ).isEmpty() )
1941 alias = context.
projectTranslator()->
translate( QStringLiteral(
"project:layers:%1:fieldaliases" ).arg( layerNode.namedItem( QStringLiteral(
"id" ) ).toElement().text() ), aliasElem.attribute( QStringLiteral(
"name" ) ) );
1942 QgsDebugMsgLevel(
"context" + QStringLiteral(
"project:layers:%1:fieldaliases" ).arg( layerNode.namedItem( QStringLiteral(
"id" ) ).toElement().text() ) +
" source " + aliasElem.attribute( QStringLiteral(
"name" ) ), 3 );
1947 alias = context.
projectTranslator()->
translate( QStringLiteral(
"project:layers:%1:fieldaliases" ).arg( layerNode.namedItem( QStringLiteral(
"id" ) ).toElement().text() ), field );
1948 QgsDebugMsgLevel(
"context" + QStringLiteral(
"project:layers:%1:fieldaliases" ).arg( layerNode.namedItem( QStringLiteral(
"id" ) ).toElement().text() ) +
" source " + field, 3 );
1950 if ( alias == aliasElem.attribute( QStringLiteral(
"field" ) ) )
1954 QgsDebugMsgLevel(
"field " + field +
" origalias " + aliasElem.attribute( QStringLiteral(
"name" ) ) +
" trans " + alias, 3 );
1955 mAttributeAliasMap.insert( field, alias );
1960 mDefaultExpressionMap.clear();
1961 QDomNode defaultsNode = layerNode.namedItem( QStringLiteral(
"defaults" ) );
1962 if ( !defaultsNode.isNull() )
1964 QDomNodeList defaultNodeList = defaultsNode.toElement().elementsByTagName( QStringLiteral(
"default" ) );
1965 for (
int i = 0; i < defaultNodeList.size(); ++i )
1967 QDomElement defaultElem = defaultNodeList.at( i ).toElement();
1969 QString field = defaultElem.attribute( QStringLiteral(
"field" ), QString() );
1970 QString expression = defaultElem.attribute( QStringLiteral(
"expression" ), QString() );
1971 bool applyOnUpdate = defaultElem.attribute( QStringLiteral(
"applyOnUpdate" ), QStringLiteral(
"0" ) ) == QLatin1String(
"1" );
1972 if ( field.isEmpty() || expression.isEmpty() )
1975 mDefaultExpressionMap.insert( field,
QgsDefaultValue( expression, applyOnUpdate ) );
1980 mFieldConstraints.clear();
1981 mFieldConstraintStrength.clear();
1982 QDomNode constraintsNode = layerNode.namedItem( QStringLiteral(
"constraints" ) );
1983 if ( !constraintsNode.isNull() )
1985 QDomNodeList constraintNodeList = constraintsNode.toElement().elementsByTagName( QStringLiteral(
"constraint" ) );
1986 for (
int i = 0; i < constraintNodeList.size(); ++i )
1988 QDomElement constraintElem = constraintNodeList.at( i ).toElement();
1990 QString field = constraintElem.attribute( QStringLiteral(
"field" ), QString() );
1991 int constraints = constraintElem.attribute( QStringLiteral(
"constraints" ), QStringLiteral(
"0" ) ).toInt();
1992 if ( field.isEmpty() || constraints == 0 )
1995 mFieldConstraints.insert( field, static_cast< QgsFieldConstraints::Constraints >( constraints ) );
1997 int uniqueStrength = constraintElem.attribute( QStringLiteral(
"unique_strength" ), QStringLiteral(
"1" ) ).toInt();
1998 int notNullStrength = constraintElem.attribute( QStringLiteral(
"notnull_strength" ), QStringLiteral(
"1" ) ).toInt();
1999 int expStrength = constraintElem.attribute( QStringLiteral(
"exp_strength" ), QStringLiteral(
"1" ) ).toInt();
2006 mFieldConstraintExpressions.clear();
2007 QDomNode constraintExpressionsNode = layerNode.namedItem( QStringLiteral(
"constraintExpressions" ) );
2008 if ( !constraintExpressionsNode.isNull() )
2010 QDomNodeList constraintNodeList = constraintExpressionsNode.toElement().elementsByTagName( QStringLiteral(
"constraint" ) );
2011 for (
int i = 0; i < constraintNodeList.size(); ++i )
2013 QDomElement constraintElem = constraintNodeList.at( i ).toElement();
2015 QString field = constraintElem.attribute( QStringLiteral(
"field" ), QString() );
2016 QString exp = constraintElem.attribute( QStringLiteral(
"exp" ), QString() );
2017 QString desc = constraintElem.attribute( QStringLiteral(
"desc" ), QString() );
2018 if ( field.isEmpty() || exp.isEmpty() )
2021 mFieldConstraintExpressions.insert( field, qMakePair( exp, desc ) );
2028 mExcludeAttributesWMS.clear();
2029 QDomNode excludeWMSNode = layerNode.namedItem( QStringLiteral(
"excludeAttributesWMS" ) );
2030 if ( !excludeWMSNode.isNull() )
2032 QDomNodeList attributeNodeList = excludeWMSNode.toElement().elementsByTagName( QStringLiteral(
"attribute" ) );
2033 for (
int i = 0; i < attributeNodeList.size(); ++i )
2035 mExcludeAttributesWMS.insert( attributeNodeList.at( i ).toElement().text() );
2039 mExcludeAttributesWFS.clear();
2040 QDomNode excludeWFSNode = layerNode.namedItem( QStringLiteral(
"excludeAttributesWFS" ) );
2041 if ( !excludeWFSNode.isNull() )
2043 QDomNodeList attributeNodeList = excludeWFSNode.toElement().elementsByTagName( QStringLiteral(
"attribute" ) );
2044 for (
int i = 0; i < attributeNodeList.size(); ++i )
2046 mExcludeAttributesWFS.insert( attributeNodeList.at( i ).toElement().text() );
2051 QDomElement widgetsElem = layerNode.namedItem( QStringLiteral(
"fieldConfiguration" ) ).toElement();
2052 QDomNodeList fieldConfigurationElementList = widgetsElem.elementsByTagName( QStringLiteral(
"field" ) );
2053 for (
int i = 0; i < fieldConfigurationElementList.size(); ++i )
2055 const QDomElement fieldConfigElement = fieldConfigurationElementList.at( i ).toElement();
2056 const QDomElement fieldWidgetElement = fieldConfigElement.elementsByTagName( QStringLiteral(
"editWidget" ) ).at( 0 ).toElement();
2058 QString fieldName = fieldConfigElement.attribute( QStringLiteral(
"name" ) );
2060 const QString widgetType = fieldWidgetElement.attribute( QStringLiteral(
"type" ) );
2061 const QDomElement cfgElem = fieldConfigElement.elementsByTagName( QStringLiteral(
"config" ) ).at( 0 ).toElement();
2062 const QDomElement optionsElem = cfgElem.childNodes().at( 0 ).toElement();
2064 if ( widgetType == QStringLiteral(
"ValueRelation" ) )
2066 optionsMap[ QStringLiteral(
"Value" ) ] = context.
projectTranslator()->
translate( QStringLiteral(
"project:layers:%1:fields:%2:valuerelationvalue" ).arg( layerNode.namedItem( QStringLiteral(
"id" ) ).toElement().text(), fieldName ), optionsMap[ QStringLiteral(
"Value" ) ].toString() );
2069 mFieldWidgetSetups[fieldName] = setup;
2074 mGeometryOptions->readXml( layerNode.namedItem( QStringLiteral(
"geometryOptions" ) ) );
2076 if ( categories.testFlag(
Forms ) )
2077 mEditFormConfig.
readXml( layerNode, context );
2081 mAttributeTableConfig.
readXml( layerNode );
2082 mConditionalStyles->
readXml( layerNode, context );
2088 QDomElement mapLayerNode = layerNode.toElement();
2090 && mapLayerNode.attribute( QStringLiteral(
"readOnly" ), QStringLiteral(
"0" ) ).toInt() == 1 )
2110 if ( !rendererElement.isNull() )
2130 if ( categories.testFlag(
Labeling ) )
2132 QDomElement labelingElement = node.firstChildElement( QStringLiteral(
"labeling" ) );
2134 if ( labelingElement.isNull() ||
2135 ( labelingElement.attribute( QStringLiteral(
"type" ) ) == QLatin1String(
"simple" ) && labelingElement.firstChildElement( QStringLiteral(
"settings" ) ).isNull() ) )
2143 labeling = readLabelingFromCustomProperties();
2151 if ( node.toElement().hasAttribute( QStringLiteral(
"labelsEnabled" ) ) )
2152 mLabelsEnabled = node.toElement().attribute( QStringLiteral(
"labelsEnabled" ) ).toInt();
2154 mLabelsEnabled =
true;
2160 QDomNode blendModeNode = node.namedItem( QStringLiteral(
"blendMode" ) );
2161 if ( !blendModeNode.isNull() )
2163 QDomElement e = blendModeNode.toElement();
2168 QDomNode featureBlendModeNode = node.namedItem( QStringLiteral(
"featureBlendMode" ) );
2169 if ( !featureBlendModeNode.isNull() )
2171 QDomElement e = featureBlendModeNode.toElement();
2179 QDomNode layerTransparencyNode = node.namedItem( QStringLiteral(
"layerTransparency" ) );
2180 if ( !layerTransparencyNode.isNull() )
2182 QDomElement e = layerTransparencyNode.toElement();
2183 setOpacity( 1.0 - e.text().toInt() / 100.0 );
2185 QDomNode layerOpacityNode = node.namedItem( QStringLiteral(
"layerOpacity" ) );
2186 if ( !layerOpacityNode.isNull() )
2188 QDomElement e = layerOpacityNode.toElement();
2195 QDomElement e = node.toElement();
2198 mSimplifyMethod.
setSimplifyHints( static_cast< QgsVectorSimplifyMethod::SimplifyHints >( e.attribute( QStringLiteral(
"simplifyDrawingHints" ), QStringLiteral(
"1" ) ).toInt() ) );
2199 mSimplifyMethod.
setSimplifyAlgorithm( static_cast< QgsVectorSimplifyMethod::SimplifyAlgorithm >( e.attribute( QStringLiteral(
"simplifyAlgorithm" ), QStringLiteral(
"0" ) ).toInt() ) );
2200 mSimplifyMethod.
setThreshold( e.attribute( QStringLiteral(
"simplifyDrawingTol" ), QStringLiteral(
"1" ) ).toFloat() );
2201 mSimplifyMethod.
setForceLocalOptimization( e.attribute( QStringLiteral(
"simplifyLocal" ), QStringLiteral(
"1" ) ).toInt() );
2202 mSimplifyMethod.
setMaximumScale( e.attribute( QStringLiteral(
"simplifyMaxScale" ), QStringLiteral(
"1" ) ).toFloat() );
2206 if ( categories.testFlag(
Diagrams ) )
2208 delete mDiagramRenderer;
2209 mDiagramRenderer =
nullptr;
2210 QDomElement singleCatDiagramElem = node.firstChildElement( QStringLiteral(
"SingleCategoryDiagramRenderer" ) );
2211 if ( !singleCatDiagramElem.isNull() )
2214 mDiagramRenderer->
readXml( singleCatDiagramElem, context );
2216 QDomElement linearDiagramElem = node.firstChildElement( QStringLiteral(
"LinearlyInterpolatedDiagramRenderer" ) );
2217 if ( !linearDiagramElem.isNull() )
2219 if ( linearDiagramElem.hasAttribute( QStringLiteral(
"classificationAttribute" ) ) )
2222 int idx = linearDiagramElem.attribute( QStringLiteral(
"classificationAttribute" ) ).toInt();
2223 if ( idx >= 0 && idx < mFields.
count() )
2224 linearDiagramElem.setAttribute( QStringLiteral(
"classificationField" ), mFields.
at( idx ).
name() );
2228 mDiagramRenderer->
readXml( linearDiagramElem, context );
2231 if ( mDiagramRenderer )
2233 QDomElement diagramSettingsElem = node.firstChildElement( QStringLiteral(
"DiagramLayerSettings" ) );
2234 if ( !diagramSettingsElem.isNull() )
2236 bool oldXPos = diagramSettingsElem.hasAttribute( QStringLiteral(
"xPosColumn" ) );
2237 bool oldYPos = diagramSettingsElem.hasAttribute( QStringLiteral(
"yPosColumn" ) );
2238 bool oldShow = diagramSettingsElem.hasAttribute( QStringLiteral(
"showColumn" ) );
2239 if ( oldXPos || oldYPos || oldShow )
2245 int xPosColumn = diagramSettingsElem.attribute( QStringLiteral(
"xPosColumn" ) ).toInt();
2246 if ( xPosColumn >= 0 && xPosColumn < mFields.
count() )
2251 int yPosColumn = diagramSettingsElem.attribute( QStringLiteral(
"yPosColumn" ) ).toInt();
2252 if ( yPosColumn >= 0 && yPosColumn < mFields.
count() )
2257 int showColumn = diagramSettingsElem.attribute( QStringLiteral(
"showColumn" ) ).toInt();
2258 if ( showColumn >= 0 && showColumn < mFields.
count() )
2261 QDomElement propertiesElem = diagramSettingsElem.ownerDocument().createElement( QStringLiteral(
"properties" ) );
2268 ddp.
writeXml( propertiesElem, defs );
2269 diagramSettingsElem.appendChild( propertiesElem );
2272 delete mDiagramLayerSettings;
2274 mDiagramLayerSettings->
readXml( diagramSettingsElem );
2287 QDomElement layerElement = node.toElement();
2290 ( void )
writeStyle( node, doc, errorMessage, context, categories );
2293 mGeometryOptions->writeXml( node );
2295 if ( categories.testFlag(
Fields ) )
2297 QDomElement fieldConfigurationElement = doc.createElement( QStringLiteral(
"fieldConfiguration" ) );
2298 node.appendChild( fieldConfigurationElement );
2301 Q_FOREACH (
const QgsField &field, mFields )
2303 QDomElement fieldElement = doc.createElement( QStringLiteral(
"field" ) );
2304 fieldElement.setAttribute( QStringLiteral(
"name" ), field.
name() );
2306 fieldConfigurationElement.appendChild( fieldElement );
2311 QDomElement editWidgetElement = doc.createElement( QStringLiteral(
"editWidget" ) );
2312 fieldElement.appendChild( editWidgetElement );
2314 QDomElement editWidgetConfigElement = doc.createElement( QStringLiteral(
"config" ) );
2317 editWidgetElement.appendChild( editWidgetConfigElement );
2324 QDomElement aliasElem = doc.createElement( QStringLiteral(
"aliases" ) );
2325 Q_FOREACH (
const QgsField &field, mFields )
2327 QDomElement aliasEntryElem = doc.createElement( QStringLiteral(
"alias" ) );
2328 aliasEntryElem.setAttribute( QStringLiteral(
"field" ), field.
name() );
2329 aliasEntryElem.setAttribute( QStringLiteral(
"index" ), mFields.
indexFromName( field.
name() ) );
2330 aliasEntryElem.setAttribute( QStringLiteral(
"name" ), field.
alias() );
2331 aliasElem.appendChild( aliasEntryElem );
2333 node.appendChild( aliasElem );
2336 QDomElement excludeWMSElem = doc.createElement( QStringLiteral(
"excludeAttributesWMS" ) );
2337 QSet<QString>::const_iterator attWMSIt = mExcludeAttributesWMS.constBegin();
2338 for ( ; attWMSIt != mExcludeAttributesWMS.constEnd(); ++attWMSIt )
2340 QDomElement attrElem = doc.createElement( QStringLiteral(
"attribute" ) );
2341 QDomText attrText = doc.createTextNode( *attWMSIt );
2342 attrElem.appendChild( attrText );
2343 excludeWMSElem.appendChild( attrElem );
2345 node.appendChild( excludeWMSElem );
2348 QDomElement excludeWFSElem = doc.createElement( QStringLiteral(
"excludeAttributesWFS" ) );
2349 QSet<QString>::const_iterator attWFSIt = mExcludeAttributesWFS.constBegin();
2350 for ( ; attWFSIt != mExcludeAttributesWFS.constEnd(); ++attWFSIt )
2352 QDomElement attrElem = doc.createElement( QStringLiteral(
"attribute" ) );
2353 QDomText attrText = doc.createTextNode( *attWFSIt );
2354 attrElem.appendChild( attrText );
2355 excludeWFSElem.appendChild( attrElem );
2357 node.appendChild( excludeWFSElem );
2360 QDomElement defaultsElem = doc.createElement( QStringLiteral(
"defaults" ) );
2361 Q_FOREACH (
const QgsField &field, mFields )
2363 QDomElement defaultElem = doc.createElement( QStringLiteral(
"default" ) );
2364 defaultElem.setAttribute( QStringLiteral(
"field" ), field.
name() );
2367 defaultsElem.appendChild( defaultElem );
2369 node.appendChild( defaultsElem );
2372 QDomElement constraintsElem = doc.createElement( QStringLiteral(
"constraints" ) );
2373 Q_FOREACH (
const QgsField &field, mFields )
2375 QDomElement constraintElem = doc.createElement( QStringLiteral(
"constraint" ) );
2376 constraintElem.setAttribute( QStringLiteral(
"field" ), field.
name() );
2381 constraintsElem.appendChild( constraintElem );
2383 node.appendChild( constraintsElem );
2386 QDomElement constraintExpressionsElem = doc.createElement( QStringLiteral(
"constraintExpressions" ) );
2387 Q_FOREACH (
const QgsField &field, mFields )
2389 QDomElement constraintExpressionElem = doc.createElement( QStringLiteral(
"constraint" ) );
2390 constraintExpressionElem.setAttribute( QStringLiteral(
"field" ), field.
name() );
2393 constraintExpressionsElem.appendChild( constraintExpressionElem );
2395 node.appendChild( constraintExpressionsElem );
2398 if ( !mExpressionFieldBuffer )
2406 mExpressionFieldBuffer->
writeXml( node, doc );
2411 if ( categories.testFlag(
Actions ) )
2416 mAttributeTableConfig.
writeXml( node );
2417 mConditionalStyles->
writeXml( node, doc, context );
2420 if ( categories.testFlag(
Forms ) )
2421 mEditFormConfig.
writeXml( node, context );
2425 node.toElement().setAttribute( QStringLiteral(
"readOnly" ), mReadOnly );
2430 QDomElement prevExpElem = doc.createElement( QStringLiteral(
"previewExpression" ) );
2431 QDomText prevExpText = doc.createTextNode( mDisplayExpression );
2432 prevExpElem.appendChild( prevExpText );
2433 node.appendChild( prevExpElem );
2437 if ( categories.testFlag(
MapTips ) )
2439 QDomElement mapTipElem = doc.createElement( QStringLiteral(
"mapTip" ) );
2440 QDomText mapTipText = doc.createTextNode( mMapTipTemplate );
2441 mapTipElem.appendChild( mapTipText );
2442 node.toElement().appendChild( mapTipElem );
2451 QDomElement mapLayerNode = node.toElement();
2461 QDomElement rendererElement = mRenderer->
save( doc, context );
2462 node.appendChild( rendererElement );
2466 if ( categories.testFlag(
Labeling ) )
2470 QDomElement labelingElement = mLabeling->
save( doc, context );
2471 node.appendChild( labelingElement );
2473 mapLayerNode.setAttribute( QStringLiteral(
"labelsEnabled" ), mLabelsEnabled ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
2479 mapLayerNode.setAttribute( QStringLiteral(
"simplifyDrawingHints" ), QString::number( mSimplifyMethod.
simplifyHints() ) );
2480 mapLayerNode.setAttribute( QStringLiteral(
"simplifyAlgorithm" ), QString::number( mSimplifyMethod.
simplifyAlgorithm() ) );
2481 mapLayerNode.setAttribute( QStringLiteral(
"simplifyDrawingTol" ), QString::number( mSimplifyMethod.
threshold() ) );
2482 mapLayerNode.setAttribute( QStringLiteral(
"simplifyLocal" ), mSimplifyMethod.
forceLocalOptimization() ? 1 : 0 );
2483 mapLayerNode.setAttribute( QStringLiteral(
"simplifyMaxScale" ), QString::number( mSimplifyMethod.
maximumScale() ) );
2495 QDomElement blendModeElem = doc.createElement( QStringLiteral(
"blendMode" ) );
2497 blendModeElem.appendChild( blendModeText );
2498 node.appendChild( blendModeElem );
2501 QDomElement featureBlendModeElem = doc.createElement( QStringLiteral(
"featureBlendMode" ) );
2503 featureBlendModeElem.appendChild( featureBlendModeText );
2504 node.appendChild( featureBlendModeElem );
2510 QDomElement layerOpacityElem = doc.createElement( QStringLiteral(
"layerOpacity" ) );
2511 QDomText layerOpacityText = doc.createTextNode( QString::number(
opacity() ) );
2512 layerOpacityElem.appendChild( layerOpacityText );
2513 node.appendChild( layerOpacityElem );
2516 if ( categories.testFlag(
Diagrams ) && mDiagramRenderer )
2518 mDiagramRenderer->
writeXml( mapLayerNode, doc, context );
2519 if ( mDiagramLayerSettings )
2520 mDiagramLayerSettings->
writeXml( mapLayerNode, doc );
2529 QDomElement nameElem = node.firstChildElement( QStringLiteral(
"Name" ) );
2530 if ( nameElem.isNull() )
2532 errorMessage = QStringLiteral(
"Warning: Name element not found within NamedLayer while it's required." );
2544 readSldLabeling( node );
2551 Q_UNUSED( errorMessage );
2562 QDomElement nameNode = doc.createElement( QStringLiteral(
"se:Name" ) );
2563 nameNode.appendChild( doc.createTextNode(
name() ) );
2564 node.appendChild( nameNode );
2566 QDomElement userStyleElem = doc.createElement( QStringLiteral(
"UserStyle" ) );
2567 node.appendChild( userStyleElem );
2569 QDomElement nameElem = doc.createElement( QStringLiteral(
"se:Name" ) );
2570 nameElem.appendChild( doc.createTextNode(
name() ) );
2572 userStyleElem.appendChild( nameElem );
2574 QDomElement featureTypeStyleElem = doc.createElement( QStringLiteral(
"se:FeatureTypeStyle" ) );
2575 userStyleElem.appendChild( featureTypeStyleElem );
2577 mRenderer->
toSld( doc, featureTypeStyleElem, localProps );
2580 mLabeling->
toSld( featureTypeStyleElem, localProps );
2589 if ( !mEditBuffer || !mDataProvider )
2594 if ( mGeometryOptions->isActive() )
2595 mGeometryOptions->apply( geom );
2604 if ( !skipDefaultValue && !mDefaultValueOnUpdateFields.isEmpty() )
2605 updateDefaultValues( fid );
2613 bool result =
false;
2615 switch (
fields().fieldOrigin( field ) )
2627 if ( mEditBuffer && mDataProvider )
2636 if ( result && !skipDefaultValues && !mDefaultValueOnUpdateFields.isEmpty() )
2637 updateDefaultValues( fid );
2652 for (
auto it = newValues.constBegin(); it != newValues.constEnd(); ++it )
2654 const int field = it.key();
2655 const QVariant newValue = it.value();
2658 if ( oldValues.contains( field ) )
2659 oldValue = oldValues[field];
2664 newValuesJoin[field] = newValue;
2665 oldValuesJoin[field] = oldValue;
2672 newValuesNotJoin[field] = newValue;
2673 oldValuesNotJoin[field] = oldValue;
2682 if ( ! newValuesJoin.isEmpty() && mJoinBuffer )
2687 if ( ! newValuesNotJoin.isEmpty() && mEditBuffer && mDataProvider )
2692 if ( result && !skipDefaultValues && !mDefaultValueOnUpdateFields.isEmpty() )
2694 updateDefaultValues( fid );
2702 if ( !mEditBuffer || !mDataProvider )
2710 if ( attIndex < 0 || attIndex >=
fields().count() )
2714 mFields[ attIndex ].setAlias( QString() );
2715 if ( mAttributeAliasMap.contains( name ) )
2717 mAttributeAliasMap.remove( name );
2719 mEditFormConfig.setFields( mFields );
2726 if ( index < 0 || index >=
fields().count() )
2733 if ( mExpressionFieldBuffer )
2749 if ( !mEditBuffer || !mDataProvider )
2765 if ( attIndex < 0 || attIndex >=
fields().count() )
2770 mAttributeAliasMap.insert( name, aliasString );
2771 mFields[ attIndex ].setAlias( aliasString );
2772 mEditFormConfig.setFields( mFields );
2778 if ( index < 0 || index >=
fields().count() )
2786 if ( index >= 0 && index < mFields.
count() )
2794 return mAttributeAliasMap;
2799 if ( index < 0 || index >=
fields().count() )
2808 if ( !mEditBuffer || !mDataProvider )
2816 bool deleted =
false;
2819 QList<int> attrList = attrs.toSet().toList();
2821 std::sort( attrList.begin(), attrList.end(), std::greater<int>() );
2823 for (
int attr : qgis::as_const( attrList ) )
2845 mSelectedFeatureIds.remove( fid );
2856 QgsDebugMsgLevel( QStringLiteral(
"Cannot delete features (mEditBuffer==NULL)" ), 1 );
2867 mSelectedFeatureIds.subtract( fids );
2884 for (
int i = 0; i < mFields.
count(); ++i )
2888 pkAttributesList << i;
2891 return pkAttributesList;
2905 if ( mEditBuffer && !deletedFeatures.empty() )
2907 if ( addedFeatures.size() > deletedFeatures.size() )
2908 return QgsFeatureSource::FeatureAvailability::FeaturesAvailable;
2910 return QgsFeatureSource::FeatureAvailability::FeaturesMaybeAvailable;
2913 if ( ( !mEditBuffer || addedFeatures.empty() ) && mDataProvider->
empty() )
2914 return QgsFeatureSource::FeatureAvailability::NoFeaturesAvailable;
2916 return QgsFeatureSource::FeatureAvailability::FeaturesAvailable;
2921 mCommitErrors.clear();
2923 if ( !mDataProvider )
2925 mCommitErrors << tr(
"ERROR: no provider" );
2931 mCommitErrors << tr(
"ERROR: layer not editable" );
2937 if ( !mAllowCommit )
2945 mEditBuffer =
nullptr;
2966 return mCommitErrors;
2998 mEditBuffer =
nullptr;
3003 if ( rollbackExtent )
3014 return mSelectedFeatureIds.size();
3019 return mSelectedFeatureIds;
3025 features.reserve( mSelectedFeatureIds.count() );
3028 if ( mSelectedFeatureIds.count() <= 8 )
3044 features.push_back( f );
3053 if ( mSelectedFeatureIds.isEmpty() )
3059 if ( mSelectedFeatureIds.count() == 1 )
3060 request.
setFilterFid( *mSelectedFeatureIds.constBegin() );
3069 if ( !mEditBuffer || !mDataProvider )
3072 if ( mGeometryOptions->isActive() )
3074 for (
auto feature = features.begin(); feature != features.end(); ++feature )
3077 mGeometryOptions->apply( geom );
3110 if ( mDisplayExpression == displayExpression )
3119 if ( !mDisplayExpression.isEmpty() || mFields.
isEmpty() )
3121 return mDisplayExpression;
3127 Q_FOREACH (
const QgsField &field, mFields )
3129 QString fldName = field.
name();
3135 if ( fldName.indexOf( QLatin1String(
"name" ), 0, Qt::CaseInsensitive ) > -1 )
3140 if ( fldName.indexOf( QLatin1String(
"descrip" ), 0, Qt::CaseInsensitive ) > -1 )
3145 if ( fldName.indexOf( QLatin1String(
"id" ), 0, Qt::CaseInsensitive ) > -1 )
3152 if ( !idxName.isNull() )
3165 return ( mEditBuffer && mDataProvider );
3174 bool QgsVectorLayer::isReadOnly()
const 3182 if ( readonly && mEditBuffer )
3185 mReadOnly = readonly;
3193 return mEditBuffer && mEditBuffer->
isModified();
3198 bool auxiliaryField =
false;
3202 return auxiliaryField;
3209 auxiliaryField =
true;
3212 return auxiliaryField;
3220 if ( r != mRenderer )
3224 mSymbolFeatureCounted =
false;
3225 mSymbolFeatureCountMap.clear();
3234 if ( !mDataProvider )
3240 QString ignoredError;
3244 mEditCommandActive =
true;
3250 if ( !mDataProvider )
3255 mEditCommandActive =
false;
3256 if ( !mDeletedFids.isEmpty() )
3259 mDeletedFids.clear();
3266 if ( !mDataProvider )
3273 #if QT_VERSION >= 0x050900 // setObsolete is new in Qt 5.9 3278 std::unique_ptr< QUndoCommand > command = qgis::make_unique< QUndoCommand >();
3279 command->setObsolete(
true );
3283 mEditCommandActive =
false;
3284 mDeletedFids.clear();
3290 return mJoinBuffer->
addJoin( joinInfo );
3296 return mJoinBuffer->
removeJoin( joinLayerId );
3326 if ( oi < 0 || oi >= mExpressionFieldBuffer->
expressions().size() )
3329 return mExpressionFieldBuffer->
expressions().at( oi ).cachedExpression.expression();
3340 if ( !mDataProvider )
3345 mFields = mDataProvider->
fields();
3355 if ( mExpressionFieldBuffer )
3359 QMap< QString, QString >::const_iterator aliasIt = mAttributeAliasMap.constBegin();
3360 for ( ; aliasIt != mAttributeAliasMap.constEnd(); ++aliasIt )
3366 mFields[ index ].setAlias( aliasIt.value() );
3370 mDefaultValueOnUpdateFields.clear();
3371 QMap< QString, QgsDefaultValue >::const_iterator defaultIt = mDefaultExpressionMap.constBegin();
3372 for ( ; defaultIt != mDefaultExpressionMap.constEnd(); ++defaultIt )
3374 int index = mFields.
lookupField( defaultIt.key() );
3378 mFields[ index ].setDefaultValueDefinition( defaultIt.value() );
3379 if ( defaultIt.value().applyOnUpdate() )
3380 mDefaultValueOnUpdateFields.insert( index );
3383 QMap< QString, QgsFieldConstraints::Constraints >::const_iterator constraintIt = mFieldConstraints.constBegin();
3384 for ( ; constraintIt != mFieldConstraints.constEnd(); ++constraintIt )
3386 int index = mFields.
lookupField( constraintIt.key() );
3399 mFields[ index ].setConstraints( constraints );
3402 QMap< QString, QPair< QString, QString > >::const_iterator constraintExpIt = mFieldConstraintExpressions.constBegin();
3403 for ( ; constraintExpIt != mFieldConstraintExpressions.constEnd(); ++constraintExpIt )
3405 int index = mFields.
lookupField( constraintExpIt.key() );
3416 mFields[ index ].setConstraints( constraints );
3420 for ( ; constraintStrengthIt != mFieldConstraintStrength.constEnd(); ++constraintStrengthIt )
3422 int index = mFields.
lookupField( constraintStrengthIt.key().first );
3432 constraints.
setConstraintStrength( constraintStrengthIt.key().second, constraintStrengthIt.value() );
3433 mFields[ index ].setConstraints( constraints );
3436 auto fieldWidgetIterator = mFieldWidgetSetups.constBegin();
3437 for ( ; fieldWidgetIterator != mFieldWidgetSetups.constEnd(); ++ fieldWidgetIterator )
3439 int index = mFields.
indexOf( fieldWidgetIterator.key() );
3443 mFields[index].setEditorWidgetSetup( fieldWidgetIterator.value() );
3446 if ( oldFields != mFields )
3449 mEditFormConfig.setFields( mFields );
3456 if ( index < 0 || index >= mFields.
count() )
3460 if ( expression.isEmpty() )
3464 std::unique_ptr< QgsExpressionContext > tempContext;
3469 evalContext = tempContext.get();
3502 if ( index < 0 || index >= mFields.
count() )
3507 mDefaultExpressionMap.insert( mFields.
at( index ).
name(), definition );
3511 mDefaultExpressionMap.remove( mFields.
at( index ).
name() );
3518 if ( index < 0 || index >= mFields.
count() )
3527 if ( !mDataProvider )
3540 uniqueValues = mDataProvider->
uniqueValues( index, limit );
3545 Q_FOREACH (
const QVariant &v, uniqueValues )
3547 vals << v.toString();
3551 QMapIterator< QgsFeatureId, QgsFeature > addedIt( added );
3552 while ( addedIt.hasNext() && ( limit < 0 || uniqueValues.count() < limit ) )
3555 QVariant v = addedIt.value().attribute( index );
3558 QString vs = v.toString();
3559 if ( !vals.contains( vs ) )
3568 while ( it.hasNext() && ( limit < 0 || uniqueValues.count() < limit ) )
3571 QVariant v = it.value().value( index );
3574 QString vs = v.toString();
3575 if ( !vals.contains( vs ) )
3594 uniqueValues = mDataProvider->
uniqueValues( index, limit );
3607 .setSubsetOfAttributes( attList ) );
3610 QVariant currentValue;
3611 QHash<QString, QVariant> val;
3615 val.insert( currentValue.toString(), currentValue );
3616 if ( limit >= 0 && val.size() >= limit )
3622 return val.values().toSet();
3626 Q_ASSERT_X(
false,
"QgsVectorLayer::uniqueValues()",
"Unknown source of the field!" );
3632 QStringList results;
3633 if ( !mDataProvider )
3651 QMapIterator< QgsFeatureId, QgsFeature > addedIt( added );
3652 while ( addedIt.hasNext() && ( limit < 0 || results.count() < limit ) && ( !feedback || !feedback->
isCanceled() ) )
3655 QVariant v = addedIt.value().attribute( index );
3658 QString vs = v.toString();
3659 if ( vs.contains( substring, Qt::CaseInsensitive ) && !results.contains( vs ) )
3667 while ( it.hasNext() && ( limit < 0 || results.count() < limit ) && ( !feedback || !feedback->
isCanceled() ) )
3670 QVariant v = it.value().value( index );
3673 QString vs = v.toString();
3674 if ( vs.contains( substring, Qt::CaseInsensitive ) && !results.contains( vs ) )
3705 QString fieldName = mFields.
at( index ).
name();
3706 request.
setFilterExpression( QStringLiteral(
"\"%1\" ILIKE '%%2%'" ).arg( fieldName, substring ) );
3710 QString currentValue;
3713 currentValue = f.
attribute( index ).toString();
3714 if ( !results.contains( currentValue ) )
3715 results << currentValue;
3717 if ( ( limit >= 0 && results.size() >= limit ) || ( feedback && feedback->
isCanceled() ) )
3727 Q_ASSERT_X(
false,
"QgsVectorLayer::uniqueStringsMatching()",
"Unknown source of the field!" );
3733 if ( !mDataProvider )
3751 QMapIterator< QgsFeatureId, QgsFeature > addedIt( added );
3752 while ( addedIt.hasNext() )
3755 QVariant v = addedIt.value().attribute( index );
3763 while ( it.hasNext() )
3766 QVariant v = it.value().value( index );
3798 .setSubsetOfAttributes( attList ) );
3801 double minimumValue = std::numeric_limits<double>::max();
3802 double currentValue = 0;
3805 currentValue = f.
attribute( index ).toDouble();
3806 if ( currentValue < minimumValue )
3808 minimumValue = currentValue;
3811 return QVariant( minimumValue );
3815 Q_ASSERT_X(
false,
"QgsVectorLayer::minimumValue()",
"Unknown source of the field!" );
3821 if ( !mDataProvider )
3838 QMapIterator< QgsFeatureId, QgsFeature > addedIt( added );
3839 while ( addedIt.hasNext() )
3842 QVariant v = addedIt.value().attribute( index );
3850 while ( it.hasNext() )
3853 QVariant v = it.value().value( index );
3883 .setSubsetOfAttributes( attList ) );
3886 double maximumValue = -std::numeric_limits<double>::max();
3887 double currentValue = 0;
3890 currentValue = f.
attribute( index ).toDouble();
3891 if ( currentValue > maximumValue )
3893 maximumValue = currentValue;
3896 return QVariant( maximumValue );
3900 Q_ASSERT_X(
false,
"QgsVectorLayer::maximumValue()",
"Unknown source of the field!" );
3910 if ( !mDataProvider )
3916 int attrIndex = mFields.
lookupField( fieldOrExpression );
3917 if ( attrIndex >= 0 )
3924 bool providerOk =
false;
3925 QVariant val = mDataProvider->
aggregate( aggregate, attrIndex, parameters, context, providerOk );
3939 return c.
calculate( aggregate, fieldOrExpression, context, ok );
3944 if ( mFeatureBlendMode == featureBlendMode )
3954 return mFeatureBlendMode;
3968 return mLayerOpacity;
3973 void QgsVectorLayer::readSldLabeling(
const QDomNode &node )
3978 QDomElement element = node.toElement();
3979 if ( element.isNull() )
3982 QDomElement userStyleElem = element.firstChildElement( QStringLiteral(
"UserStyle" ) );
3983 if ( userStyleElem.isNull() )
3985 QgsDebugMsgLevel( QStringLiteral(
"Info: UserStyle element not found." ), 4 );
3989 QDomElement featureTypeStyleElem = userStyleElem.firstChildElement( QStringLiteral(
"FeatureTypeStyle" ) );
3990 if ( featureTypeStyleElem.isNull() )
3992 QgsDebugMsgLevel( QStringLiteral(
"Info: FeatureTypeStyle element not found." ), 4 );
3997 QDomElement ruleElem = featureTypeStyleElem.lastChildElement( QStringLiteral(
"Rule" ) );
3998 if ( ruleElem.isNull() )
4005 QDomElement textSymbolizerElem = ruleElem.lastChildElement( QStringLiteral(
"TextSymbolizer" ) );
4006 if ( textSymbolizerElem.isNull() )
4008 QgsDebugMsgLevel( QStringLiteral(
"Info: TextSymbolizer element not found." ), 4 );
4015 QDomElement labelElem = textSymbolizerElem.firstChildElement( QStringLiteral(
"Label" ) );
4016 if ( !labelElem.isNull() )
4018 QDomElement propertyNameElem = labelElem.firstChildElement( QStringLiteral(
"PropertyName" ) );
4019 if ( !propertyNameElem.isNull() )
4024 QString labelAttribute = propertyNameElem.text();
4028 int fieldIndex = mFields.
lookupField( labelAttribute );
4029 if ( fieldIndex == -1 )
4045 QgsDebugMsgLevel( QStringLiteral(
"Info: PropertyName element not found." ), 4 );
4055 QString fontFamily = QStringLiteral(
"Sans-Serif" );
4056 int fontPointSize = 10;
4057 int fontWeight = -1;
4058 bool fontItalic =
false;
4059 bool fontUnderline =
false;
4062 QDomElement fontElem = textSymbolizerElem.firstChildElement( QStringLiteral(
"Font" ) );
4063 if ( !fontElem.isNull() )
4067 QDomElement cssElem = fontElem.firstChildElement( QStringLiteral(
"CssParameter" ) );
4068 while ( !cssElem.isNull() )
4070 cssName = cssElem.attribute( QStringLiteral(
"name" ), QStringLiteral(
"not_found" ) );
4071 if ( cssName != QLatin1String(
"not_found" ) )
4073 elemText = cssElem.text();
4074 if ( cssName == QLatin1String(
"font-family" ) )
4076 fontFamily = elemText;
4078 else if ( cssName == QLatin1String(
"font-style" ) )
4080 fontItalic = ( elemText == QLatin1String(
"italic" ) ) || ( elemText == QLatin1String(
"Italic" ) );
4082 else if ( cssName == QLatin1String(
"font-size" ) )
4085 int fontSize = elemText.toInt( &ok );
4088 fontPointSize = fontSize;
4091 else if ( cssName == QLatin1String(
"font-weight" ) )
4093 if ( ( elemText == QLatin1String(
"bold" ) ) || ( elemText == QLatin1String(
"Bold" ) ) )
4094 fontWeight = QFont::Bold;
4096 else if ( cssName == QLatin1String(
"font-underline" ) )
4098 fontUnderline = ( elemText == QLatin1String(
"underline" ) ) || ( elemText == QLatin1String(
"Underline" ) );
4102 cssElem = cssElem.nextSiblingElement( QStringLiteral(
"CssParameter" ) );
4107 QFont font( fontFamily, fontPointSize, fontWeight, fontItalic );
4108 font.setUnderline( fontUnderline );
4110 format.
setSize( fontPointSize );
4114 if ( textColor.isValid() )
4122 QDomElement haloElem = textSymbolizerElem.firstChildElement( QStringLiteral(
"Halo" ) );
4123 if ( !haloElem.isNull() )
4128 QDomElement radiusElem = haloElem.firstChildElement( QStringLiteral(
"Radius" ) );
4129 if ( !radiusElem.isNull() )
4132 double bufferSize = radiusElem.text().toDouble( &ok );
4135 bufferSettings.
setSize( bufferSize );
4140 if ( bufferColor.isValid() )
4142 bufferSettings.
setColor( bufferColor );
4147 QDomElement labelPlacementElem = textSymbolizerElem.firstChildElement( QStringLiteral(
"LabelPlacement" ) );
4148 if ( !labelPlacementElem.isNull() )
4151 QDomElement pointPlacementElem = labelPlacementElem.firstChildElement( QStringLiteral(
"PointPlacement" ) );
4152 if ( !pointPlacementElem.isNull() )
4156 QDomElement displacementElem = pointPlacementElem.firstChildElement( QStringLiteral(
"Displacement" ) );
4157 if ( !displacementElem.isNull() )
4159 QDomElement displacementXElem = displacementElem.firstChildElement( QStringLiteral(
"DisplacementX" ) );
4160 if ( !displacementXElem.isNull() )
4163 double xOffset = displacementXElem.text().toDouble( &ok );
4169 QDomElement displacementYElem = displacementElem.firstChildElement( QStringLiteral(
"DisplacementY" ) );
4170 if ( !displacementYElem.isNull() )
4173 double yOffset = displacementYElem.text().toDouble( &ok );
4181 QDomElement rotationElem = pointPlacementElem.firstChildElement( QStringLiteral(
"Rotation" ) );
4182 if ( !rotationElem.isNull() )
4185 double rotation = rotationElem.text().toDouble( &ok );
4202 return mEditFormConfig;
4207 if ( mEditFormConfig == editFormConfig )
4211 mEditFormConfig.onRelationsLoaded();
4217 return mMapTipTemplate;
4222 if ( mMapTipTemplate == mapTip )
4225 mMapTipTemplate = mapTip;
4241 if ( mAttributeTableConfig != attributeTableConfig )
4260 if ( !mDiagramLayerSettings )
4262 *mDiagramLayerSettings = s;
4268 QString myMetadata = QStringLiteral(
"<html>\n<body>\n" );
4271 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Information from provider" ) + QStringLiteral(
"</h1>\n<hr>\n" );
4272 myMetadata += QLatin1String(
"<table class=\"list-view\">\n" );
4275 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Name" ) + QStringLiteral(
"</td><td>" ) +
name() + QStringLiteral(
"</td></tr>\n" );
4280 if ( uriComponents.contains( QStringLiteral(
"path" ) ) )
4282 path = uriComponents[QStringLiteral(
"path" )].toString();
4283 if ( QFile::exists( path ) )
4284 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Path" ) + QStringLiteral(
"</td><td>%1" ).arg( QStringLiteral(
"<a href=\"%1\">%2</a>" ).arg( QUrl::fromLocalFile( path ).toString(), QDir::toNativeSeparators( path ) ) ) + QStringLiteral(
"</td></tr>\n" );
4289 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Source" ) + QStringLiteral(
"</td><td>%1" ).arg(
publicSource() ) + QStringLiteral(
"</td></tr>\n" );
4292 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Storage" ) + QStringLiteral(
"</td><td>" ) +
storageType() + QStringLiteral(
"</td></tr>\n" );
4295 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Comment" ) + QStringLiteral(
"</td><td>" ) +
dataComment() + QStringLiteral(
"</td></tr>\n" );
4298 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Encoding" ) + QStringLiteral(
"</td><td>" ) +
dataProvider()->
encoding() + QStringLiteral(
"</td></tr>\n" );
4312 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Geometry" ) + QStringLiteral(
"</td><td>" ) + typeString + QStringLiteral(
"</td></tr>\n" );
4316 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"CRS" ) + QStringLiteral(
"</td><td>" );
4319 myMetadata +=
crs().
authid() + QStringLiteral(
" - " );
4321 if (
crs().isGeographic() )
4322 myMetadata += tr(
"Geographic" );
4324 myMetadata += tr(
"Projected" );
4326 myMetadata += QLatin1String(
"</td></tr>\n" );
4329 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Extent" ) + QStringLiteral(
"</td><td>" ) +
extent().
toString() + QStringLiteral(
"</td></tr>\n" );
4332 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Unit" ) + QStringLiteral(
"</td><td>" ) +
QgsUnitTypes::toString(
crs().mapUnits() ) + QStringLiteral(
"</td></tr>\n" );
4337 QLocale locale = QLocale();
4338 locale.setNumberOptions( locale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator );
4339 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" )
4340 + tr(
"Feature count" ) + QStringLiteral(
"</td><td>" )
4342 + QStringLiteral(
"</td></tr>\n" );
4345 myMetadata += QLatin1String(
"</table>\n<br><br>" );
4348 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Identification" ) + QStringLiteral(
"</h1>\n<hr>\n" );
4350 myMetadata += QLatin1String(
"<br><br>\n" );
4353 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Extent" ) + QStringLiteral(
"</h1>\n<hr>\n" );
4355 myMetadata += QLatin1String(
"<br><br>\n" );
4358 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Access" ) + QStringLiteral(
"</h1>\n<hr>\n" );
4360 myMetadata += QLatin1String(
"<br><br>\n" );
4363 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Fields" ) + QStringLiteral(
"</h1>\n<hr>\n<table class=\"list-view\">\n" );
4367 if ( !pkAttrList.isEmpty() )
4369 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Primary key attributes" ) + QStringLiteral(
"</td><td>" );
4370 Q_FOREACH (
int idx, pkAttrList )
4374 myMetadata += QLatin1String(
"</td></tr>\n" );
4380 myMetadata += QStringLiteral(
"<tr><td class=\"highlight\">" ) + tr(
"Count" ) + QStringLiteral(
"</td><td>" ) + QString::number( myFields.
size() ) + QStringLiteral(
"</td></tr>\n" );
4382 myMetadata += QLatin1String(
"</table>\n<br><table width=\"100%\" class=\"tabular-view\">\n" );
4383 myMetadata += QLatin1String(
"<tr><th>" ) + tr(
"Field" ) + QLatin1String(
"</th><th>" ) + tr(
"Type" ) + QLatin1String(
"</th><th>" ) + tr(
"Length" ) + QLatin1String(
"</th><th>" ) + tr(
"Precision" ) + QLatin1String(
"</th><th>" ) + tr(
"Comment" ) + QLatin1String(
"</th></tr>\n" );
4385 for (
int i = 0; i < myFields.
size(); ++i )
4390 rowClass = QStringLiteral(
"class=\"odd-row\"" );
4391 myMetadata += QLatin1String(
"<tr " ) + rowClass + QLatin1String(
"><td>" ) + myField.
name() + QLatin1String(
"</td><td>" ) + myField.
typeName() + QLatin1String(
"</td><td>" ) + QString::number( myField.
length() ) + QLatin1String(
"</td><td>" ) + QString::number( myField.
precision() ) + QLatin1String(
"</td><td>" ) + myField.
comment() + QLatin1String(
"</td></tr>\n" );
4395 myMetadata += QLatin1String(
"</table>\n<br><br>" );
4398 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Contacts" ) + QStringLiteral(
"</h1>\n<hr>\n" );
4400 myMetadata += QLatin1String(
"<br><br>\n" );
4403 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"Links" ) + QStringLiteral(
"</h1>\n<hr>\n" );
4405 myMetadata += QLatin1String(
"<br><br>\n" );
4408 myMetadata += QStringLiteral(
"<h1>" ) + tr(
"History" ) + QStringLiteral(
"</h1>\n<hr>\n" );
4410 myMetadata += QLatin1String(
"<br><br>\n" );
4412 myMetadata += QStringLiteral(
"\n</body>\n</html>\n" );
4416 void QgsVectorLayer::invalidateSymbolCountedFlag()
4418 mSymbolFeatureCounted =
false;
4421 void QgsVectorLayer::onFeatureCounterCompleted()
4424 mFeatureCounter =
nullptr;
4427 void QgsVectorLayer::onFeatureCounterTerminated()
4429 mFeatureCounter =
nullptr;
4432 void QgsVectorLayer::onJoinedFieldsChanged()
4438 void QgsVectorLayer::onFeatureDeleted(
QgsFeatureId fid )
4440 if ( mEditCommandActive )
4441 mDeletedFids << fid;
4448 void QgsVectorLayer::onRelationsLoaded()
4450 mEditFormConfig.onRelationsLoaded();
4453 void QgsVectorLayer::onSymbolsCounted()
4455 if ( mFeatureCounter )
4458 mSymbolFeatureCounted =
true;
4473 msgError = QObject::tr(
"Unable to load %1 provider" ).arg( mProviderKey );
4478 if ( !listStylesExternalMethod )
4480 msgError = QObject::tr(
"Provider %1 has no %2 method" ).arg( mProviderKey, QStringLiteral(
"listStyles" ) );
4484 return listStylesExternalMethod(
mDataSource, ids, names, descriptions, msgError );
4492 msgError = QObject::tr(
"Unable to load %1 provider" ).arg( mProviderKey );
4497 if ( !getStyleByIdMethod )
4499 msgError = QObject::tr(
"Provider %1 has no %2 method" ).arg( mProviderKey, QStringLiteral(
"getStyleById" ) );
4503 return getStyleByIdMethod(
mDataSource, styleId, msgError );
4511 msgError = QObject::tr(
"Unable to load %1 provider" ).arg( mProviderKey );
4515 if ( !deleteStyleByIdMethod )
4517 msgError = QObject::tr(
"Provider %1 has no %2 method" ).arg( mProviderKey, QStringLiteral(
"deleteStyleById" ) );
4520 return deleteStyleByIdMethod(
mDataSource, styleId, msgError );
4525 bool useAsDefault,
const QString &uiFileContent, QString &msgError )
4528 QString sldStyle, qmlStyle;
4532 msgError = QObject::tr(
"Unable to load %1 provider" ).arg( mProviderKey );
4537 if ( !saveStyleExternalMethod )
4539 msgError = QObject::tr(
"Provider %1 has no %2 method" ).arg( mProviderKey, QStringLiteral(
"saveStyle" ) );
4543 QDomDocument qmlDocument, sldDocument;
4546 if ( !msgError.isNull() )
4550 qmlStyle = qmlDocument.toString();
4553 if ( !msgError.isNull() )
4557 sldStyle = sldDocument.toString();
4559 saveStyleExternalMethod(
mDataSource, qmlStyle, sldStyle, name,
4560 description, uiFileContent, useAsDefault, msgError );
4574 QString joinKey = mAuxiliaryLayerKey;
4575 if ( !key.isEmpty() )
4578 if ( storage.
isValid() && !joinKey.isEmpty() )
4601 mAuxiliaryLayerKey.clear();
4603 if ( mAuxiliaryLayer )
4616 mAuxiliaryLayer.reset( alayer );
4617 if ( mAuxiliaryLayer )
4618 mAuxiliaryLayer->setParent(
this );
4624 return mAuxiliaryLayer.get();
4629 return mAuxiliaryLayer.get();
4641 if ( loadStyleExternalMethod )
4643 QString qml, errorMsg;
4644 qml = loadStyleExternalMethod(
mDataSource, errorMsg );
4645 if ( !qml.isEmpty() )
4647 QDomDocument myDocument( QStringLiteral(
"qgis" ) );
4648 myDocument.setContent( qml );
4650 return QObject::tr(
"Loaded from Provider" );
4661 if ( mDataProvider )
4668 QSet<QgsMapLayerDependency> deps;
4677 QSet<QgsMapLayerDependency> toAdd = deps -
dependencies();
4693 if ( mDataProvider )
4713 if ( ! toAdd.isEmpty() )
4721 if ( fieldIndex < 0 || fieldIndex >= mFields.
count() )
4737 QMap< QgsFieldConstraints::Constraint, QgsFieldConstraints::ConstraintStrength > m;
4739 if ( fieldIndex < 0 || fieldIndex >= mFields.
count() )
4742 QString
name = mFields.
at( fieldIndex ).
name();
4745 for ( ; conIt != mFieldConstraintStrength.constEnd(); ++conIt )
4747 if ( conIt.key().first ==
name )
4749 m[ conIt.key().second ] = mFieldConstraintStrength.value( conIt.key() );
4758 if ( index < 0 || index >= mFields.
count() )
4764 QgsFieldConstraints::Constraints constraints = mFieldConstraints.value( name,
nullptr );
4765 constraints |= constraint;
4766 mFieldConstraints.insert( name, constraints );
4768 mFieldConstraintStrength.insert( qMakePair( name, constraint ), strength );
4775 if ( index < 0 || index >= mFields.
count() )
4781 QgsFieldConstraints::Constraints constraints = mFieldConstraints.value( name,
nullptr );
4782 constraints &= ~constraint;
4783 mFieldConstraints.insert( name, constraints );
4785 mFieldConstraintStrength.remove( qMakePair( name, constraint ) );
4792 if ( index < 0 || index >= mFields.
count() )
4800 if ( index < 0 || index >= mFields.
count() )
4808 if ( index < 0 || index >= mFields.
count() )
4811 if ( expression.isEmpty() )
4813 mFieldConstraintExpressions.remove( mFields.
at( index ).
name() );
4817 mFieldConstraintExpressions.insert( mFields.
at( index ).
name(), qMakePair( expression, description ) );
4824 if ( index < 0 || index >= mFields.
count() )
4828 mFieldWidgetSetups.remove( mFields.
at( index ).
name() );
4830 mFieldWidgetSetups.insert( mFields.
at( index ).
name(), setup );
4837 if ( index < 0 || index >= mFields.
count() )
4846 if (
customProperty( QStringLiteral(
"labeling" ) ).toString() == QLatin1String(
"pal" ) )
4848 if (
customProperty( QStringLiteral(
"labeling/enabled" ), QVariant(
false ) ).toBool() )
4852 settings.readFromLayerCustomProperties(
this );
4860 if ( key.startsWith( QLatin1String(
"labeling/" ) ) )
4870 return mAllowCommit;
4875 if ( mAllowCommit == allowCommit )
4884 return mGeometryOptions.get();
4894 return mReadExtentFromXml;
4897 void QgsVectorLayer::onDirtyTransaction(
const QString &sql,
const QString &
name )
4900 if ( tr && mEditBuffer )
void setProperty(int key, const QgsProperty &property)
Adds a property to the collection and takes ownership of it.
static void mergeScaleDependencies(double mScaleMinDenom, double mScaleMaxDenom, QgsStringMap &props)
Merges the local scale limits, if any, with the ones already in the map, if any.
bool isAuxiliaryField(int index, int &srcIndex) const
Returns true if the field comes from the auxiliary layer, false otherwise.
bool writeXml(QDomNode &layer_node, QDomDocument &doc, const QgsReadWriteContext &context) const FINAL
Write vector layer specific state to project file Dom node.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=nullptr) override
Adds a list of features in joined layers.
const QList< QgsVectorLayerJoinInfo > vectorJoins() const
Class for parsing and evaluation of expressions (formerly called "search strings").
void updateFields()
Will regenerate the fields property of this layer by obtaining all fields from the dataProvider...
QgsRectangle boundingBoxOfSelected() const
Returns the bounding box of the selected features. If there is no selection, QgsRectangle(0,0,0,0) is returned.
void opacityChanged(double opacity)
Emitted when the layer's opacity is changed, where opacity is a value between 0 (transparent) and 1 (...
QgsGeometry::OperationResult addPart(const QList< QgsPointXY > &ring)
Adds a new part polygon to a multipart feature.
bool readExtentFromXml() const
Returns true if the extent is read from the XML document when data source has no metadata, false if it's the data provider which determines it.
QgsRectangle sourceExtent() const FINAL
Returns the extent of all geometries from the source.
QgsActionManager * actions()
Returns all layer actions defined on this layer.
QString displayName() const
Returns the name to use when displaying this field.
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
double xOffset
Horizontal offset of label.
bool writeStyle(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const FINAL
Write just the style information for the layer into the document.
The class is used as a container of context for various read/write operations on other objects...
Wrapper for iterator of features from vector data provider or vector layer.
bool isCanceled() const
Tells whether the operation has been canceled already.
void featuresDeleted(const QgsFeatureIds &fids)
Emitted when features have been deleted.
void selectAll()
Select all the features.
void setConstraintStrength(Constraint constraint, ConstraintStrength strength)
Sets the strength of a constraint.
Constraint was set by layer.
bool addJoin(const QgsVectorLayerJoinInfo &joinInfo)
Joins another vector layer to this layer.
void taskTerminated()
Will be emitted by task if it has terminated for any reason other then completion (e...
virtual bool setSubsetString(const QString &subset, bool updateFeatureCount=true)
Set the subset string used to create a subset of features in the layer.
A rectangle specified with double values.
bool readSld(const QDomNode &node, QString &errorMessage) FINAL
Base class for all map layer types.
QgsGeometry::OperationResult splitParts(const QVector< QgsPointXY > &splitLine, bool topologicalEditing=false)
Splits parts cut by the given line.
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geom)
Emitted when a feature's geometry is changed.
void renameExpression(int index, const QString &name)
Renames an expression field at a given index.
virtual void writeXml(QDomElement &layerElem, QDomDocument &doc, const QgsReadWriteContext &context) const =0
Writes diagram state to a DOM element.
void setDiagramLayerSettings(const QgsDiagramLayerSettings &s)
bool loadDefaultStyle
Sets to true if the default layer style should be loaded.
QVariant maximumValue(int index) const override
Returns the maximum value of an attribute.
QgsVectorLayerFeatureCounter * countSymbolFeatures()
Count features for symbols.
void update(const QgsFields &fields)
Update the configuration with the given fields.
void setRenderer(QgsFeatureRenderer *r)
Set renderer which will be invoked to represent this layer.
Field comes from a joined layer (originIndex / 1000 = index of the join, originIndex % 1000 = index w...
float threshold() const
Gets the simplification threshold of the vector layer managed.
bool readSymbology(const QDomNode &layerNode, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) FINAL
Read the symbology for the current layer from the Dom node supplied.
QSet< QgsFeatureId > QgsFeatureIds
void setExcludeAttributesWms(const QSet< QString > &att)
A set of attributes that are not advertised in WMS requests with QGIS server.
QString joinLayerId() const
ID of the joined layer - may be used to resolve reference to the joined layer.
QgsMapLayer::LayerType type() const
Returns the type of the layer.
virtual bool renameAttribute(int attr, const QString &newName)
Renames an attribute field (but does not commit it)
virtual bool addAttribute(const QgsField &field)
Add an attribute field (but does not commit it) returns true if the field was added.
bool isValid() const
Returns the status of the layer.
QgsFeatureIds deletedFeatureIds() const
Returns a list of deleted feature IDs which are not committed.
void setMinimal()
Set a rectangle so that min corner is at max and max corner is at min.
void taskCompleted()
Will be emitted by task to indicate its successful completion.
virtual QgsMapLayer * clone() const =0
Returns a new instance equivalent to this one except for the id which is still unique.
virtual QgsLayerMetadata layerMetadata() const
Returns layer metadata collected from the provider's source.
void dependenciesChanged()
Emitted when dependencies are changed.
bool diagramsEnabled() const
Returns whether the layer contains diagrams which are enabled and should be drawn.
QgsWkbTypes::Type wkbType() const override=0
Returns the geometry type which is returned by this layer.
QSet< QString > excludeAttributesWfs() const
A set of attributes that are not advertised in WFS requests with QGIS server.
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes)
void committedAttributesDeleted(const QString &layerId, const QgsAttributeList &deletedAttributes)
Signals emitted after committing changes.
static Q_INVOKABLE QString toString(QgsUnitTypes::DistanceUnit unit)
Returns a translated string representing a distance unit.
void editFormConfigChanged()
Will be emitted whenever the edit form configuration of this layer changes.
void modifySelection(const QgsFeatureIds &selectIds, const QgsFeatureIds &deselectIds)
Modifies the current selection on this layer.
virtual bool writeXml(QDomElement &collectionElem, const QgsPropertiesDefinition &definitions) const
Writes the current state of the property collection into an XML element.
virtual void updateExtents()
Update the extents of the layer.
The QgsGeometryOptions class contains options to automatically adjust geometries to constraints on a ...
void addExpression(const QString &exp, const QgsField &fld)
Add an expression to the buffer.
QVariant minimumValue(int index) const override
Returns the minimum value of an attribute.
void removeFieldConstraint(int index, QgsFieldConstraints::Constraint constraint)
Removes a constraint for a specified field index.
QString name() const
Returns the display name of the layer.
const QgsVectorLayerJoinInfo * joinForFieldIndex(int index, const QgsFields &fields, int &sourceFieldIndex) const
Finds the vector join for a layer field index.
bool isValid() const
Returns the validity of this feature.
QString publicSource() const
Gets a version of the internal layer definition that has sensitive bits removed (for example...
virtual bool importNamedStyle(QDomDocument &doc, QString &errorMsg, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Import the properties of this layer from a QDomDocument.
void beforeRollBack()
Is emitted, before changes are rolled back.
virtual bool addFeatures(QgsFeatureList &features)
Insert a copy of the given features into the layer (but does not commit it)
void beginEditCommand(const QString &text)
Create edit command for undo/redo operations.
Use exact geometry intersection (slower) instead of bounding boxes.
QgsFieldConstraints::Constraints fieldConstraints(int fieldIndex) const
Returns any constraints which are present for a specified field index.
QgsGeometry getGeometry(QgsFeatureId fid) const
Query the layer for the geometry at the given id.
This class is a composition of two QSettings instances:
QgsGeometry::OperationResult splitParts(const QVector< QgsPointXY > &splitLine, bool topologicalEditing=false)
Splits parts cut by the given line.
QString encodedSource(const QString &source, const QgsReadWriteContext &context) const FINAL
Called by writeLayerXML(), used by derived classes to encode provider's specific data source to proje...
virtual QgsAttributeList pkAttributeIndexes() const
Returns list of indexes of fields that make up the primary key.
MAYBE_UNUSED NODISCARD QgsReadWriteContextCategoryPopper enterCategory(const QString &category, const QString &details=QString())
Push a category to the stack.
double angleOffset
Label rotation, in degrees clockwise.
int translateFeature(QgsFeatureId featureId, double dx, double dy)
Translates feature by dx, dy.
Renders the diagrams for all features with the same settings.
QString capabilitiesString() const
Returns the above in friendly format.
FeatureAvailability
Possible return value for hasFeatures() to determine if a source is empty.
void setExtent(const QgsRectangle &rect) FINAL
Sets the extent.
The QgsDefaultValue class provides a container for managing client side default values for fields...
QgsGeometry::OperationResult addRing(const QVector< QgsPointXY > &ring, QgsFeatureId *featureId=nullptr)
Adds a ring to polygon/multipolygon features.
Constraint
Constraints which may be present on a field.
virtual QStringList uniqueStringsMatching(int index, const QString &substring, int limit=-1, QgsFeedback *feedback=nullptr) const
Returns unique string values of an attribute which contain a specified subset string.
virtual bool addFeature(QgsFeature &f)
Adds a feature.
QStringList commitErrors() const
Returns a list containing any error messages generated when attempting to commit changes to the layer...
Field has been temporarily added in editing mode (originIndex = index in the list of added attributes...
QgsWkbTypes::Type wkbType() const FINAL
Returns the WKBType or WKBUnknown in case of error.
Setting options for loading vector layers.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
bool deleteFeature(QgsFeatureId fid)
Deletes a feature from the layer (but does not commit it).
void committedAttributesAdded(const QString &layerId, const QList< QgsField > &addedAttributes)
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
QSet< QgsMapLayerDependency > dependencies() const FINAL
Gets the list of dependencies.
void mapTipTemplateChanged()
Emitted when the map tip changes.
Class allowing to manage the auxiliary storage for a vector layer.
void attributeDeleted(int idx)
QList< QgsFeature > QgsFeatureList
double maximumScale() const
Returns the maximum map scale (i.e.
virtual void readXml(const QDomElement &elem, const QgsReadWriteContext &context)=0
Reads diagram state from a DOM element.
const QgsVectorJoinList & vectorJoins() const
bool deleteStyleById_t(const QString &uri, QString styleID, QString &errCause)
static void warning(const QString &msg)
Goes to qWarning.
Counts the features in a QgsVectorLayer in task.
void willBeDeleted()
Emitted in the destructor when the layer is about to be deleted, but it is still in a perfectly valid...
double rendererScale() const
Returns the renderer map scale.
void setSize(double size)
Sets the size of the buffer.
A class to represent a 2D point.
QgsEditorWidgetSetup editorWidgetSetup(int index) const
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
friend class QgsVectorLayerFeatureSource
void setForceLocalOptimization(bool localOptimization)
Sets where the simplification executes, after fetch the geometries from provider, or when supported...
void readOnlyChanged()
Emitted when the read only state of this layer is changed.
bool renameAttribute(int index, const QString &newName)
Renames an attribute field (but does not commit it).
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
void invertSelectionInRectangle(QgsRectangle &rect)
Invert selection of features found within the search rectangle (in layer's coordinates) ...
void subsetStringChanged()
Emitted when the layer's subset string has changed.
bool commitChanges()
Attempts to commit to the underlying data provider any buffered changes made since the last to call t...
QString targetFieldName() const
Returns name of the field of our layer that will be used for join.
virtual QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context)
store renderer info to XML element
const QgsVectorSimplifyMethod & simplifyMethod() const
Returns the simplification settings for fast rendering of features.
EditResult deleteVertex(QgsFeatureId featureId, int vertex)
Deletes a vertex from a feature.
virtual void setEncoding(const QString &e)
Set encoding used for accessing data from layer.
bool startEditing()
Makes the layer editable.
void setSimplifyHints(SimplifyHints simplifyHints)
Sets the simplification hints of the vector layer managed.
void setFont(const QFont &font)
Sets the font used for rendering text.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
QgsVectorLayer(const QString &path=QString(), const QString &baseName=QString(), const QString &providerLib="ogr", const QgsVectorLayer::LayerOptions &options=QgsVectorLayer::LayerOptions())
Constructor - creates a vector layer.
bool deleteAttributes(const QList< int > &attrs)
Deletes a list of attribute fields (but does not commit it)
VertexMarkerType
Editing vertex markers.
bool writeXml(QDomNode &layer_node) const
Writes the actions out in XML format.
void removeExpressionField(int index)
Remove an expression field.
void setFeatureBlendMode(QPainter::CompositionMode blendMode)
Sets the blending mode used for rendering each feature.
void writeCommonStyle(QDomElement &layerElement, QDomDocument &document, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories) const
Write style data common to all layer types.
QVariant evaluate()
Evaluate the feature and return the result.
void readCustomProperties(const QDomNode &layerNode, const QString &keyStartsWith=QString())
Read custom properties from project file.
static QgsPainting::BlendMode getBlendModeEnum(QPainter::CompositionMode blendMode)
Returns a BlendMode corresponding to a QPainter::CompositionMode.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
Remove from current selection.
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
virtual void resolveReferences(QgsProject *project)
Resolve references to other layers (kept as layer IDs after reading XML) into layer objects...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
QString readPath(const QString &filename) const
Turn filename read from the project file to an absolute path.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QString expressionField(int index) const
Returns the expression used for a given expression field.
~QgsVectorLayer() override
bool writeSymbology(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const FINAL
Write the symbology for the layer into the docment provided.
int selectedFeatureCount() const
Returns the number of features that are selected in this layer.
Class providing some utility methods to manage auxiliary storage.
SimplifyHint
Simplification flags for fast rendering of features.
Utility class for calculating aggregates for a field (or expression) over the features from a vector ...
double yOffset
Vertical offset of label.
void setLabeling(QgsAbstractVectorLayerLabeling *labeling)
Set labeling configuration.
Provider can create feature renderers using backend-specific formatting information. Since QGIS 3.2. See QgsVectorDataProvider::createRenderer().
void readCustomSymbology(const QDomElement &element, QString &errorMessage)
Signal emitted whenever the symbology (QML-file) for this layer is being read.
Aliases, widgets, WMS/WFS, expressions, constraints, virtual fields.
QgsConditionalLayerStyles * conditionalStyles() const
Returns the conditional styles that are set for this layer.
bool deleteFeatures(const QgsFeatureIds &fids)
Deletes a set of features from the layer (but does not commit it)
QString constraintDescription() const
Returns the descriptive name for the constraint expression.
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void readXml(const QDomNode &layer_node)
Reads joins from project file.
void configChanged()
Emitted whenever the configuration is changed.
void setDiagramRenderer(QgsDiagramRenderer *r)
Sets diagram rendering object (takes ownership)
Container of fields for a vector layer.
virtual void rollBack()
Stop editing and discard the edits.
A geometry is the spatial representation of a feature.
void selectByIds(const QgsFeatureIds &ids, SelectBehavior behavior=SetSelection)
Select matching features using a list of feature IDs.
bool setAttribute(int field, const QVariant &attr)
Set an attribute's value by field index.
#define RENDERER_TAG_NAME
void beforeRemovingExpressionField(int idx)
Will be emitted, when an expression field is going to be deleted from this vector layer...
long featureCount() const FINAL
Returns feature count including changes which have not yet been committed If you need only the count ...
QString source() const
Returns the source for the layer.
QString decodedSource(const QString &source, const QString &provider, const QgsReadWriteContext &context) const FINAL
Called by readLayerXML(), used by derived classes to decode provider's specific data source from proj...
static QPainter::CompositionMode getCompositionMode(QgsPainting::BlendMode blendMode)
Returns a QPainter::CompositionMode corresponding to a BlendMode.
QgsChangedAttributesMap mChangedAttributeValues
Changed attributes values which are not committed.
Allows entering a context category and takes care of leaving this category on deletion of the class...
virtual QgsFeatureIds allFeatureIds() const
Returns a list of all feature IDs for features present in the source.
double opacity() const
Returns the opacity for the vector layer, where opacity is a value between 0 (totally transparent) an...
QVariantMap decodeUri(const QString &providerKey, const QString &uri)
Returns the components (e.g.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the scope.
void setDisplayExpression(const QString &displayExpression)
Set the preview expression, used to create a human readable preview string.
Stores information about constraints which may be present on a field.
Field comes from the underlying data provider of the vector layer (originIndex = index in provider's ...
QString host() const
Returns the host.
int addTopologicalPoints(const QgsGeometry &geom)
Adds topological points for every vertex of the geometry.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
virtual QVariant aggregate(QgsAggregateCalculator::Aggregate aggregate, int index, const QgsAggregateCalculator::AggregateParameters ¶meters, QgsExpressionContext *context, bool &ok) const
Calculates an aggregated value from the layer's features.
QList< QgsRelation > referencingRelations(const QgsVectorLayer *layer=nullptr, int fieldIdx=-2) const
Gets all relations where the specified layer (and field) is the referencing part (i.e.
static const int EditingCapabilities
Bitmask of all provider's editing capabilities.
QVariant aggregate(QgsAggregateCalculator::Aggregate aggregate, const QString &fieldOrExpression, const QgsAggregateCalculator::AggregateParameters ¶meters=QgsAggregateCalculator::AggregateParameters(), QgsExpressionContext *context=nullptr, bool *ok=nullptr) const
Calculates an aggregated value from the layer's features.
void writeXml(QDomNode &node) const
Serialize to XML on layer save.
void resolveReferences(QgsProject *project) FINAL
Resolve references to other layers (kept as layer IDs after reading XML) into layer objects...
const QgsDiagramLayerSettings * diagramLayerSettings() const
void beforeCommitChanges()
Is emitted, before changes are committed to the data provider.
bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
QgsField at(int i) const
Gets field at particular index (must be in range 0..N-1)
QString port() const
Returns the port.
void committedFeaturesRemoved(const QString &layerId, const QgsFeatureIds &deletedFeatureIds)
This signal is emitted, when features are deleted from the provider.
QUuid addAction(QgsAction::ActionType type, const QString &name, const QString &command, bool capture=false)
Add an action with the given name and action details.
void committedAttributesDeleted(const QString &layerId, const QgsAttributeList &deletedAttributes)
This signal is emitted, when attributes are deleted from the provider.
void setBlendMode(QPainter::CompositionMode blendMode)
Set the blending mode used for rendering a layer.
void setConnection(const QString &aHost, const QString &aPort, const QString &aDatabase, const QString &aUsername, const QString &aPassword, SslMode sslmode=SslPrefer, const QString &authConfigId=QString())
Sets all connection related members at once.
QgsFieldConstraints::Constraints fieldConstraints(int fieldIndex) const
Returns any constraints which are present at the provider for a specified field index.
bool insertVertex(double x, double y, QgsFeatureId atFeatureId, int beforeVertex)
Insert a new vertex before the given vertex number, in the given ring, item (first number is index 0)...
void featureDeleted(QgsFeatureId fid)
Emitted when a feature has been deleted.
QMap< QString, QString > QgsStringMap
void editCommandEnded()
Signal emitted, when an edit command successfully ended.
bool isSpatial() const FINAL
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
QString displayField() const
This is a shorthand for accessing the displayExpression if it is a simple field.
OperationResult
Success or failure of a geometry operation.
void writeCustomSymbology(QDomElement &element, QDomDocument &doc, QString &errorMessage) const
Signal emitted whenever the symbology (QML-file) for this layer is being written. ...
void recalculateExtents() const
This is used to send a request that any mapcanvas using this layer update its extents.
void invertSelection()
Select not selected features and deselect selected ones.
void setParameters(const AggregateParameters ¶meters)
Sets all aggregate parameters from a parameter bundle.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Attribute table settings: choice and order of columns, conditional styling.
It has not been specified where the field comes from.
void deselect(QgsFeatureId featureId)
Deselect feature by its ID.
Constraint was set at data provider.
void styleChanged()
Signal emitted whenever a change affects the layer's style.
Field has an expression constraint set. See constraintExpression().
void setFormat(const QgsTextFormat &format)
Sets the label text formatting settings, e.g., font settings, buffer settings, etc.
QStringList customPropertyKeys() const
Returns list of all keys within custom properties.
void setMapTipTemplate(const QString &mapTipTemplate)
The mapTip is a pretty, html representation for feature information.
void removeSelection()
Clear selection.
Manages joined fields for a vector layer.
void setAuxiliaryLayer(QgsAuxiliaryLayer *layer=nullptr)
Sets the current auxiliary layer.
QgsDataProvider * createProvider(const QString &providerKey, const QString &dataSource, const QgsDataProvider::ProviderOptions &options=QgsDataProvider::ProviderOptions())
Creates a new instance of a provider.
bool updateFeature(QgsFeature &feature, bool skipDefaultValues=false)
Updates an existing feature in the layer, replacing the attributes and geometry for the feature with ...
static QgsTaskManager * taskManager()
Returns the application's task manager, used for managing application wide background task handling...
void dataChanged()
This is emitted whenever an asynchronous operation has finished and the data should be redrawn...
Base class for feedback objects to be used for cancellation of something running in a worker thread...
bool containsJoins() const
Quick way to test if there is any join at all.
QString database() const
Returns the database.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
void setFieldConstraint(int index, QgsFieldConstraints::Constraint constraint, QgsFieldConstraints::ConstraintStrength strength=QgsFieldConstraints::ConstraintStrengthHard)
Sets a constraint for a specified field index.
void featureAdded(QgsFeatureId fid)
QString mapTipTemplate() const
The mapTip is a pretty, html representation for feature information.
virtual int listStylesInDatabase(QStringList &ids, QStringList &names, QStringList &descriptions, QString &msgError)
Lists all the style in db split into related to the layer and not related to.
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
QgsRectangle mExtent
Extent of the layer.
bool isEditable() const FINAL
Returns true if the provider is in editing mode.
QString encoding() const
Gets encoding which is used for accessing data.
void setExcludeAttributesWfs(const QSet< QString > &att)
A set of attributes that are not advertised in WFS requests with QGIS server.
QgsFeatureRequest & setFilterFid(QgsFeatureId fid)
Sets feature ID that should be fetched.
bool changeAttributeValue(QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue=QVariant())
Changes attribute value in joined layers.
bool allowCommit() const
Controls, if the layer is allowed to commit changes.
bool deleteFeature(QgsFeatureId fid) const
Deletes a feature from joined layers.
Q_DECL_DEPRECATED void setDataSource(const QString &dataSource, const QString &baseName, const QString &provider, bool loadDefaultStyleFlag=false)
Update the data source of the layer.
virtual QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const
Returns the set of unique values contained within the specified fieldIndex from this source...
void committedGeometriesChanges(const QString &layerId, const QgsGeometryMap &changedGeometries)
void setEditorWidgetSetup(int index, const QgsEditorWidgetSetup &setup)
The editor widget setup defines which QgsFieldFormatter and editor widget will be used for the field ...
QgsFeature getFeature(QgsFeatureId fid) const
Query the layer for the feature with the given id.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
virtual void updateExtents(bool force=false)
Update the extents for the layer.
Type
The WKB type describes the number of dimensions a geometry has.
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
bool readXml(const QDomNode &layer_node)
Reads the actions in in XML format.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
bool simplifyDrawingCanbeApplied(const QgsRenderContext &renderContext, QgsVectorSimplifyMethod::SimplifyHint simplifyHint) const
Returns whether the VectorLayer can apply the specified simplification hint.
static QVariant readVariant(const QDomElement &element)
Read a QVariant from a QDomElement.
void setSize(double size)
Sets the size for rendered text.
QString typeName() const
Gets the field type.
QPainter::CompositionMode featureBlendMode() const
Returns the current blending mode for features.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
QString uri(bool expandAuthConfig=true) const
Returns complete uri.
bool changeGeometry(QgsFeatureId fid, QgsGeometry &geometry, bool skipDefaultValue=false)
Changes a feature's geometry within the layer's edit buffer (but does not immediately commit the chan...
void readStyleManager(const QDomNode &layerNode)
Read style manager's configuration (if any). To be called by subclasses.
void triggerRepaint(bool deferredUpdate=false)
Will advise the map canvas (and any other interested party) that this layer requires to be repainted...
bool rollBack(bool deleteBuffer=true)
Stops a current editing operation and discards any uncommitted edits.
bool readStyle(const QDomNode &node, QString &errorMessage, QgsReadWriteContext &context, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) FINAL
Read the style for the current layer from the Dom node supplied.
void attributeAdded(int idx)
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
void select(QgsFeatureId featureId)
Select feature by its ID.
#define QgsDebugMsgLevel(str, level)
virtual QgsRectangle extent() const
Returns the extent of the layer.
QString capabilitiesString() const
Capabilities for this layer, comma separated and translated.
Rendering: scale visibility, simplify method, opacity.
void featureBlendModeChanged(QPainter::CompositionMode blendMode)
Signal emitted when setFeatureBlendMode() is called.
virtual QString dataComment() const
Returns a short comment for the data that this provider is providing access to (e.g.
virtual void setMetadata(const QgsLayerMetadata &metadata)
Sets the layer's metadata store.
static QgsFeatureRenderer * load(QDomElement &symbologyElem, const QgsReadWriteContext &context)
create a renderer from XML element
bool changeAttributeValues(QgsFeatureId fid, const QgsAttributeMap &newValues, const QgsAttributeMap &oldValues=QgsAttributeMap())
Changes attributes' values in joined layers.
Evaluates and returns the diagram settings relating to a diagram for a specific feature.
void setCrs(const QgsCoordinateReferenceSystem &srs, bool emitSignal=true)
Sets layer's spatial reference system.
QSet< QgsMapLayerDependency > mDependencies
List of layers that may modify this layer on modification.
void reload() FINAL
Synchronises with changes in the datasource.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
virtual bool isValid() const =0
Returns true if this is a valid layer.
virtual QgsCoordinateReferenceSystem crs() const =0
Returns the coordinate system for the data source.
virtual QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Writes configuration to a DOM element, to be used later with readXml()
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
const QgsProjectTranslator * projectTranslator() const
Returns the project translator.
QgsFields fields() const override=0
Returns the fields associated with this data provider.
void writeStyleManager(QDomNode &layerNode, QDomDocument &doc) const
Write style manager's configuration (if exists). To be called by subclasses.
bool needsGeometry() const
Returns true if the expression uses feature geometry for some computation.
static QString geometryDisplayString(GeometryType type)
Returns a display string for a geometry type.
virtual void exportSldStyle(QDomDocument &doc, QString &errorMsg) const
Export the properties of this layer as SLD style in a QDomDocument.
void afterRollBack()
Is emitted, after changes are rolled back.
virtual void setExtent(const QgsRectangle &rect)
Sets the extent.
Utility class that encapsulates an action based on vector attributes.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
Geometry validation configuration.
void committedFeaturesAdded(const QString &layerId, const QgsFeatureList &addedFeatures)
This signal is emitted, when features are added to the provider.
QgsMapLayerRenderer * createMapRenderer(QgsRenderContext &rendererContext) FINAL
Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context...
void readXml(const QDomElement &elem)
Reads the diagram settings from a DOM element.
bool setDependencies(const QSet< QgsMapLayerDependency > &layers) FINAL
Sets the list of dependencies.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
QgsGeometry::OperationResult splitFeatures(const QVector< QgsPointXY > &splitLine, bool topologicalEditing=false)
Splits features cut by the given line.
Defines left outer join from our vector layer to some other vector layer.
QgsGeometry::OperationResult splitFeatures(const QVector< QgsPointXY > &splitLine, bool topologicalEditing=false)
Splits features cut by the given line.
int fieldOriginIndex(int fieldIdx) const
Gets field's origin index (its meaning is specific to each type of origin)
QMap< int, QVariant > QgsAttributeMap
virtual bool deleteAttribute(int attr)
Deletes an attribute field (but does not commit it).
void editingStopped()
Is emitted, when edited changes successfully have been written to the data provider.
void beforeEditingStarted()
Is emitted, before editing on this layer is started.
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
void writeXml(QDomNode &layer_node, QDomDocument &document) const
Saves expressions to xml under the layer node.
QgsGeometryMap mChangedGeometries
Changed geometries which are not committed.
QgsEditFormConfig editFormConfig() const
Returns the configuration of the form used to represent this vector layer.
int translateFeature(QgsFeatureId featureId, double dx, double dy)
Translates feature by dx, dy.
virtual bool isSaveAndLoadStyleToDatabaseSupported() const
It returns false by default.
void setEnabled(bool enabled)
Sets whether the text buffer will be drawn.
long addTask(QgsTask *task, int priority=0)
Adds a task to the manager.
bool moveVertex(double x, double y, QgsFeatureId atFeatureId, int atVertex)
Moves the vertex at the given position number, ring and item (first number is index 0)...
QStringList uniqueStringsMatching(int index, const QString &substring, int limit=-1, QgsFeedback *feedback=nullptr) const
Returns unique string values of an attribute which contain a specified subset string.
virtual QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
void setColor(const QColor &color)
Sets the color that text will be rendered in.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
void setLabelsEnabled(bool enabled)
Sets whether labels should be enabled for the layer.
virtual QString dataSourceUri(bool expandAuthConfig=false) const
Gets the data source specification.
virtual bool changeGeometry(QgsFeatureId fid, const QgsGeometry &geom)
Change feature's geometry.
The QgsMapLayerLegend class is abstract interface for implementations of legends for one map layer...
virtual QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context) const =0
Returns labeling configuration as XML element.
QList< QgsRelation > referencingRelations(int idx) const
Returns the layer's relations, where the foreign key is on this layer.
void raiseError(const QString &msg) const
Signals an error in this provider.
void setFieldAlias(int index, const QString &aliasString)
Sets an alias (a display name) for attributes to display in dialogs.
bool removeJoin(const QString &joinLayerId)
Removes a vector layer join.
void destroyEditCommand()
Destroy active command and reverts all changes in it.
bool addFeatures(QgsFeatureList &features, QgsFeatureSink::Flags flags=nullptr) FINAL
Adds a list of features to the sink.
An expression node which takes it value from a feature's field.
virtual void toSld(QDomNode &parent, const QgsStringMap &props) const
Writes the SE 1.1 TextSymbolizer element based on the current layer labeling settings.
QString id() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
Reads and writes project states.
void writeCustomProperties(QDomNode &layerNode, QDomDocument &doc) const
Write custom properties to project file.
Storage and management of actions associated with a layer.
bool isField() const
Checks whether an expression consists only of a single field reference.
virtual bool deleteFeatures(const QgsFeatureIds &fid)
Deletes a set of features from the layer (but does not commit it)
Provider can read layer metadata from data store. Since QGIS 3.0. See QgsDataProvider::layerMetadata(...
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geometry)
Is emitted whenever a geometry change is done in the edit buffer.
bool isEmpty() const
Returns true if the configuration is empty, ie it contains no columns.
virtual bool isClosed() const
Returns true if the curve is closed.
int count() const
Returns number of items.
bool setReadOnly(bool readonly=true)
Make layer read-only (editing disabled) or not.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
This signal is emitted when selection was changed.
virtual bool isModified() const
Returns true if the provider has been modified since the last commit.
void setParam(const QString &key, const QString &value)
Set generic param (generic mode)
virtual bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=nullptr)
Adds a single feature to the sink.
T flagValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on a flag.
QgsFeatureRenderer * renderer()
Returns renderer.
x-coordinate data defined diagram position
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
QgsFeatureIds mDeletedFeatureIds
Deleted feature IDs which are not committed.
QString constraintExpression() const
Returns the constraint expression for the field, if set.
Abstract base class for curved geometry type.
virtual void toSld(QDomDocument &doc, QDomElement &element, const QgsStringMap &props=QgsStringMap()) const
used from subclasses to create SLD Rule elements following SLD v1.1 specs
void removeCustomProperty(const QString &key)
Remove a custom property from layer.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &value)
Is emitted whenever an attribute value change is done in the edit buffer.
Encapsulate a field in an attribute table or data source.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.
Fetch only a subset of attributes (setSubsetOfAttributes sets this flag)
const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
void setSimplifyAlgorithm(SimplifyAlgorithm simplifyAlgorithm)
Sets the local simplification algorithm of the vector layer managed.
QVariant minimumValue(int index) const FINAL
Returns the minimum value for an attribute column or an invalid variant in case of error...
QVariant customProperty(const QString &value, const QVariant &defaultValue=QVariant()) const
Read a custom property from layer.
void rendererChanged()
Signal emitted when renderer is changed.
void updateFields(QgsFields &flds)
Adds fields with the expressions buffered in this object to a QgsFields object.
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QString layerId() const
Returns the ID of the layer this dependency depends on.
Single scope for storing variables and functions for use within a QgsExpressionContext.
virtual bool changeAttributeValues(QgsFeatureId fid, const QgsAttributeMap &newValues, const QgsAttributeMap &oldValues)
Changes values of attributes (but does not commit it).
Fast access to features using their ID.
QgsRelationManager relationManager
Whether diagram features act as obstacles for other diagrams/labels.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the scope.
bool mValid
Indicates if the layer is valid and can be drawn.
bool useRenderingOptimization() const
Returns true if the rendering optimization (geometry simplification) can be executed.
int indexOf(const QString &fieldName) const
Gets the field index from the field name.
void raiseError(const QString &msg)
Signals an error related to this vector layer.
Add selection to current selection.
void editingStarted()
Is emitted, when editing on this layer has started.
QgsAttributeList primaryKeyAttributes() const
Returns the list of attributes which make up the layer's primary keys.
void setName(const QString &name)
Set the display name of the layer.
QgsExpressionContext createExpressionContext() const FINAL
This method needs to be reimplemented in all classes which implement this interface and return an exp...
static Q_DECL_DEPRECATED void drawVertexMarker(double x, double y, QPainter &p, QgsVectorLayer::VertexMarkerType type, int vertexSize)
Draws a vertex symbol at (screen) coordinates x, y.
Origin origin() const
Returns the dependency origin.
Type type() const
Returns the dependency type.
virtual QSet< QgsMapLayerDependency > dependencies() const
Gets the list of layer ids on which this layer depends.
QgsAuxiliaryLayer * auxiliaryLayer()
Returns the current auxiliary layer.
Point geometry type, with support for z-dimension and m-values.
Double value (including negative values)
void symbolFeatureCountMapChanged()
Emitted when the feature count for symbols on this layer has been recalculated.
ConstraintStrength constraintStrength(Constraint constraint) const
Returns the strength of a field constraint, or ConstraintStrengthNotSet if the constraint is not pres...
void endEditCommand()
Finish edit command and add it to undo/redo stack.
virtual bool commitChanges(QStringList &commitErrors)
Attempts to commit any changes to disk.
double minimumScale() const
Returns the minimum map scale (i.e.
void setConstraint(Constraint constraint, ConstraintOrigin origin=ConstraintOriginLayer)
Sets a constraint on the field.
void committedAttributeValuesChanges(const QString &layerId, const QgsChangedAttributesMap &changedAttributesValues)
This signal is emitted, when attribute value changes are saved to the provider.
void dirtied(const QString &sql, const QString &name)
Emitted if a sql query is executed and the underlying data is modified.
QgsDefaultValue defaultValueDefinition(int index) const
Returns the definition of the expression used when calculating the default value for a field...
virtual bool deleteAttribute(int attr)
Delete an attribute field (but does not commit it)
QString attributeDisplayName(int index) const
Convenience function that returns the attribute alias if defined or the field name else...
bool readXml(const QDomNode &node, const QgsReadWriteContext &context)
Reads field ui properties specific state from Dom node.
virtual QgsTransaction * transaction() const
Returns the transaction this data provider is included in, if any.
QgsRectangle extent() const FINAL
Returns the extent of the layer.
Definition for a property.
void fullExtentCalculated()
This is emitted whenever the worker thread has fully calculated the PostGIS extents for this layer...
QgsGeometry::OperationResult addPart(const QList< QgsPointXY > &ring, QgsFeatureId featureId)
Adds a new part polygon to a multipart feature.
void writeXml(QDomElement &layerElem, QDomDocument &doc) const
Writes the diagram settings to a DOM element.
bool forceLocalOptimization() const
Gets where the simplification executes, after fetch the geometries from provider, or when supported...
int indexFromName(const QString &fieldName) const
Gets the field index from the field name.
bool loadAuxiliaryLayer(const QgsAuxiliaryStorage &storage, const QString &key=QString())
Loads the auxiliary layer for this vector layer.
QMap< int, QgsPropertyDefinition > QgsPropertiesDefinition
Definition of available properties.
QgsFeatureMap addedFeatures() const
Returns a map of new features which are not committed.
void editCommandDestroyed()
Signal emitted, when an edit command is destroyed.
Set selection, removing any existing selection.
int addExpressionField(const QString &exp, const QgsField &fld)
Add a new field which is calculated by the expression specified.
void setMaximumScale(float maximumScale)
Sets the maximum scale at which the layer should be simplified.
void dataSourceChanged()
Emitted whenever the layer's data source has been changed.
void repaintRequested(bool deferredUpdate=false)
By emitting this signal the layer tells that either appearance or content have been changed and any v...
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
The derived translate() translates with QTranslator and qm file the sourceText.
void selectByRect(QgsRectangle &rect, SelectBehavior behavior=SetSelection)
Select features found within the search rectangle (in layer's coordinates)
virtual const QgsLayerMetadata & metadata() const
Returns a reference to the layer's metadata store.
static QgsMapLayerLegend * defaultVectorLegend(QgsVectorLayer *vl)
Create new legend implementation for vector layer.
void setProviderEncoding(const QString &encoding)
Sets the textencoding of the data provider.
void relationsLoaded()
This signal is emitted when the relations were loaded after reading a project.
int addTopologicalPoints(const QgsGeometry &geom)
Adds topological points for every vertex of the geometry.
virtual void cancel()
Notifies the task that it should terminate.
General configuration: identifiable, removable, searchable, display expression, read-only.
Implementation of threaded rendering for vector layers.
Stores the settings for rendering of all diagrams for a layer.
QgsMapLayerLegend * legend() const
Can be null.
QVector< QgsPoint > QgsPointSequence
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle...
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
QString displayExpression() const
Returns the preview expression, used to create a human readable preview string.
Modify current selection to include only select features which match.
QMap< QgsFeatureId, QgsFeature > QgsFeatureMap
bool removeJoin(const QString &joinLayerId)
Removes a vector layer join.
QgsGeometryOptions * geometryOptions() const
Configuration and logic to apply automatically on any edit happening on this layer.
SelectBehavior
Selection behavior.
bool insertVertex(double x, double y, QgsFeatureId atFeatureId, int beforeVertex)
Insert a new vertex before the given vertex number, in the given ring, item (first number is index 0)...
QString providerType() const
Returns the provider type for this layer.
void selectByExpression(const QString &expression, SelectBehavior behavior=SetSelection)
Select matching features using an expression.
QgsChangedAttributesMap changedAttributeValues() const
Returns a map of features with changed attributes values which are not committed. ...
QHash< QString, long > symbolFeatureCountMap() const
Gets the count for each symbol.
void attributeAdded(int idx)
Will be emitted, when a new attribute has been added to this vector layer.
void allowCommitChanged()
Emitted whenever the allowCommitChanged() property of this layer changes.
virtual QString loadDefaultStyle(bool &resultFlag)
Retrieve the default style for this layer if one exists (either as a .qml file on disk or as a record...
void beforeAddingExpressionField(const QString &fieldName)
Will be emitted, when an expression field is going to be added to this vector layer.
Custom properties (by plugins for instance)
Contains information about the context of a rendering operation.
QgsExpressionContextScope * createExpressionContextScope() const FINAL
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QString constraintDescription(int index) const
Returns the descriptive name for the constraint expression for a specified field index.
Setting options for creating vector data providers.
QgsFieldConstraints constraints
const QgsDiagramRenderer * diagramRenderer() const
Buffers information about expression fields for a vector layer.
QString getStyleById_t(const QString &uri, QString styleID, QString &errCause)
void editCommandStarted(const QString &text)
Signal emitted when a new edit command has been started.
QString loadStyle_t(const QString &uri, QString &errCause)
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets feature IDs that should be fetched.
QSet< QString > excludeAttributesWms() const
A set of attributes that are not advertised in WMS requests with QGIS server.
bool hasDependencyCycle(const QSet< QgsMapLayerDependency > &layers) const
Checks whether a new set of dependencies will introduce a cycle.
void displayExpressionChanged()
Emitted when the display expression changes.
QgsGeometry::OperationResult addRing(const QVector< QgsPointXY > &ring, const QgsFeatureIds &targetFeatureIds=QgsFeatureIds(), QgsFeatureId *modifiedFeatureId=nullptr)
Adds a ring to polygon/multipolygon features.
bool addJoin(const QgsVectorLayerJoinInfo &joinInfo)
Joins another vector layer to this layer.
QString mDataSource
Data source description string, varies by layer type.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &)
QSet< QVariant > uniqueValues(int fieldIndex, int limit=-1) const FINAL
Calculates a list of unique values contained within an attribute in the layer.
virtual QgsVectorDataProvider::Capabilities capabilities() const
Returns flags containing the supported capabilities.
long featureCount() const override=0
Number of features in the layer.
QgsMapLayer * mapLayer(const QString &layerId) const
Retrieve a pointer to a registered layer by layer ID.
void setConstraintExpression(const QString &expression, const QString &description=QString())
Set the constraint expression for the field.
QgsCurve * clone() const override=0
Clones the geometry by performing a deep copy.
This class allows including a set of layers in a database-side transaction, provided the layer data p...
ConstraintStrength
Strength of constraints.
void updateExpression(int index, const QString &exp)
Changes the expression at a given index.
void writeXml(QDomNode &layer_node, QDomDocument &document) const
Saves mVectorJoins to xml under the layer node.
QVariant calculate(Aggregate aggregate, const QString &fieldOrExpression, QgsExpressionContext *context=nullptr, bool *ok=nullptr) const
Calculates the value of an aggregate.
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
void committedAttributeValuesChanges(const QString &layerId, const QgsChangedAttributesMap &changedAttributesValues)
static QgsFeatureRenderer * loadSld(const QDomNode &node, QgsWkbTypes::GeometryType geomType, QString &errorMessage)
Create a new renderer according to the information contained in the UserStyle element of a SLD style ...
Container for settings relating to a text buffer.
virtual void reloadData()
Reloads the data from the source.
void beforeModifiedCheck() const
Is emitted, when layer is checked for modifications. Use for last-minute additions.
void setAllowCommit(bool allowCommit)
Controls, if the layer is allowed to commit changes.
bool deleteSelectedFeatures(int *deletedCount=nullptr)
Deletes the selected features.
QVariant defaultValue(int index, const QgsFeature &feature=QgsFeature(), QgsExpressionContext *context=nullptr) const
Returns the calculated default value for the specified field index.
Edit operation was successful.
virtual QList< QgsDiagramSettings > diagramSettings() const =0
Returns list with all diagram settings in the renderer.
The QgsConditionalLayerStyles class holds conditional style information for a layer.
bool moveVertex(double x, double y, QgsFeatureId atFeatureId, int atVertex)
Moves the vertex at the given position number, ring and item (first number is index 0)...
void updateFields(QgsFields &fields)
Updates field map with joined attributes.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
QgsAuxiliaryLayer * createAuxiliaryLayer(const QgsField &field, QgsVectorLayer *layer) const
Creates an auxiliary layer for a vector layer.
void committedAttributesAdded(const QString &layerId, const QList< QgsField > &addedAttributes)
This signal is emitted, when attributes are added to the provider.
void readXml(const QDomNode &layer_node)
Reads expressions from project file.
static QgsProject * instance()
Returns the QgsProject singleton instance.
virtual QString loadNamedStyle(const QString &uri, bool &resultFlag, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Retrieve a named style for this layer if one exists (either as a .qml file on disk or as a record in ...
virtual QString subsetString() const
Returns the string (typically sql) used to define a subset of the layer.
void removeExpression(int index)
Remove an expression from the buffer.
This class represents a coordinate reference system (CRS).
QList< QgsExpressionFieldBuffer::ExpressionField > expressions() const
virtual QVariant defaultValue(int fieldIndex) const
Returns any literal default values which are present at the provider for a specified field index...
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
friend class QgsVectorLayerEditBuffer
Abstract base class - its implementations define different approaches to the labeling of a vector lay...
int size() const
Returns number of items.
SimplifyHints simplifyHints() const
Gets the simplification hints of the vector layer managed.
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
void removeFieldAlias(int index)
Removes an alias (a display name) for attributes to display in dialogs.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=nullptr) FINAL
Adds a single feature to the sink.
FieldOrigin fieldOrigin(int fieldIdx) const
Gets field's origin (value from an enumeration)
QString authid() const
Returns the authority identifier for the CRS.
static QString displayString(Type type)
Returns a display string type for a WKB type, e.g., the geometry name used in WKT geometry representa...
bool deleteFeatures(const QgsFeatureIds &fids) const
Deletes a list of features from joined layers.
const QgsExpressionNode * rootNode() const
Returns root node of the expression. Root node is null is parsing has failed.
virtual bool setSubsetString(const QString &subset)
Set the string (typically sql) used to define a subset of the layer.
QgsVectorLayer::EditResult deleteVertex(QgsFeatureId featureId, int vertex)
Deletes a vertex from a feature.
void setDefaultValueDefinition(int index, const QgsDefaultValue &definition)
Sets the definition of the expression to use when calculating the default value for a field...
const QgsPathResolver & pathResolver() const
Returns path resolver for conversion between relative and absolute paths.
virtual QString getStyleFromDatabase(const QString &styleId, QString &msgError)
Will return the named style corresponding to style id provided.
virtual bool deleteFeature(QgsFeatureId fid)
Delete a feature from the layer (but does not commit it)
virtual bool enterUpdateMode()
Enter update mode.
void setSimplifyMethod(const QgsVectorSimplifyMethod &simplifyMethod)
Set the simplification settings for fast rendering of features.
friend class QgsVectorLayerEditPassthrough
Basic implementation of the labeling interface.
T enumValue(const QString &key, const T &defaultValue, const Section section=NoSection)
Returns the setting value for a setting based on an enum.
virtual bool empty() const
Returns true if the layer contains at least one feature.
void dataChanged()
Data of layer changed.
void joinedFieldsChanged()
Emitted whenever the list of joined fields changes (e.g.
static QColor colorFromOgcFill(const QDomElement &fillElement)
Parse XML with OGC fill into QColor.
virtual bool changeAttributeValue(QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue=QVariant())
Changed an attribute value (but does not commit it)
A grouped map of multiple QgsProperty objects, each referenced by a integer key value.
Base class for utility classes that encapsulate information necessary for rendering of map layers...
bool hasParam(const QString &key) const
Test if param exists (generic mode)
virtual QgsFeatureRenderer * createRenderer(const QVariantMap &configuration=QVariantMap()) const
Creates a new vector layer feature renderer, using provider backend specific information.
void setConstraintExpression(int index, const QString &expression, const QString &description=QString())
Set the constraint expression for the specified field index.
QString sourceName() const FINAL
Returns a friendly display name for the source.
void setBuffer(const QgsTextBufferSettings &bufferSettings)
Sets the text's buffer settings.
Allows deletion of features.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Query the layer for features specified in request.
bool isExpression
True if this label is made from a expression string, e.g., FieldName || 'mm'.
QgsCoordinateReferenceSystem sourceCrs() const FINAL
Returns the coordinate reference system for features in the source.
virtual void exportNamedStyle(QDomDocument &doc, QString &errorMsg, const QgsReadWriteContext &context=QgsReadWriteContext(), QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories) const
Export the properties of this layer as named style in a QDomDocument.
QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
virtual QgsRectangle extent() const =0
Returns the extent of the layer.
QString description() const
Returns the descriptive name of the CRS, e.g., "WGS 84" or "GDA 94 / Vicgrid94".
FeatureAvailability hasFeatures() const FINAL
Determines if this vector layer has features.
bool changeAttributeValue(QgsFeatureId fid, int field, const QVariant &newValue, const QVariant &oldValue=QVariant(), bool skipDefaultValues=false)
Changes an attribute value for a feature (but does not immediately commit the changes).
QString dataComment() const
Returns a description for this layer as defined in the data provider.
QgsCoordinateReferenceSystem crs() const
Returns the layer's spatial reference system.
Edit failed due to invalid layer.
bool writeXml(QDomNode &node, QDomDocument &doc, const QgsReadWriteContext &context) const
Write field ui properties specific state from Dom node.
QUndoStack * undoStack()
Returns pointer to layer's undo stack.
virtual QString subsetString() const
Returns the subset definition string (typically sql) currently in use by the layer and used by the pr...
void committedFeaturesRemoved(const QString &layerId, const QgsFeatureIds &deletedFeatureIds)
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider.
QList< int > QgsAttributeList
bool equals(const QgsGeometry &geometry) const
Test if this geometry is exactly equal to another geometry.
QMap< QgsFieldConstraints::Constraint, QgsFieldConstraints::ConstraintStrength > fieldConstraintsAndStrength(int fieldIndex) const
Returns a map of constraint with their strength for a specific field of the layer.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
void committedFeaturesAdded(const QString &layerId, const QgsFeatureList &addedFeatures)
void normalize()
Normalize the rectangle so it has non-negative width/height.
virtual bool deleteStyleFromDatabase(const QString &styleId, QString &msgError)
Delete a style from the database.
float maximumScale() const
Gets the maximum scale at which the layer should be simplified.
bool nextFeature(QgsFeature &f)
This is a container for configuration of the attribute table.
void setCoordinateSystem()
Setup the coordinate system transformation for the layer.
This is the base class for vector data providers.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
void attributeDeleted(int idx)
Will be emitted, when an attribute has been deleted from this vector layer.
Container for all settings relating to text rendering.
bool isValid() const
Returns the status of the auxiliary storage currently defined.
static QgsFeatureRenderer * defaultRenderer(QgsWkbTypes::GeometryType geomType)
Returns a new renderer - used by default in vector layers.
bool changeAttributeValues(QgsFeatureId fid, const QgsAttributeMap &newValues, const QgsAttributeMap &oldValues=QgsAttributeMap(), bool skipDefaultValues=false)
Changes attributes' values for a feature (but does not immediately commit the changes).
Geometry is not required. It may still be returned if e.g. required for a filter condition.
bool writeSld(QDomNode &node, QDomDocument &doc, QString &errorMessage, const QgsStringMap &props=QgsStringMap()) const
Writes the symbology of the layer into the document provided in SLD 1.1 format.
void setEditFormConfig(const QgsEditFormConfig &editFormConfig)
Set the editFormConfig (configuration) of the form used to represent this vector layer.
virtual bool hasMetadata() const
Returns true if the data source has metadata, false otherwise.
void setLegend(QgsMapLayerLegend *legend)
Assign a legend controller to the map layer.
Class for storing the component parts of a PostgreSQL/RDBMS datasource URI.
QgsFeatureMap mAddedFeatures
New features which are not committed.
double width() const
Returns the width of the rectangle.
void committedGeometriesChanges(const QString &layerId, const QgsGeometryMap &changedGeometries)
This signal is emitted, when geometry changes are saved to the provider.
This class models dependencies with or between map layers.
ConstraintOrigin constraintOrigin(Constraint constraint) const
Returns the origin of a field constraint, or ConstraintOriginNotSet if the constraint is not present ...
QString createSavepoint(QString &error)
creates a save point returns empty string on error returns the last created savepoint if it's not dir...
void updateFields(QgsFields &fields)
QVariant maximumValue(int index) const FINAL
Returns the maximum value for an attribute column or an invalid variant in case of error...
void layerModified()
This signal is emitted when modifications has been done on layer.
Represents a vector layer which manages a vector based data sets.
bool isEmpty() const
Checks whether the container is empty.
QgsFeatureList selectedFeatures() const
Returns a copy of the user-selected features.
bool addAttribute(const QgsField &field)
Add an attribute field (but does not commit it) returns true if the field was added.
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
QString htmlMetadata() const FINAL
Obtain a formatted HTML string containing assorted metadata for this layer.
QgsAttributeTableConfig attributeTableConfig() const
Returns the attribute table configuration object.
virtual bool isModified() const
Returns true if the provider has been modified since the last commit.
virtual void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Reads configuration from a DOM element previously written by writeXml()
QString constraintExpression(int index) const
Returns the constraint expression for for a specified field index, if set.
QgsWkbTypes::GeometryType type() const
Returns type of the geometry as a QgsWkbTypes::GeometryType.
Field is calculated from an expression.
void updatedFields()
Is emitted, whenever the fields available from this layer have been changed.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
void updateExpressionField(int index, const QString &exp)
Changes the expression used to define an expression based (virtual) field.
EditResult
Result of an edit operation.
QString attributeAlias(int index) const
Returns the alias of an attribute name or a null string if there is no alias.
void setAttributeTableConfig(const QgsAttributeTableConfig &attributeTableConfig)
Set the attribute table configuration object.
void layerModified()
This signal is emitted when modifications has been done on layer.
QgsAttributeList mDeletedAttributeIds
Deleted attributes fields which are not committed. The list is kept sorted.
QString evalErrorString() const
Returns evaluation error.
static QgsRectangle readRectangle(const QDomElement &element)
QMap< QString, QgsMapLayer * > mapLayers() const
Returns a map of all registered layers by layer ID.
void setColor(const QColor &color)
Sets the color for the buffer.
void featureDeleted(QgsFeatureId fid)
static QDomElement writeVariant(const QVariant &value, QDomDocument &doc)
Write a QVariant to a QDomElement.
QgsDefaultValue defaultValueDefinition
QgsVectorLayerJoinInfo joinInfo() const
Returns information to use for joining with primary key and so on.
void set(const QgsPointXY &p1, const QgsPointXY &p2)
Sets the rectangle from two QgsPoints.
void setDatabase(const QString &database)
Sets database.
QgsStringMap attributeAliases() const
Returns a map of field name to attribute alias.
void resolveReferences(QgsProject *project)
Resolves layer IDs of joined layers using given project's available layers.
static QgsAbstractVectorLayerLabeling * create(const QDomElement &element, const QgsReadWriteContext &context)
Try to create instance of an implementation based on the XML data.
QgsVectorLayer * clone() const override
Returns a new instance equivalent to this one.
void readXml(const QDomNode &node)
Deserialize to XML on layer load.
Aggregate
Available aggregates to calculate.
virtual bool leaveUpdateMode()
Leave update mode.
void setFlags(QgsMapLayer::LayerFlags flags)
Returns the flags for this layer.
double height() const
Returns the height of the rectangle.
void readCommonStyle(const QDomElement &layerElement, const QgsReadWriteContext &context, StyleCategories categories=AllStyleCategories)
Read style data common to all layer types.
QString username() const
Returns the username.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
bool readXml(const QDomNode &layer_node, QgsReadWriteContext &context) FINAL
Reads vector layer specific state from project file Dom node.
void setReadExtentFromXml(bool readExtentFromXml)
Flag allowing to indicate if the extent has to be read from the XML document when data source has no ...
virtual QString loadNamedStyle(const QString &theURI, bool &resultFlag, bool loadFromLocalDb, QgsMapLayer::StyleCategories categories=QgsMapLayer::AllStyleCategories)
Load a named style from file/local db/datasource db.
A bundle of parameters controlling aggregate calculation.
QString loadDefaultStyle(bool &resultFlag) FINAL
Retrieve the default style for this layer if one exists (either as a .qml file on disk or as a record...
virtual void saveStyleToDatabase(const QString &name, const QString &description, bool useAsDefault, const QString &uiFileContent, QString &msgError)
Save named and sld style of the layer to the style table in the db.
QString password() const
Returns the password.
SimplifyAlgorithm simplifyAlgorithm() const
Gets the local simplification algorithm of the vector layer managed.
void setThreshold(float threshold)
Sets the simplification threshold of the vector layer managed.
bool saveStyle_t(const QString &uri, const QString &qmlStyle, const QString &sldStyle, const QString &styleName, const QString &styleDescription, const QString &uiFileContent, bool useAsDefault, QString &errCause)
QString fieldName
Name of field (or an expression) to use for label text.
Field must have a unique value.
QString storageType() const
Returns the permanent storage type for this layer as a friendly name.
int listStyles_t(const QString &uri, QStringList &ids, QStringList &names, QStringList &descriptions, QString &errCause)
bool isValid() const
Returns if this default value should be applied.
void setOpacity(double opacity)
Sets the opacity for the vector layer, where opacity is a value between 0 (totally transparent) and 1...