QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgscategorizedsymbolrenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgscategorizedsymbolrenderer.cpp
3 ---------------------
4 begin : November 2009
5 copyright : (C) 2009 by Martin Dobias
6 email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
16
17#include <algorithm>
18#include <memory>
19
20#include "qgsapplication.h"
21#include "qgscolorramp.h"
22#include "qgscolorrampimpl.h"
27#include "qgsfeature.h"
28#include "qgsfieldformatter.h"
32#include "qgslogger.h"
33#include "qgsmarkersymbol.h"
34#include "qgspainteffect.h"
36#include "qgsproperty.h"
38#include "qgssldexportcontext.h"
39#include "qgsstyle.h"
41#include "qgssymbol.h"
42#include "qgssymbollayer.h"
43#include "qgssymbollayerutils.h"
44#include "qgsvariantutils.h"
45#include "qgsvectorlayer.h"
46
47#include <QDomDocument>
48#include <QDomElement>
49#include <QRegularExpression>
50#include <QSettings>
51#include <QString>
52#include <QUuid>
53
54using namespace Qt::StringLiterals;
55
56QgsRendererCategory::QgsRendererCategory( const QVariant &value, QgsSymbol *symbol, const QString &label, bool render, const QString &uuid )
57 : mValue( value )
58 , mSymbol( symbol )
59 , mLabel( label )
60 , mRender( render )
61{
62 mUuid = !uuid.isEmpty() ? uuid : QUuid::createUuid().toString();
63}
64
66 : mValue( cat.mValue )
67 , mSymbol( cat.mSymbol ? cat.mSymbol->clone() : nullptr )
68 , mLabel( cat.mLabel )
69 , mRender( cat.mRender )
70 , mUuid( cat.mUuid )
71{}
72
74{
75 if ( &cat == this )
76 return *this;
77
78 mValue = cat.mValue;
79 mSymbol.reset( cat.mSymbol ? cat.mSymbol->clone() : nullptr );
80 mLabel = cat.mLabel;
81 mRender = cat.mRender;
82 mUuid = cat.mUuid;
83 return *this;
84}
85
87
89{
90 return mUuid;
91}
92
94{
95 return mValue;
96}
97
99{
100 return mSymbol.get();
101}
102
104{
105 return mLabel;
106}
107
109{
110 return mRender;
111}
112
114{
115 mValue = value;
116}
117
119{
120 if ( mSymbol.get() != s )
121 mSymbol.reset( s );
122}
123
125{
126 mLabel = label;
127}
128
130{
131 mRender = render;
132}
133
135{
136 return u"%1::%2::%3:%4\n"_s.arg( mValue.toString(), mLabel, mSymbol->dump() ).arg( mRender );
137}
138
139void QgsRendererCategory::toSld( QDomDocument &doc, QDomElement &element, QVariantMap props ) const
140{
141 if ( !mSymbol.get() || props.value( u"attribute"_s, QString() ).toString().isEmpty() )
142 return;
143
144 QString attrName = props[u"attribute"_s].toString();
145
146 QgsSldExportContext context;
147 context.setExtraProperties( props );
148 toSld( doc, element, attrName, context );
149}
150
151bool QgsRendererCategory::toSld( QDomDocument &doc, QDomElement &element, const QString &classAttribute, QgsSldExportContext &context ) const
152{
153 if ( !mSymbol.get() || classAttribute.isEmpty() )
154 return false;
155
156 QString attrName = classAttribute;
157
158 // try to determine if attribute name is actually a field reference or expression.
159 // If it's a field reference, we need to quote it.
160 // Because we don't have access to the layer or fields here, we treat a parser error
161 // as just an unquoted field name (eg a field name with spaces)
162 const QgsExpression attrExpression = QgsExpression( attrName );
163 if ( attrExpression.hasParserError() )
164 {
165 attrName = QgsExpression::quotedColumnRef( attrName );
166 }
167 else if ( attrExpression.isField() )
168 {
169 attrName = QgsExpression::quotedColumnRef( qgis::down_cast<const QgsExpressionNodeColumnRef *>( attrExpression.rootNode() )->name() );
170 }
171
172 QDomElement ruleElem = doc.createElement( u"se:Rule"_s );
173
174 QDomElement nameElem = doc.createElement( u"se:Name"_s );
175 nameElem.appendChild( doc.createTextNode( mLabel ) );
176 ruleElem.appendChild( nameElem );
177
178 QDomElement descrElem = doc.createElement( u"se:Description"_s );
179 QDomElement titleElem = doc.createElement( u"se:Title"_s );
180 QString descrStr = u"%1 is '%2'"_s.arg( attrName, mValue.toString() );
181 titleElem.appendChild( doc.createTextNode( !mLabel.isEmpty() ? mLabel : descrStr ) );
182 descrElem.appendChild( titleElem );
183 ruleElem.appendChild( descrElem );
184
185 // create the ogc:Filter for the range
186 QString filterFunc;
187 if ( mValue.userType() == QMetaType::Type::QVariantList )
188 {
189 const QVariantList list = mValue.toList();
190 if ( list.size() == 1 )
191 {
192 filterFunc = u"%1 = %2"_s.arg( attrName, QgsExpression::quotedValue( list.at( 0 ) ) );
193 }
194 else
195 {
196 QStringList valuesList;
197 valuesList.reserve( list.size() );
198 for ( const QVariant &v : list )
199 {
200 valuesList << QgsExpression::quotedValue( v );
201 }
202 filterFunc = u"%1 IN (%2)"_s.arg( attrName, valuesList.join( ',' ) );
203 }
204 }
205 else if ( QgsVariantUtils::isNull( mValue ) || mValue.toString().isEmpty() )
206 {
207 filterFunc = u"ELSE"_s;
208 }
209 else
210 {
211 filterFunc = u"%1 = %2"_s.arg( attrName, QgsExpression::quotedValue( mValue ) );
212 }
213
214 QgsSymbolLayerUtils::createFunctionElement( doc, ruleElem, filterFunc, context );
215
216 // add the mix/max scale denoms if we got any from the callers
217 const QVariantMap oldProps = context.extraProperties();
218 QVariantMap props = oldProps;
219 QgsSymbolLayerUtils::applyScaleDependency( doc, ruleElem, props );
220 context.setExtraProperties( props );
221 mSymbol->toSld( doc, ruleElem, context );
222 context.setExtraProperties( oldProps );
223 if ( !QgsSymbolLayerUtils::hasSldSymbolizer( ruleElem ) )
224 {
225 // symbol could not be converted to SLD, or is an "empty" symbol. In this case we do not generate a rule, as
226 // SLD spec requires a Symbolizer element to be present
227 return false;
228 }
229
230 element.appendChild( ruleElem );
231 return true;
232}
233
235
237 : QgsFeatureRenderer( u"categorizedSymbol"_s )
238 , mAttrName( attrName )
239{
240 //important - we need a deep copy of the categories list, not a shared copy. This is required because
241 //QgsRendererCategory::symbol() is marked const, and so retrieving the symbol via this method does not
242 //trigger a detachment and copy of mCategories BUT that same method CAN be used to modify a symbol in place
243 for ( const QgsRendererCategory &cat : categories )
244 {
245 if ( !cat.symbol() )
246 {
247 QgsDebugError( u"invalid symbol in a category! ignoring..."_s );
248 }
249 mCategories << cat;
250 }
251}
252
254{
256 QgsCategoryList::const_iterator catIt = mCategories.constBegin();
257 for ( ; catIt != mCategories.constEnd(); ++catIt )
258 {
259 if ( QgsSymbol *catSymbol = catIt->symbol() )
260 {
261 if ( catSymbol->flags().testFlag( Qgis::SymbolFlag::AffectsLabeling ) )
263 }
264 }
265
266 return res;
267}
268
270
272{
273 mSymbolHash.clear();
274
275 for ( const QgsRendererCategory &cat : std::as_const( mCategories ) )
276 {
277 const QVariant val = cat.value();
278 if ( val.userType() == QMetaType::Type::QVariantList )
279 {
280 const QVariantList list = val.toList();
281 for ( const QVariant &v : list )
282 {
283 mSymbolHash.insert( v.toString(), ( cat.renderState() || mCounting ) ? cat.symbol() : nullptr );
284 }
285 }
286 else
287 {
288 mSymbolHash.insert( val.toString(), ( cat.renderState() || mCounting ) ? cat.symbol() : nullptr );
289 }
290 }
291}
292
297
299{
300 bool found = false;
301 return symbolForValue( value, found );
302}
303
304QgsSymbol *QgsCategorizedSymbolRenderer::symbolForValue( const QVariant &value, bool &foundMatchingSymbol ) const
305{
306 foundMatchingSymbol = false;
307
308 // TODO: special case for int, double
309 QHash<QString, QgsSymbol *>::const_iterator it = mSymbolHash.constFind( QgsVariantUtils::isNull( value ) ? QString() : value.toString() );
310 if ( it == mSymbolHash.constEnd() )
311 {
312 if ( mSymbolHash.isEmpty() )
313 {
314 QgsDebugError( u"there are no hashed symbols!!!"_s );
315 }
316 else
317 {
318 QgsDebugMsgLevel( "attribute value not found: " + value.toString(), 3 );
319 }
320 return nullptr;
321 }
322
323 foundMatchingSymbol = true;
324
325 return *it;
326}
327
329{
330 return originalSymbolForFeature( feature, context );
331}
332
333QVariant QgsCategorizedSymbolRenderer::valueForFeature( const QgsFeature &feature, QgsRenderContext &context ) const
334{
335 QgsAttributes attrs = feature.attributes();
336 QVariant value;
337 if ( mAttrNum == -1 )
338 {
339 Q_ASSERT( mExpression );
340
341 value = mExpression->evaluate( &context.expressionContext() );
342 }
343 else
344 {
345 value = attrs.value( mAttrNum );
346 }
347
348 return value;
349}
350
352{
353 QVariant value = valueForFeature( feature, context );
354
355 bool foundCategory = false;
356 // find the right symbol for the category
357 QgsSymbol *symbol = symbolForValue( value, foundCategory );
358
359 if ( !foundCategory )
360 {
361 // if no symbol found, use default symbol
362 return symbolForValue( QVariant( "" ), foundCategory );
363 }
364
365 return symbol;
366}
367
368
370{
371 for ( int i = 0; i < mCategories.count(); i++ )
372 {
373 if ( mCategories[i].value() == val )
374 return i;
375 }
376 return -1;
377}
378
380{
381 int idx = -1;
382 for ( int i = 0; i < mCategories.count(); i++ )
383 {
384 if ( mCategories[i].label() == val )
385 {
386 if ( idx != -1 )
387 return -1;
388 else
389 idx = i;
390 }
391 }
392 return idx;
393}
394
395bool QgsCategorizedSymbolRenderer::updateCategoryValue( int catIndex, const QVariant &value )
396{
397 if ( catIndex < 0 || catIndex >= mCategories.size() )
398 return false;
399 mCategories[catIndex].setValue( value );
400 return true;
401}
402
404{
405 if ( catIndex < 0 || catIndex >= mCategories.size() )
406 return false;
407 mCategories[catIndex].setSymbol( symbol );
408 return true;
409}
410
411bool QgsCategorizedSymbolRenderer::updateCategoryLabel( int catIndex, const QString &label )
412{
413 if ( catIndex < 0 || catIndex >= mCategories.size() )
414 return false;
415 mCategories[catIndex].setLabel( label );
416 return true;
417}
418
420{
421 if ( catIndex < 0 || catIndex >= mCategories.size() )
422 return false;
423 mCategories[catIndex].setRenderState( render );
424 return true;
425}
426
428{
429 if ( !cat.symbol() )
430 {
431 QgsDebugError( u"invalid symbol in a category! ignoring..."_s );
432 return;
433 }
434
435 mCategories.append( cat );
436}
437
439{
440 if ( catIndex < 0 || catIndex >= mCategories.size() )
441 return false;
442
443 mCategories.removeAt( catIndex );
444 return true;
445}
446
451
453{
454 if ( from < 0 || from >= mCategories.size() || to < 0 || to >= mCategories.size() )
455 return;
456 mCategories.move( from, to );
457}
458
460{
461 return qgsVariantLessThan( c1.value(), c2.value() );
462}
464{
465 return qgsVariantGreaterThan( c1.value(), c2.value() );
466}
467
469{
470 if ( order == Qt::AscendingOrder )
471 {
472 std::sort( mCategories.begin(), mCategories.end(), valueLessThan );
473 }
474 else
475 {
476 std::sort( mCategories.begin(), mCategories.end(), valueGreaterThan );
477 }
478}
479
481{
482 return QString::localeAwareCompare( c1.label(), c2.label() ) < 0;
483}
484
486{
487 return QString::localeAwareCompare( c1.label(), c2.label() ) > 0;
488}
489
491{
492 if ( order == Qt::AscendingOrder )
493 {
494 std::sort( mCategories.begin(), mCategories.end(), labelLessThan );
495 }
496 else
497 {
498 std::sort( mCategories.begin(), mCategories.end(), labelGreaterThan );
499 }
500}
501
503{
504 QgsFeatureRenderer::startRender( context, fields );
505
506 mCounting = context.rendererScale() == 0.0;
507
508 // make sure that the hash table is up to date
509 rebuildHash();
510
511 // find out classification attribute index from name
512 mAttrNum = fields.lookupField( mAttrName );
513 if ( mAttrNum == -1 )
514 {
515 mExpression = std::make_unique<QgsExpression>( mAttrName );
516 mExpression->prepare( &context.expressionContext() );
517 }
518
519 for ( const QgsRendererCategory &cat : std::as_const( mCategories ) )
520 {
521 cat.symbol()->startRender( context, fields );
522 }
523}
524
526{
528
529 for ( const QgsRendererCategory &cat : std::as_const( mCategories ) )
530 {
531 cat.symbol()->stopRender( context );
532 }
533 mExpression.reset();
534}
535
537{
538 QSet<QString> attributes;
539
540 // mAttrName can contain either attribute name or an expression.
541 // Sometimes it is not possible to distinguish between those two,
542 // e.g. "a - b" can be both a valid attribute name or expression.
543 // Since we do not have access to fields here, try both options.
544 attributes << mAttrName;
545
546 QgsExpression testExpr( mAttrName );
547 if ( !testExpr.hasParserError() )
548 attributes.unite( testExpr.referencedColumns() );
549
550 QgsCategoryList::const_iterator catIt = mCategories.constBegin();
551 for ( ; catIt != mCategories.constEnd(); ++catIt )
552 {
553 QgsSymbol *catSymbol = catIt->symbol();
554 if ( catSymbol )
555 {
556 attributes.unite( catSymbol->usedAttributes( context ) );
557 }
558 }
559 return attributes;
560}
561
563{
564 QgsExpression testExpr( mAttrName );
565 if ( !testExpr.hasParserError() )
566 {
567 QgsExpressionContext context;
568 context.appendScopes( QgsExpressionContextUtils::globalProjectLayerScopes( nullptr ) ); // unfortunately no layer access available!
569 testExpr.prepare( &context );
570 return testExpr.needsGeometry();
571 }
572 return false;
573}
574
576{
577 QString s = u"CATEGORIZED: idx %1\n"_s.arg( mAttrName );
578 for ( int i = 0; i < mCategories.count(); i++ )
579 s += mCategories[i].dump();
580 return s;
581}
582
597
598void QgsCategorizedSymbolRenderer::toSld( QDomDocument &doc, QDomElement &element, const QVariantMap &props ) const
599{
600 QgsSldExportContext context;
601 context.setExtraProperties( props );
602 toSld( doc, element, context );
603}
604
605bool QgsCategorizedSymbolRenderer::toSld( QDomDocument &doc, QDomElement &element, QgsSldExportContext &context ) const
606{
607 const QVariantMap oldProps = context.extraProperties();
608 QVariantMap newProps = oldProps;
609 newProps[u"attribute"_s] = mAttrName;
610 context.setExtraProperties( newProps );
611
612 // create a Rule for each range
613 bool result = true;
614 for ( QgsCategoryList::const_iterator it = mCategories.constBegin(); it != mCategories.constEnd(); ++it )
615 {
616 if ( !it->toSld( doc, element, mAttrName, context ) )
617 result = false;
618 }
619 context.setExtraProperties( oldProps );
620 return result;
621}
622
624{
625 int attrNum = fields.lookupField( mAttrName );
626 bool isExpression = ( attrNum == -1 );
627
628 bool hasDefault = false;
629 bool defaultActive = false;
630 bool allActive = true;
631 bool noneActive = true;
632
633 //we need to build lists of both inactive and active values, as either list may be required
634 //depending on whether the default category is active or not
635 QString activeValues;
636 QString inactiveValues;
637
638 for ( const QgsRendererCategory &cat : std::as_const( mCategories ) )
639 {
640 if ( cat.value() == "" || QgsVariantUtils::isNull( cat.value() ) )
641 {
642 hasDefault = true;
643 defaultActive = cat.renderState();
644 }
645
646 noneActive = noneActive && !cat.renderState();
647 allActive = allActive && cat.renderState();
648
649 const bool isList = cat.value().userType() == QMetaType::Type::QVariantList;
650 QString value = QgsExpression::quotedValue( cat.value(), static_cast<QMetaType::Type>( cat.value().userType() ) );
651
652 if ( !cat.renderState() )
653 {
654 if ( value != "" )
655 {
656 if ( isList )
657 {
658 const QVariantList list = cat.value().toList();
659 for ( const QVariant &v : list )
660 {
661 if ( !inactiveValues.isEmpty() )
662 inactiveValues.append( ',' );
663
664 inactiveValues.append( QgsExpression::quotedValue( v, isExpression ? static_cast<QMetaType::Type>( v.userType() ) : fields.at( attrNum ).type() ) );
665 }
666 }
667 else
668 {
669 if ( !inactiveValues.isEmpty() )
670 inactiveValues.append( ',' );
671
672 inactiveValues.append( value );
673 }
674 }
675 }
676 else
677 {
678 if ( value != "" )
679 {
680 if ( isList )
681 {
682 const QVariantList list = cat.value().toList();
683 for ( const QVariant &v : list )
684 {
685 if ( !activeValues.isEmpty() )
686 activeValues.append( ',' );
687
688 activeValues.append( QgsExpression::quotedValue( v, isExpression ? static_cast<QMetaType::Type>( v.userType() ) : fields.at( attrNum ).type() ) );
689 }
690 }
691 else
692 {
693 if ( !activeValues.isEmpty() )
694 activeValues.append( ',' );
695
696 activeValues.append( value );
697 }
698 }
699 }
700 }
701
702 QString attr = isExpression ? mAttrName : u"\"%1\""_s.arg( mAttrName );
703
704 if ( allActive && hasDefault )
705 {
706 return QString();
707 }
708 else if ( noneActive )
709 {
710 return u"FALSE"_s;
711 }
712 else if ( defaultActive )
713 {
714 return u"(%1) NOT IN (%2) OR (%1) IS NULL"_s.arg( attr, inactiveValues );
715 }
716 else
717 {
718 return u"(%1) IN (%2)"_s.arg( attr, activeValues );
719 }
720}
721
723{
724 Q_UNUSED( context )
725 QgsSymbolList lst;
726 lst.reserve( mCategories.count() );
727 for ( const QgsRendererCategory &cat : mCategories )
728 {
729 lst.append( cat.symbol() );
730 }
731 return lst;
732}
733
735{
736 for ( const QgsRendererCategory &cat : mCategories )
737 {
738 QgsStyleSymbolEntity entity( cat.symbol() );
739 if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity, cat.value().toString(), cat.label() ) ) )
740 return false;
741 }
742
743 if ( mSourceColorRamp )
744 {
746 if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity ) ) )
747 return false;
748 }
749
750 return true;
751}
752
754{
755 QDomElement symbolsElem = element.firstChildElement( u"symbols"_s );
756 if ( symbolsElem.isNull() )
757 return nullptr;
758
759 QDomElement catsElem = element.firstChildElement( u"categories"_s );
760 if ( catsElem.isNull() )
761 return nullptr;
762
763 QgsSymbolMap symbolMap = QgsSymbolLayerUtils::loadSymbols( symbolsElem, context );
764 QgsCategoryList cats;
765
766 // Value from string (long, ulong, double and string)
767 const auto valueFromString = []( const QString &value, const QString &valueType ) -> QVariant {
768 if ( valueType == "double"_L1 )
769 {
770 bool ok;
771 const auto val { value.toDouble( &ok ) };
772 if ( ok )
773 {
774 return val;
775 }
776 }
777 else if ( valueType == "ulong"_L1 )
778 {
779 bool ok;
780 const auto val { value.toULongLong( &ok ) };
781 if ( ok )
782 {
783 return val;
784 }
785 }
786 else if ( valueType == "long"_L1 )
787 {
788 bool ok;
789 const auto val { value.toLongLong( &ok ) };
790 if ( ok )
791 {
792 return val;
793 }
794 }
795 else if ( valueType == "bool"_L1 )
796 {
797 if ( value.toLower() == "false"_L1 )
798 return false;
799 if ( value.toLower() == "true"_L1 )
800 return true;
801 }
802 else if ( valueType == "NULL"_L1 )
803 {
804 // This is the default ("fallback") category
805 return QVariant();
806 }
807 return value;
808 };
809
810 QDomElement catElem = catsElem.firstChildElement();
811 int i = 0;
812 QSet<QString> usedUuids;
813 while ( !catElem.isNull() )
814 {
815 if ( catElem.tagName() == "category"_L1 )
816 {
817 QVariant value;
818 if ( catElem.hasAttribute( u"value"_s ) )
819 {
820 value = valueFromString( catElem.attribute( u"value"_s ), catElem.attribute( u"type"_s, QString() ) );
821 }
822 else
823 {
824 QVariantList values;
825 QDomElement valElem = catElem.firstChildElement();
826 while ( !valElem.isNull() )
827 {
828 if ( valElem.tagName() == "val"_L1 )
829 {
830 values << valueFromString( valElem.attribute( u"value"_s ), valElem.attribute( u"type"_s, QString() ) );
831 }
832 valElem = valElem.nextSiblingElement();
833 }
834 if ( !values.isEmpty() )
835 value = values;
836 }
837
838 QString symbolName = catElem.attribute( u"symbol"_s );
839 QString label = context.projectTranslator()->translate( u"project:layers:%1:legendsymbollabels"_s.arg( context.currentLayerId() ), catElem.attribute( u"label"_s ) );
840 QgsDebugMsgLevel( "context" + u"project:layers:%1:legendsymbollabels"_s.arg( context.currentLayerId() ) + " source " + catElem.attribute( u"label"_s ), 3 );
841
842 bool render = catElem.attribute( u"render"_s ) != "false"_L1;
843 QString uuid = catElem.attribute( u"uuid"_s, QString::number( i++ ) );
844
845 while ( usedUuids.contains( uuid ) )
846 {
847 uuid = QUuid::createUuid().toString();
848 }
849 if ( symbolMap.contains( symbolName ) )
850 {
851 QgsSymbol *symbol = symbolMap.take( symbolName );
852 cats.append( QgsRendererCategory( value, symbol, label, render, uuid ) );
853 usedUuids << uuid;
854 }
855 }
856 catElem = catElem.nextSiblingElement();
857 }
858
859 QString attrName = element.attribute( u"attr"_s );
860
862
863 // delete symbols if there are any more
865
866 // try to load source symbol (optional)
867 QDomElement sourceSymbolElem = element.firstChildElement( u"source-symbol"_s );
868 if ( !sourceSymbolElem.isNull() )
869 {
870 QgsSymbolMap sourceSymbolMap = QgsSymbolLayerUtils::loadSymbols( sourceSymbolElem, context );
871 if ( sourceSymbolMap.contains( u"0"_s ) )
872 {
873 r->setSourceSymbol( sourceSymbolMap.take( u"0"_s ) );
874 }
875 QgsSymbolLayerUtils::clearSymbolMap( sourceSymbolMap );
876 }
877
878 // try to load color ramp (optional)
879 QDomElement sourceColorRampElem = element.firstChildElement( u"colorramp"_s );
880 if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( u"name"_s ) == "[source]"_L1 )
881 {
882 r->setSourceColorRamp( QgsSymbolLayerUtils::loadColorRamp( sourceColorRampElem ).release() );
883 }
884
885 QDomElement rotationElem = element.firstChildElement( u"rotation"_s );
886 if ( !rotationElem.isNull() && !rotationElem.attribute( u"field"_s ).isEmpty() )
887 {
888 for ( const QgsRendererCategory &cat : r->mCategories )
889 {
890 convertSymbolRotation( cat.symbol(), rotationElem.attribute( u"field"_s ) );
891 }
892 if ( r->mSourceSymbol )
893 {
894 convertSymbolRotation( r->mSourceSymbol.get(), rotationElem.attribute( u"field"_s ) );
895 }
896 }
897
898 QDomElement sizeScaleElem = element.firstChildElement( u"sizescale"_s );
899 if ( !sizeScaleElem.isNull() && !sizeScaleElem.attribute( u"field"_s ).isEmpty() )
900 {
901 for ( const QgsRendererCategory &cat : r->mCategories )
902 {
903 convertSymbolSizeScale( cat.symbol(), QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( u"scalemethod"_s ) ), sizeScaleElem.attribute( u"field"_s ) );
904 }
905 if ( r->mSourceSymbol && r->mSourceSymbol->type() == Qgis::SymbolType::Marker )
906 {
907 convertSymbolSizeScale( r->mSourceSymbol.get(), QgsSymbolLayerUtils::decodeScaleMethod( sizeScaleElem.attribute( u"scalemethod"_s ) ), sizeScaleElem.attribute( u"field"_s ) );
908 }
909 }
910
911 QDomElement ddsLegendSizeElem = element.firstChildElement( u"data-defined-size-legend"_s );
912 if ( !ddsLegendSizeElem.isNull() )
913 {
914 r->mDataDefinedSizeLegend.reset( QgsDataDefinedSizeLegend::readXml( ddsLegendSizeElem, context ) );
915 }
916
917 // TODO: symbol levels
918 return r;
919}
920
921QDomElement QgsCategorizedSymbolRenderer::save( QDomDocument &doc, const QgsReadWriteContext &context )
922{
923 // clazy:skip
924 QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME );
925 rendererElem.setAttribute( u"type"_s, u"categorizedSymbol"_s );
926 rendererElem.setAttribute( u"attr"_s, mAttrName );
927
928 // String for type
929 // We just need string, bool, and three numeric types: double, ulong and long for unsigned, signed and float/double
930 const auto stringForType = []( const QMetaType::Type type ) -> QString {
931 if ( type == QMetaType::Type::QChar || type == QMetaType::Type::Int || type == QMetaType::Type::LongLong )
932 {
933 return u"long"_s;
934 }
935 else if ( type == QMetaType::Type::UInt || type == QMetaType::Type::ULongLong )
936 {
937 return u"ulong"_s;
938 }
939 else if ( type == QMetaType::Type::Double )
940 {
941 return u"double"_s;
942 }
943 else if ( type == QMetaType::Type::Bool )
944 {
945 return u"bool"_s;
946 }
947 else // Default: string
948 {
949 return u"string"_s;
950 }
951 };
952
953 // categories
954 if ( !mCategories.isEmpty() )
955 {
956 int i = 0;
958 QDomElement catsElem = doc.createElement( u"categories"_s );
959 QgsCategoryList::const_iterator it = mCategories.constBegin();
960 for ( ; it != mCategories.constEnd(); ++it )
961 {
962 const QgsRendererCategory &cat = *it;
963 QString symbolName = QString::number( i );
964 symbols.insert( symbolName, cat.symbol() );
965
966 QDomElement catElem = doc.createElement( u"category"_s );
967 if ( cat.value().userType() == QMetaType::Type::QVariantList )
968 {
969 const QVariantList list = cat.value().toList();
970 for ( const QVariant &v : list )
971 {
972 QDomElement valueElem = doc.createElement( u"val"_s );
973 valueElem.setAttribute( u"value"_s, v.toString() );
974 valueElem.setAttribute( u"type"_s, stringForType( static_cast<QMetaType::Type>( v.userType() ) ) );
975 catElem.appendChild( valueElem );
976 }
977 }
978 else
979 {
980 if ( QgsVariantUtils::isNull( cat.value() ) )
981 {
982 // We need to save NULL value as specific kind, it is the default ("fallback") category
983 catElem.setAttribute( u"value"_s, "NULL" );
984 catElem.setAttribute( u"type"_s, "NULL" );
985 }
986 else
987 {
988 catElem.setAttribute( u"value"_s, cat.value().toString() );
989 catElem.setAttribute( u"type"_s, stringForType( static_cast<QMetaType::Type>( cat.value().userType() ) ) );
990 }
991 }
992 catElem.setAttribute( u"symbol"_s, symbolName );
993 catElem.setAttribute( u"label"_s, cat.label() );
994 catElem.setAttribute( u"render"_s, cat.renderState() ? "true" : "false" );
995 catElem.setAttribute( u"uuid"_s, cat.uuid() );
996 catsElem.appendChild( catElem );
997 i++;
998 }
999 rendererElem.appendChild( catsElem );
1000
1001 // save symbols
1002 QDomElement symbolsElem = QgsSymbolLayerUtils::saveSymbols( symbols, u"symbols"_s, doc, context );
1003 rendererElem.appendChild( symbolsElem );
1004 }
1005
1006 // save source symbol
1007 if ( mSourceSymbol )
1008 {
1009 QgsSymbolMap sourceSymbols;
1010 sourceSymbols.insert( u"0"_s, mSourceSymbol.get() );
1011 QDomElement sourceSymbolElem = QgsSymbolLayerUtils::saveSymbols( sourceSymbols, u"source-symbol"_s, doc, context );
1012 rendererElem.appendChild( sourceSymbolElem );
1013 }
1014
1015 // save source color ramp
1016 if ( mSourceColorRamp )
1017 {
1018 QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( u"[source]"_s, mSourceColorRamp.get(), doc );
1019 rendererElem.appendChild( colorRampElem );
1020 }
1021
1022 QDomElement rotationElem = doc.createElement( u"rotation"_s );
1023 rendererElem.appendChild( rotationElem );
1024
1025 QDomElement sizeScaleElem = doc.createElement( u"sizescale"_s );
1026 rendererElem.appendChild( sizeScaleElem );
1027
1029 {
1030 QDomElement ddsLegendElem = doc.createElement( u"data-defined-size-legend"_s );
1031 mDataDefinedSizeLegend->writeXml( ddsLegendElem, context );
1032 rendererElem.appendChild( ddsLegendElem );
1033 }
1034
1035 saveRendererData( doc, rendererElem, context );
1036
1037 return rendererElem;
1038}
1039
1040
1041QgsLegendSymbolList QgsCategorizedSymbolRenderer::baseLegendSymbolItems() const
1042{
1044 for ( const QgsRendererCategory &cat : mCategories )
1045 {
1046 lst << QgsLegendSymbolItem( cat.symbol(), cat.label(), cat.uuid(), true );
1047 }
1048 return lst;
1049}
1050
1051QString QgsCategorizedSymbolRenderer::displayString( const QVariant &v, int precision )
1052{
1053 return QgsVariantUtils::displayString( v, precision );
1054}
1055
1057{
1059 {
1060 // check that all symbols that have the same size expression
1061 QgsProperty ddSize;
1062 for ( const QgsRendererCategory &category : mCategories )
1063 {
1064 const QgsMarkerSymbol *symbol = static_cast<const QgsMarkerSymbol *>( category.symbol() );
1065 if ( ddSize )
1066 {
1067 QgsProperty sSize( symbol->dataDefinedSize() );
1068 if ( sSize != ddSize )
1069 {
1070 // no common size expression
1071 return baseLegendSymbolItems();
1072 }
1073 }
1074 else
1075 {
1076 ddSize = symbol->dataDefinedSize();
1077 }
1078 }
1079
1080 if ( ddSize && ddSize.isActive() )
1081 {
1083
1085 ddSizeLegend.updateFromSymbolAndProperty( static_cast<const QgsMarkerSymbol *>( mSourceSymbol.get() ), ddSize );
1086 lst += ddSizeLegend.legendSymbolList();
1087
1088 lst += baseLegendSymbolItems();
1089 return lst;
1090 }
1091 }
1092
1093 return baseLegendSymbolItems();
1094}
1095
1097{
1098 const QVariant value = valueForFeature( feature, context );
1099
1100 for ( const QgsRendererCategory &cat : mCategories )
1101 {
1102 bool match = false;
1103 if ( cat.value().userType() == QMetaType::Type::QVariantList )
1104 {
1105 const QVariantList list = cat.value().toList();
1106 for ( const QVariant &v : list )
1107 {
1108 if ( value == v )
1109 {
1110 match = true;
1111 break;
1112 }
1113 }
1114 }
1115 else
1116 {
1117 // NULL cat value may be stored as an empty string or an invalid variant, depending on how
1118 // the renderer was constructed and which QGIS version was used
1119 if ( QgsVariantUtils::isNull( value ) )
1120 {
1121 match = cat.value().toString().isEmpty() || QgsVariantUtils::isNull( cat.value() );
1122 }
1123 else
1124 {
1125 match = value == cat.value();
1126 }
1127 }
1128
1129 if ( match )
1130 {
1131 if ( cat.renderState() || mCounting )
1132 return QSet< QString >() << cat.uuid();
1133 else
1134 return QSet< QString >();
1135 }
1136 }
1137
1138 return QSet< QString >();
1139}
1140
1141QString QgsCategorizedSymbolRenderer::legendKeyToExpression( const QString &key, QgsVectorLayer *layer, bool &ok ) const
1142{
1143 ok = false;
1144 int i = 0;
1145 for ( i = 0; i < mCategories.size(); i++ )
1146 {
1147 if ( mCategories[i].uuid() == key )
1148 {
1149 ok = true;
1150 break;
1151 }
1152 }
1153
1154 if ( !ok )
1155 {
1156 ok = false;
1157 return QString();
1158 }
1159
1160 const int fieldIndex = layer ? layer->fields().lookupField( mAttrName ) : -1;
1161 const bool isNumeric = layer && fieldIndex >= 0 ? layer->fields().at( fieldIndex ).isNumeric() : false;
1162 const QMetaType::Type fieldType = layer && fieldIndex >= 0 ? layer->fields().at( fieldIndex ).type() : QMetaType::Type::UnknownType;
1163 const QString attributeComponent = QgsExpression::quoteFieldExpression( mAttrName, layer );
1164
1165 ok = true;
1166 const QgsRendererCategory &cat = mCategories[i];
1167 if ( cat.value().userType() == QMetaType::Type::QVariantList )
1168 {
1169 const QVariantList list = cat.value().toList();
1170 QStringList parts;
1171 parts.reserve( list.size() );
1172 for ( const QVariant &v : list )
1173 {
1174 parts.append( QgsExpression::quotedValue( v ) );
1175 }
1176
1177 return u"%1 IN (%2)"_s.arg( attributeComponent, parts.join( ", "_L1 ) );
1178 }
1179 else
1180 {
1181 // Numeric NULL cat value is stored as an empty string
1182 QVariant value = cat.value();
1183 if ( isNumeric && value.toString().isEmpty() )
1184 {
1185 value = QVariant();
1186 }
1187
1188 if ( QgsVariantUtils::isNull( value ) )
1189 return u"%1 IS NULL"_s.arg( attributeComponent );
1190 else if ( fieldType == QMetaType::Type::UnknownType )
1191 return u"%1 = %2"_s.arg( attributeComponent, QgsExpression::quotedValue( value ) );
1192 else
1193 return u"%1 = %2"_s.arg( attributeComponent, QgsExpression::quotedValue( value, fieldType ) );
1194 }
1195}
1196
1201
1203{
1204 return mSourceSymbol.get();
1205}
1206
1211
1216
1221
1226
1228{
1229 setSourceColorRamp( ramp );
1230 double num = mCategories.count() - 1;
1231 double count = 0;
1232
1233 QgsRandomColorRamp *randomRamp = dynamic_cast<QgsRandomColorRamp *>( ramp );
1234 if ( randomRamp )
1235 {
1236 //ramp is a random colors ramp, so inform it of the total number of required colors
1237 //this allows the ramp to pregenerate a set of visually distinctive colors
1238 randomRamp->setTotalColorCount( mCategories.count() );
1239 }
1240
1241 for ( const QgsRendererCategory &cat : mCategories )
1242 {
1243 double value = count / num;
1244 cat.symbol()->setColor( mSourceColorRamp->color( value ) );
1245 count += 1;
1246 }
1247}
1248
1250{
1251 int i = 0;
1252 for ( const QgsRendererCategory &cat : mCategories )
1253 {
1254 QgsSymbol *symbol = sym->clone();
1255 symbol->setColor( cat.symbol()->color() );
1256 updateCategorySymbol( i, symbol );
1257 ++i;
1258 }
1259 setSourceSymbol( sym->clone() );
1260}
1261
1263{
1264 return true;
1265}
1266
1268{
1269 for ( const QgsRendererCategory &category : std::as_const( mCategories ) )
1270 {
1271 if ( category.uuid() == key )
1272 {
1273 return category.renderState();
1274 }
1275 }
1276
1277 return true;
1278}
1279
1281{
1282 bool ok = false;
1283 int i = 0;
1284 for ( i = 0; i < mCategories.size(); i++ )
1285 {
1286 if ( mCategories[i].uuid() == key )
1287 {
1288 ok = true;
1289 break;
1290 }
1291 }
1292
1293 if ( ok )
1294 updateCategorySymbol( i, symbol );
1295 else
1296 delete symbol;
1297}
1298
1299void QgsCategorizedSymbolRenderer::checkLegendSymbolItem( const QString &key, bool state )
1300{
1301 for ( int i = 0; i < mCategories.size(); i++ )
1302 {
1303 if ( mCategories[i].uuid() == key )
1304 {
1305 updateCategoryRenderState( i, state );
1306 break;
1307 }
1308 }
1309}
1310
1312{
1313 std::unique_ptr< QgsCategorizedSymbolRenderer > r;
1314 if ( renderer->type() == "categorizedSymbol"_L1 )
1315 {
1316 r.reset( static_cast<QgsCategorizedSymbolRenderer *>( renderer->clone() ) );
1317 }
1318 else if ( renderer->type() == "graduatedSymbol"_L1 )
1319 {
1320 const QgsGraduatedSymbolRenderer *graduatedSymbolRenderer = dynamic_cast<const QgsGraduatedSymbolRenderer *>( renderer );
1321 if ( graduatedSymbolRenderer )
1322 {
1323 r = std::make_unique<QgsCategorizedSymbolRenderer>( QString(), QgsCategoryList() );
1324 if ( graduatedSymbolRenderer->sourceSymbol() )
1325 r->setSourceSymbol( graduatedSymbolRenderer->sourceSymbol()->clone() );
1326 if ( graduatedSymbolRenderer->sourceColorRamp() )
1327 {
1328 r->setSourceColorRamp( graduatedSymbolRenderer->sourceColorRamp()->clone() );
1329 }
1330 r->setClassAttribute( graduatedSymbolRenderer->classAttribute() );
1331 }
1332 }
1333 else if ( renderer->type() == "RuleRenderer"_L1 )
1334 {
1335 const QgsRuleBasedRenderer *ruleBasedSymbolRenderer = dynamic_cast<const QgsRuleBasedRenderer *>( renderer );
1336 if ( ruleBasedSymbolRenderer )
1337 {
1338 r = std::make_unique<QgsCategorizedSymbolRenderer>( QString(), QgsCategoryList() );
1339
1340 const QList< QgsRuleBasedRenderer::Rule * > rules = const_cast< QgsRuleBasedRenderer * >( ruleBasedSymbolRenderer )->rootRule()->children();
1341 bool canConvert = true;
1342
1343 bool isFirst = true;
1344 QString attribute;
1345 QVariant value;
1347
1348 for ( QgsRuleBasedRenderer::Rule *rule : rules )
1349 {
1350 if ( rule->isElse() || rule->minimumScale() != 0 || rule->maximumScale() != 0 || !rule->symbol() || !rule->children().isEmpty() )
1351 {
1352 canConvert = false;
1353 break;
1354 }
1355
1356 QgsExpression e( rule->filterExpression() );
1357
1358 if ( !e.rootNode() )
1359 {
1360 canConvert = false;
1361 break;
1362 }
1363
1364 if ( const QgsExpressionNodeBinaryOperator *binOp = dynamic_cast<const QgsExpressionNodeBinaryOperator *>( e.rootNode() ) )
1365 {
1366 if ( binOp->op() == QgsExpressionNodeBinaryOperator::boEQ )
1367 {
1368 const QString left = binOp->opLeft()->dump();
1369 if ( !isFirst && left != attribute )
1370 {
1371 canConvert = false;
1372 break;
1373 }
1374 else if ( isFirst )
1375 {
1376 attribute = left;
1377 }
1378
1379 const QgsExpressionNodeLiteral *literal = dynamic_cast<const QgsExpressionNodeLiteral *>( binOp->opRight() );
1380 if ( literal )
1381 {
1383 cat.setValue( literal->value() );
1384 cat.setSymbol( rule->symbol()->clone() );
1385 cat.setLabel( rule->label().isEmpty() ? literal->value().toString() : rule->label() );
1386 cat.setRenderState( rule->active() );
1387 categories.append( cat );
1388 }
1389 else
1390 {
1391 canConvert = false;
1392 break;
1393 }
1394 }
1395 else
1396 {
1397 canConvert = false;
1398 }
1399 }
1400 else
1401 {
1402 canConvert = false;
1403 break;
1404 }
1405
1406 isFirst = false;
1407 }
1408
1409 if ( canConvert )
1410 {
1411 r = std::make_unique< QgsCategorizedSymbolRenderer >( attribute, categories );
1412 }
1413 else
1414 {
1415 r.reset();
1416 }
1417 }
1418 }
1419 else if ( renderer->type() == "pointDisplacement"_L1 || renderer->type() == "pointCluster"_L1 )
1420 {
1421 const QgsPointDistanceRenderer *pointDistanceRenderer = dynamic_cast<const QgsPointDistanceRenderer *>( renderer );
1422 if ( pointDistanceRenderer )
1423 r.reset( convertFromRenderer( pointDistanceRenderer->embeddedRenderer() ) );
1424 }
1425 else if ( renderer->type() == "invertedPolygonRenderer"_L1 )
1426 {
1427 const QgsInvertedPolygonRenderer *invertedPolygonRenderer = dynamic_cast<const QgsInvertedPolygonRenderer *>( renderer );
1428 if ( invertedPolygonRenderer )
1429 r.reset( convertFromRenderer( invertedPolygonRenderer->embeddedRenderer() ) );
1430 }
1431 else if ( renderer->type() == "embeddedSymbol"_L1 && layer )
1432 {
1433 const QgsEmbeddedSymbolRenderer *embeddedRenderer = dynamic_cast<const QgsEmbeddedSymbolRenderer *>( renderer );
1437 req.setNoAttributes();
1438 QgsFeatureIterator it = layer->getFeatures( req );
1439 QgsFeature feature;
1440 while ( it.nextFeature( feature ) && categories.size() < 2000 )
1441 {
1442 if ( feature.embeddedSymbol() )
1443 categories.append( QgsRendererCategory( feature.id(), feature.embeddedSymbol()->clone(), QString::number( feature.id() ) ) );
1444 }
1445 categories.append( QgsRendererCategory( QVariant(), embeddedRenderer->defaultSymbol()->clone(), QString() ) );
1446 r = std::make_unique<QgsCategorizedSymbolRenderer>( u"$id"_s, categories );
1447 }
1448
1449 // If not one of the specifically handled renderers, then just grab the symbol from the renderer
1450 // Could have applied this to specific renderer types (singleSymbol, graduatedSymbol)
1451
1452 if ( !r )
1453 {
1454 r = std::make_unique< QgsCategorizedSymbolRenderer >( QString(), QgsCategoryList() );
1455 QgsRenderContext context;
1456 QgsSymbolList symbols = const_cast<QgsFeatureRenderer *>( renderer )->symbols( context );
1457 if ( !symbols.isEmpty() )
1458 {
1459 QgsSymbol *newSymbol = symbols.at( 0 )->clone();
1462 r->setSourceSymbol( newSymbol );
1463 }
1464 }
1465
1466 renderer->copyRendererData( r.get() );
1467
1468 return r.release();
1469}
1470
1475
1480
1482 QgsStyle *style, Qgis::SymbolType type, QVariantList &unmatchedCategories, QStringList &unmatchedSymbols, const bool caseSensitive, const bool useTolerantMatch
1483)
1484{
1485 if ( !style )
1486 return 0;
1487
1488 int matched = 0;
1489 unmatchedSymbols = style->symbolNames();
1490 const QSet< QString > allSymbolNames( unmatchedSymbols.begin(), unmatchedSymbols.end() );
1491
1492 const thread_local QRegularExpression tolerantMatchRe( u"[^\\w\\d ]"_s, QRegularExpression::UseUnicodePropertiesOption );
1493
1494 for ( int catIdx = 0; catIdx < mCategories.count(); ++catIdx )
1495 {
1496 const QVariant value = mCategories.at( catIdx ).value();
1497 const QString val = value.toString().trimmed();
1498 std::unique_ptr< QgsSymbol > symbol( style->symbol( val ) );
1499 // case-sensitive match
1500 if ( symbol && symbol->type() == type )
1501 {
1502 matched++;
1503 unmatchedSymbols.removeAll( val );
1504 updateCategorySymbol( catIdx, symbol.release() );
1505 continue;
1506 }
1507
1508 if ( !caseSensitive || useTolerantMatch )
1509 {
1510 QString testVal = val;
1511 if ( useTolerantMatch )
1512 testVal.replace( tolerantMatchRe, QString() );
1513
1514 bool foundMatch = false;
1515 for ( const QString &name : allSymbolNames )
1516 {
1517 QString testName = name.trimmed();
1518 if ( useTolerantMatch )
1519 testName.replace( tolerantMatchRe, QString() );
1520
1521 if ( testName == testVal || ( !caseSensitive && testName.trimmed().compare( testVal, Qt::CaseInsensitive ) == 0 ) )
1522 {
1523 // found a case-insensitive match
1524 std::unique_ptr< QgsSymbol > symbol( style->symbol( name ) );
1525 if ( symbol && symbol->type() == type )
1526 {
1527 matched++;
1528 unmatchedSymbols.removeAll( name );
1529 updateCategorySymbol( catIdx, symbol.release() );
1530 foundMatch = true;
1531 break;
1532 }
1533 }
1534 }
1535 if ( foundMatch )
1536 continue;
1537 }
1538
1539 unmatchedCategories << value;
1540 }
1541
1542 return matched;
1543}
1544
1545QgsCategoryList QgsCategorizedSymbolRenderer::createCategories( const QList<QVariant> &values, const QgsSymbol *symbol, QgsVectorLayer *layer, const QString &attributeName )
1546{
1547 QgsCategoryList cats;
1548 QVariantList vals = values;
1549 // sort the categories first
1550 QgsSymbolLayerUtils::sortVariantList( vals, Qt::AscendingOrder );
1551
1552 if ( layer && !attributeName.isNull() )
1553 {
1554 const QgsFields fields = layer->fields();
1555 for ( const QVariant &value : vals )
1556 {
1557 QgsSymbol *newSymbol = symbol->clone();
1559 if ( !QgsVariantUtils::isNull( value ) )
1560 {
1561 const int fieldIdx = fields.lookupField( attributeName );
1562 QString categoryName = QgsVariantUtils::displayString( value );
1563 if ( fieldIdx != -1 )
1564 {
1565 const QgsField field = fields.at( fieldIdx );
1566 const QgsEditorWidgetSetup setup = field.editorWidgetSetup();
1568 categoryName = formatter->representValue( layer, fieldIdx, setup.config(), QVariant(), value );
1569 }
1570 cats.append( QgsRendererCategory( value, newSymbol, categoryName, true ) );
1571 }
1572 }
1573 }
1574
1575 // add null (default) value
1576 QgsSymbol *newSymbol = symbol->clone();
1578 cats.append( QgsRendererCategory( QVariant(), newSymbol, QString(), true ) );
1579
1580 return cats;
1581}
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
Definition qgis.h:2276
@ EmbeddedSymbols
Retrieve any embedded feature symbology.
Definition qgis.h:2281
QFlags< FeatureRendererFlag > FeatureRendererFlags
Flags controlling behavior of vector feature renderers.
Definition qgis.h:864
@ AffectsLabeling
If present, indicates that the renderer will participate in the map labeling problem.
Definition qgis.h:855
SymbolType
Symbol types.
Definition qgis.h:636
@ Marker
Marker symbol.
Definition qgis.h:637
@ AffectsLabeling
If present, indicates that the symbol will participate in the map labeling problem.
Definition qgis.h:875
static QgsFieldFormatterRegistry * fieldFormatterRegistry()
Gets the registry of available field formatters.
A vector of attributes.
void sortByValue(Qt::SortOrder order=Qt::AscendingOrder)
Sorts the existing categories by their value.
QString filter(const QgsFields &fields=QgsFields()) override
If a renderer does not require all the features this method may be overridden and return an expressio...
QgsSymbol * symbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
To be overridden.
void updateSymbols(QgsSymbol *sym)
Update all the symbols but leave categories and colors.
bool updateCategoryRenderState(int catIndex, bool render)
Changes the render state for the category with the specified index.
void setSourceColorRamp(QgsColorRamp *ramp)
Sets the source color ramp.
void stopRender(QgsRenderContext &context) override
Must be called when a render cycle has finished, to allow the renderer to clean up.
QgsSymbol * sourceSymbol()
Returns the renderer's source symbol, which is the base symbol used for the each categories' symbol b...
const QgsCategoryList & categories() const
Returns a list of all categories recognized by the renderer.
QString legendKeyToExpression(const QString &key, QgsVectorLayer *layer, bool &ok) const override
Attempts to convert the specified legend rule key to a QGIS expression matching the features displaye...
int matchToSymbols(QgsStyle *style, Qgis::SymbolType type, QVariantList &unmatchedCategories, QStringList &unmatchedSymbols, bool caseSensitive=true, bool useTolerantMatch=false)
Replaces category symbols with the symbols from a style that have a matching name and symbol type.
std::unique_ptr< QgsColorRamp > mSourceColorRamp
Q_DECL_DEPRECATED QgsSymbol * symbolForValue(const QVariant &value) const
Returns the matching symbol corresponding to an attribute value.
std::unique_ptr< QgsSymbol > mSourceSymbol
static QgsCategorizedSymbolRenderer * convertFromRenderer(const QgsFeatureRenderer *renderer, QgsVectorLayer *layer=nullptr)
Creates a new QgsCategorizedSymbolRenderer from an existing renderer.
void updateColorRamp(QgsColorRamp *ramp)
Update the color ramp used and all symbols colors.
QgsDataDefinedSizeLegend * dataDefinedSizeLegend() const
Returns configuration of appearance of legend when using data-defined size for marker symbols.
static QgsCategoryList createCategories(const QVariantList &values, const QgsSymbol *symbol, QgsVectorLayer *layer=nullptr, const QString &fieldName=QString())
Create categories for a list of values.
QHash< QString, QgsSymbol * > mSymbolHash
hashtable for faster access to symbols
bool filterNeedsGeometry() const override
Returns true if this renderer requires the geometry to apply the filter.
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns a list of attributes required by this renderer.
void setSourceSymbol(QgsSymbol *sym)
Sets the source symbol for the renderer, which is the base symbol used for the each categories' symbo...
void startRender(QgsRenderContext &context, const QgsFields &fields) override
Must be called when a new render cycle is started.
QgsSymbolList symbols(QgsRenderContext &context) const override
Returns list of symbols used by the renderer.
int categoryIndexForValue(const QVariant &val)
Returns the index for the category with the specified value (or -1 if not found).
static QgsFeatureRenderer * create(QDomElement &element, const QgsReadWriteContext &context)
Creates a categorized renderer from an XML element.
bool updateCategorySymbol(int catIndex, QgsSymbol *symbol)
Changes the symbol for the category with the specified index.
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified symbology visitor, causing it to visit all symbols associated with the renderer...
void setLegendSymbolItem(const QString &key, QgsSymbol *symbol) override
Sets the symbol to be used for a legend symbol item.
std::unique_ptr< QgsExpression > mExpression
std::unique_ptr< QgsDataDefinedSizeLegend > mDataDefinedSizeLegend
bool legendSymbolItemChecked(const QString &key) override
Returns true if the legend symbology item with the specified key is checked.
bool legendSymbolItemsCheckable() const override
Returns true if symbology items in legend are checkable.
void addCategory(const QgsRendererCategory &category)
Adds a new category to the renderer.
QgsCategorizedSymbolRenderer(const QString &attrName=QString(), const QgsCategoryList &categories=QgsCategoryList())
Constructor for QgsCategorizedSymbolRenderer.
void sortByLabel(Qt::SortOrder order=Qt::AscendingOrder)
Sorts the existing categories by their label.
QgsSymbol * originalSymbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
Returns symbol for feature.
int mAttrNum
attribute index (derived from attribute name in startRender)
QgsLegendSymbolList legendSymbolItems() const override
Returns a list of symbology items for the legend.
void moveCategory(int from, int to)
Moves an existing category at index position from to index position to.
QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context) override
Stores renderer properties to an XML element.
bool deleteCategory(int catIndex)
Deletes the category with the specified index from the renderer.
Qgis::FeatureRendererFlags flags() const override
Returns flags associated with the renderer.
Q_DECL_DEPRECATED QgsSymbol * skipRender()
void checkLegendSymbolItem(const QString &key, bool state=true) override
Sets whether the legend symbology item with the specified ley should be checked.
QString dump() const override
Returns debug information about this renderer.
QSet< QString > legendKeysForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
Returns legend keys matching a specified feature.
QgsColorRamp * sourceColorRamp()
Returns the source color ramp, from which each categories' color is derived.
bool updateCategoryValue(int catIndex, const QVariant &value)
Changes the value for the category with the specified index.
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props=QVariantMap()) const override
Used from subclasses to create SLD Rule elements following SLD v1.1 specs.
QgsCategorizedSymbolRenderer * clone() const override
Create a deep copy of this renderer.
void deleteAllCategories()
Deletes all existing categories from the renderer.
void setDataDefinedSizeLegend(QgsDataDefinedSizeLegend *settings)
Configures appearance of legend when renderer is configured to use data-defined size for marker symbo...
bool updateCategoryLabel(int catIndex, const QString &label)
Changes the label for the category with the specified index.
static Q_DECL_DEPRECATED QString displayString(const QVariant &value, int precision=-1)
Returns a localized representation of value with the given precision, if precision is -1 then precisi...
~QgsCategorizedSymbolRenderer() override
int categoryIndexForLabel(const QString &val)
Returns the index of the category with the specified label (or -1 if the label was not found,...
Abstract base class for color ramps.
virtual QgsColorRamp * clone() const =0
Creates a clone of the color ramp.
Object that keeps configuration of appearance of marker symbol's data-defined size in legend.
static QgsDataDefinedSizeLegend * readXml(const QDomElement &elem, const QgsReadWriteContext &context) SIP_FACTORY
Creates instance from given element and returns it (caller takes ownership). Returns nullptr on error...
void updateFromSymbolAndProperty(const QgsMarkerSymbol *symbol, const QgsProperty &ddSize)
Updates the list of classes, source symbol and title label from given symbol and property.
QgsLegendSymbolList legendSymbolList() const
Generates legend symbol items according to the configuration.
Holder for the widget type and its configuration for a field.
QString type() const
Returns the widget type to use.
QVariantMap config() const
Returns the widget configuration.
A vector feature renderer which uses embedded feature symbology to render per-feature symbols.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
A binary expression operator, which operates on two values.
An expression node for literal values.
QVariant value() const
The value of the literal.
Handles parsing and evaluation of expressions (formerly called "search strings").
bool prepare(const QgsExpressionContext *context)
Gets the expression ready for evaluation - find out column indexes.
static QString quotedValue(const QVariant &value)
Returns a string representation of a literal value, including appropriate quotations where required.
static QString quoteFieldExpression(const QString &expression, const QgsVectorLayer *layer)
Validate if the expression is a field in the layer and ensure it is quoted.
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
bool isField() const
Checks whether an expression consists only of a single field reference.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
static QString quotedColumnRef(QString name)
Returns a quoted column reference (in double quotes).
const QgsExpressionNode * rootNode() const
Returns the root node of the expression.
bool needsGeometry() const
Returns true if the expression uses feature geometry for some computation.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
QgsFeatureRenderer(const QString &type)
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
QString type() const
void copyRendererData(QgsFeatureRenderer *destRenderer) const
Clones generic renderer data to another renderer.
static void convertSymbolRotation(QgsSymbol *symbol, const QString &field)
Converts old rotation expressions to symbol level data defined angles.
void saveRendererData(QDomDocument &doc, QDomElement &element, const QgsReadWriteContext &context)
Saves generic renderer data into the specified element.
virtual const QgsFeatureRenderer * embeddedRenderer() const
Returns the current embedded renderer (subrenderer) for this feature renderer.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
static void convertSymbolSizeScale(QgsSymbol *symbol, Qgis::ScaleMethod method, const QString &field)
Converts old sizeScale expressions to symbol level data defined sizes.
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsFeatureId id
Definition qgsfeature.h:68
const QgsSymbol * embeddedSymbol() const
Returns the feature's embedded symbology, or nullptr if the feature has no embedded symbol.
QgsFieldFormatter * fieldFormatter(const QString &id) const
Gets a field formatter by its id.
A field formatter helps to handle and display values for a field.
virtual QString representValue(QgsVectorLayer *layer, int fieldIndex, const QVariantMap &config, const QVariant &cache, const QVariant &value) const
Create a pretty String representation of the value.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
QMetaType::Type type
Definition qgsfield.h:63
bool isNumeric
Definition qgsfield.h:59
QgsEditorWidgetSetup editorWidgetSetup() const
Gets the editor widget setup for the field.
Definition qgsfield.cpp:739
Container of fields for a vector layer.
Definition qgsfields.h:46
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
A vector feature renderer which uses numeric attributes to classify features into different ranges.
QgsSymbol * sourceSymbol()
Returns the renderer's source symbol, which is the base symbol used for the each classes' symbol befo...
QgsColorRamp * sourceColorRamp()
Returns the source color ramp, from which each classes' color is derived.
QString classAttribute() const
Returns the attribute name (or expression) used for the classification.
A polygon-only feature renderer used to display features inverted.
Stores information about one class/rule of a vector layer renderer in a unified way that can be used ...
A marker symbol type, for rendering Point and MultiPoint geometries.
QgsProperty dataDefinedSize() const
Returns data defined size for whole symbol (including all symbol layers).
const QgsFeatureRenderer * embeddedRenderer() const override
Returns the current embedded renderer (subrenderer) for this feature renderer.
An abstract base class for distance based point renderers (e.g., clusterer and displacement renderers...
const QgsFeatureRenderer * embeddedRenderer() const override
Returns the current embedded renderer (subrenderer) for this feature renderer.
virtual QString translate(const QString &context, const QString &sourceText, const char *disambiguation=nullptr, int n=-1) const =0
Translates a string using the Qt QTranslator mechanism.
A store for object properties.
bool isActive() const
Returns whether the property is currently active.
A color ramp consisting of random colors, constrained within component ranges.
virtual void setTotalColorCount(int colorCount)
Sets the desired total number of unique colors for the resultant ramp.
A container for the context for various read/write operations on objects.
const QgsProjectTranslator * projectTranslator() const
Returns the project translator.
const QString currentLayerId() const
Returns the currently used layer id as string.
Contains information about the context of a rendering operation.
double rendererScale() const
Returns the renderer map scale.
QgsExpressionContext & expressionContext()
Gets the expression context.
Represents an individual category (class) from a QgsCategorizedSymbolRenderer.
void setRenderState(bool render)
Sets whether the category is currently enabled and should be rendered.
std::unique_ptr< QgsSymbol > mSymbol
QgsSymbol * symbol() const
Returns the symbol which will be used to render this category.
void setSymbol(QgsSymbol *s)
Sets the symbol which will be used to render this category.
QString uuid() const
Returns the unique identifier for this category.
QgsRendererCategory()=default
bool renderState() const
Returns true if the category is currently enabled and should be rendered.
QString dump() const
Returns a string representing the categories settings, used for debugging purposes only.
void setLabel(const QString &label)
Sets the label for this category, which is used to represent the category within legends and the laye...
Q_DECL_DEPRECATED void toSld(QDomDocument &doc, QDomElement &element, QVariantMap props) const
Converts the category to a matching SLD rule, within the specified DOM document and element.
void setValue(const QVariant &value)
Sets the value corresponding to this category.
QVariant value() const
Returns the value corresponding to this category.
QString label() const
Returns the label for this category, which is used to represent the category within legends and the l...
QgsRendererCategory & operator=(QgsRendererCategory cat)
Represents an individual rule for a rule-based renderer.
Rule based renderer.
Holds SLD export options and other information related to SLD export of a QGIS layer style.
void setExtraProperties(const QVariantMap &properties)
Sets the open ended set of properties that can drive/inform the SLD encoding.
QVariantMap extraProperties() const
Returns the open ended set of properties that can drive/inform the SLD encoding.
A color ramp entity for QgsStyle databases.
Definition qgsstyle.h:1422
An interface for classes which can visit style entity (e.g.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
A symbol entity for QgsStyle databases.
Definition qgsstyle.h:1393
A database of saved style entities, including symbols, color ramps, text formats and others.
Definition qgsstyle.h:89
QgsSymbol * symbol(const QString &name)
Returns a NEW copy of symbol.
Definition qgsstyle.cpp:317
QStringList symbolNames() const
Returns a list of names of symbols.
Definition qgsstyle.cpp:339
static void sortVariantList(QList< QVariant > &list, Qt::SortOrder order)
Sorts the passed list in requested order.
static void applyScaleDependency(QDomDocument &doc, QDomElement &ruleElem, QVariantMap &props)
Checks if the properties contain scaleMinDenom and scaleMaxDenom, if available, they are added into t...
static std::unique_ptr< QgsColorRamp > loadColorRamp(QDomElement &element)
Creates a color ramp from the settings encoded in an XML element.
static Q_DECL_DEPRECATED bool createFunctionElement(QDomDocument &doc, QDomElement &element, const QString &function)
Creates an OGC function element.
static bool hasSldSymbolizer(const QDomElement &element)
Returns true if a DOM element contains an SLD Symbolizer element.
static void clearSymbolLayerMasks(QgsSymbol *symbol)
Remove recursively masks from all symbol symbol layers.
static Qgis::ScaleMethod decodeScaleMethod(const QString &str)
Decodes a symbol scale method from a string.
static QDomElement saveColorRamp(const QString &name, const QgsColorRamp *ramp, QDomDocument &doc)
Encodes a color ramp's settings to an XML element.
static void clearSymbolMap(QgsSymbolMap &symbols)
static void resetSymbolLayerIds(QgsSymbol *symbol)
Regenerate recursively unique id from all symbol symbol layers.
static QgsSymbolMap loadSymbols(QDomElement &element, const QgsReadWriteContext &context)
Reads a collection of symbols from XML and returns them in a map. Caller is responsible for deleting ...
static QDomElement saveSymbols(QgsSymbolMap &symbols, const QString &tagName, QDomDocument &doc, const QgsReadWriteContext &context)
Writes a collection of symbols to XML with specified tagName for the top-level element.
Abstract base class for all rendered symbols.
Definition qgssymbol.h:227
void setColor(const QColor &color) const
Sets the color for the symbol.
QSet< QString > usedAttributes(const QgsRenderContext &context) const
Returns a list of attributes required to render this feature.
virtual QgsSymbol * clone() const =0
Returns a deep copy of this symbol.
static QString displayString(const QVariant &variant, int precision=-1)
Returns a localized representation of value with the given precision, if precision is -1 then precisi...
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
Definition qgis.cpp:596
bool qgsVariantGreaterThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is greater than the second.
Definition qgis.cpp:601
bool labelGreaterThan(const QgsRendererCategory &c1, const QgsRendererCategory &c2)
bool valueLessThan(const QgsRendererCategory &c1, const QgsRendererCategory &c2)
bool valueGreaterThan(const QgsRendererCategory &c1, const QgsRendererCategory &c2)
bool labelLessThan(const QgsRendererCategory &c1, const QgsRendererCategory &c2)
QList< QgsRendererCategory > QgsCategoryList
QList< QgsLegendSymbolItem > QgsLegendSymbolList
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
#define RENDERER_TAG_NAME
Definition qgsrenderer.h:57
QMap< QString, QgsSymbol * > QgsSymbolMap
Definition qgsrenderer.h:52
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:51
Contains information relating to the style entity currently being visited.