QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsstackedbardiagram.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsstackedbardiagram.cpp
3 ---------------------
4 begin : November 2019
5 copyright : (C) 2019 by Nyall Dawson
6 email : nyall dot dawson 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 ***************************************************************************/
15
17
18#include "qgsdiagramrenderer.h"
19#include "qgsexpression.h"
20#include "qgslinesymbol.h"
21#include "qgsrendercontext.h"
22#include "qgssymbollayerutils.h"
23
24#include <QPainter>
25
26const QString QgsStackedBarDiagram::DIAGRAM_NAME_STACKED_BAR = QStringLiteral( "Stacked" );
27
29{
30 mCategoryBrush.setStyle( Qt::SolidPattern );
31 mPen.setStyle( Qt::SolidLine );
32}
33
38
40{
41 if ( qgsDoubleNear( is.upperValue, is.lowerValue ) )
42 return QSizeF(); // invalid value range => zero size
43
44 QVariant attrVal;
46 {
47 QgsExpressionContext expressionContext = c.expressionContext();
48 if ( !feature.fields().isEmpty() )
49 expressionContext.setFields( feature.fields() );
50 expressionContext.setFeature( feature );
51
52 QgsExpression *expression = getExpression( is.classificationAttributeExpression, expressionContext );
53 attrVal = expression->evaluate( &expressionContext );
54 }
55 else
56 {
57 attrVal = feature.attribute( is.classificationField );
58 }
59
60 bool ok = false;
61 double value = fabs( attrVal.toDouble( &ok ) );
62 if ( !ok )
63 {
64 return QSizeF(); //zero size if attribute is missing
65 }
66
67 QSizeF size = sizeForValue( value, s, is );
68
69 // eh - this method returns size in unknown units ...! We'll have to fake it and use a rough estimation of
70 // a conversion factor to painter units...
71 // TODO QGIS 4.0 -- these methods should all use painter units, dependent on the render context scaling...
72 double painterUnitConversionScale = c.convertToPainterUnits( 1, s.sizeType );
73
74 const double spacing = c.convertToPainterUnits( s.spacing(), s.spacingUnit(), s.spacingMapUnitScale() ) / painterUnitConversionScale;
75 mApplySpacingAdjust = true;
76
77 switch ( s.diagramOrientation )
78 {
81 {
82 const double totalBarLength = size.height() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 );
83 size = QSizeF( s.barWidth, totalBarLength );
84 break;
85 }
86
89 {
90 const double totalBarLength = size.width() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 );
91 size = QSizeF( totalBarLength, s.barWidth );
92 break;
93 }
94 }
95
96 if ( s.showAxis() && s.axisLineSymbol() )
97 {
98 const double maxBleed = QgsSymbolLayerUtils::estimateMaxSymbolBleed( s.axisLineSymbol(), c ) / painterUnitConversionScale;
99 size.setWidth( size.width() + 2 * maxBleed );
100 size.setHeight( size.height() + 2 * maxBleed );
101 }
102
103 return size;
104}
105
107{
108 if ( qgsDoubleNear( is.upperValue, is.lowerValue ) )
109 return s.minimumSize; // invalid value range => zero size
110
111 // Scale, if extension is smaller than the specified minimum
112 if ( value < s.minimumSize )
113 {
114 value = s.minimumSize;
115 }
116
117 double scaleFactor = ( ( is.upperSize.width() - is.lowerSize.width() ) / ( is.upperValue - is.lowerValue ) );
118 return value * scaleFactor;
119}
120
125
127{
128 Q_UNUSED( c )
129 QSizeF size;
130
131 if ( attributes.isEmpty() )
132 {
133 return QSizeF(); //zero size if no attributes
134 }
135
136 // eh - this method returns size in unknown units ...! We'll have to fake it and use a rough estimation of
137 // a conversion factor to painter units...
138 // TODO QGIS 4.0 -- these methods should all use painter units, dependent on the render context scaling...
139 double painterUnitConversionScale = c.convertToPainterUnits( 1, s.sizeType );
140
141 const double spacing = c.convertToPainterUnits( s.spacing(), s.spacingUnit(), s.spacingMapUnitScale() ) / painterUnitConversionScale;
142
143 switch ( s.diagramOrientation )
144 {
147 size.scale( s.barWidth, s.size.height() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 ), Qt::IgnoreAspectRatio );
148 break;
149
152 size.scale( s.size.width() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 ), s.barWidth, Qt::IgnoreAspectRatio );
153 break;
154 }
155
156 return size;
157}
158
159void QgsStackedBarDiagram::renderDiagram( const QgsFeature &feature, QgsRenderContext &c, const QgsDiagramSettings &s, QPointF position )
160{
161 QPainter *p = c.painter();
162 if ( !p )
163 {
164 return;
165 }
166
167 QList< QPair<double, QColor> > values;
168 QList< QPair<double, QColor> > negativeValues;
169
170 QgsExpressionContext expressionContext = c.expressionContext();
171 expressionContext.setFeature( feature );
172 if ( !feature.fields().isEmpty() )
173 expressionContext.setFields( feature.fields() );
174
175 values.reserve( s.categoryAttributes.size() );
176 double total = 0;
177 double negativeTotal = 0;
178
179 QList< QColor >::const_iterator colIt = s.categoryColors.constBegin();
180 for ( const QString &cat : std::as_const( s.categoryAttributes ) )
181 {
182 QgsExpression *expression = getExpression( cat, expressionContext );
183 double currentVal = expression->evaluate( &expressionContext ).toDouble();
184 total += fabs( currentVal );
185 if ( currentVal >= 0 )
186 {
187 values.push_back( qMakePair( currentVal, *colIt ) );
188 }
189 else
190 {
191 negativeTotal += currentVal;
192 negativeValues.push_back( qMakePair( -currentVal, *colIt ) );
193 }
194 ++colIt;
195 }
196
197
198 const double spacing = c.convertToPainterUnits( s.spacing(), s.spacingUnit(), s.spacingMapUnitScale() );
199 const double totalSpacing = std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 ) * spacing;
200
201 double scaledMaxVal = 0;
202 switch ( s.diagramOrientation )
203 {
206 scaledMaxVal = sizePainterUnits( s.size.height(), s, c );
207 break;
208
211 scaledMaxVal = sizePainterUnits( s.size.width(), s, c );
212 break;
213 }
214 if ( mApplySpacingAdjust )
215 scaledMaxVal -= totalSpacing;
216
217 double axisOffset = 0;
218 if ( !negativeValues.isEmpty() )
219 {
220 axisOffset = -negativeTotal / total * scaledMaxVal + ( negativeValues.size() - 1 ) * spacing;
221 }
222 double scaledWidth = sizePainterUnits( s.barWidth, s, c );
223
224 double baseX = position.x();
225 double baseY = position.y();
226
227 if ( s.showAxis() && s.axisLineSymbol() )
228 {
229 // if showing axis, the diagram position needs shifting from the default base x so that the axis
230 // line stroke sits within the desired label engine rect (otherwise we risk overlaps of the axis line stroke)
231 const double maxBleed = QgsSymbolLayerUtils::estimateMaxSymbolBleed( s.axisLineSymbol(), c );
232 baseX += maxBleed;
233 baseY -= maxBleed;
234 }
235
236 mPen.setColor( s.penColor );
237 setPenWidth( mPen, s, c );
238 p->setPen( mPen );
239
240 while ( !negativeValues.isEmpty() )
241 {
242 values.push_front( negativeValues.takeLast() );
243 }
244
245 double currentOffset = 0;
246 QList< QPair<double, QColor> >::const_iterator valIt = values.constBegin();
247 for ( ; valIt != values.constEnd(); ++valIt )
248 {
249 double length = valIt->first / total * scaledMaxVal;
250
251 QColor brushColor( valIt->second );
252 brushColor.setAlphaF( brushColor.alphaF() * s.opacity );
253 mCategoryBrush.setColor( brushColor );
254 p->setBrush( mCategoryBrush );
255
256 switch ( s.diagramOrientation )
257 {
259 p->drawRect( QRectF( baseX, baseY - currentOffset, scaledWidth, length * -1 ) );
260 break;
261
263 p->drawRect( QRectF( baseX, baseY + currentOffset - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ), scaledWidth, length ) );
264 break;
265
267 p->drawRect( QRectF( baseX + currentOffset, baseY - scaledWidth, length, scaledWidth ) );
268 break;
269
271 p->drawRect( QRectF( baseX + scaledMaxVal - currentOffset + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ), baseY - scaledWidth, 0 - length, scaledWidth ) );
272 break;
273 }
274
275 currentOffset += length + spacing;
276 }
277
278 if ( s.showAxis() && s.axisLineSymbol() )
279 {
281 QPolygonF axisPoints;
282 switch ( s.diagramOrientation )
283 {
285 axisPoints << QPointF( baseX, baseY - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) )
286 << QPointF( baseX, baseY - axisOffset )
287 << QPointF( baseX + scaledWidth, baseY - axisOffset );
288 break;
289
291 axisPoints << QPointF( baseX, baseY )
292 << QPointF( baseX, baseY - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) + axisOffset )
293 << QPointF( baseX + scaledWidth, baseY - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) + axisOffset );
294 break;
295
297 axisPoints << QPointF( baseX + scaledMaxVal + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ), baseY - scaledWidth )
298 << QPointF( baseX + axisOffset, baseY - scaledWidth )
299 << QPointF( baseX + axisOffset, baseY );
300 break;
301
303 axisPoints << QPointF( baseX, baseY - scaledWidth )
304 << QPointF( baseX + scaledMaxVal + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) - axisOffset, baseY - scaledWidth )
305 << QPointF( baseX + scaledMaxVal + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) - axisOffset, baseY );
306 break;
307 }
308
309 s.axisLineSymbol()->renderPolyline( axisPoints, nullptr, c );
311 }
312}
A vector of attributes.
Additional diagram settings for interpolated size rendering.
QString classificationField
Name of the field for classification.
Stores the settings for rendering a single diagram.
bool showAxis() const
Returns true if the diagram axis should be shown.
double opacity
Opacity, from 0 (transparent) to 1.0 (opaque).
QgsLineSymbol * axisLineSymbol() const
Returns the line symbol to use for rendering axis in diagrams.
Qgis::RenderUnit sizeType
Diagram size unit.
QList< QString > categoryAttributes
DiagramOrientation diagramOrientation
double spacing() const
Returns the spacing between diagram contents.
QList< QColor > categoryColors
const QgsMapUnitScale & spacingMapUnitScale() const
Returns the map unit scale for the content spacing.
double minimumSize
Scale diagrams smaller than mMinimumSize to mMinimumSize.
Qgis::RenderUnit spacingUnit() const
Returns the units for the content spacing.
void setPenWidth(QPen &pen, const QgsDiagramSettings &s, const QgsRenderContext &c)
Changes the pen width to match the current settings and rendering context.
QSizeF sizePainterUnits(QSizeF size, const QgsDiagramSettings &s, const QgsRenderContext &c)
Calculates a size to match the current settings and rendering context.
QgsExpression * getExpression(const QString &expression, const QgsExpressionContext &context)
Returns a prepared expression for the specified context.
QSizeF sizeForValue(double value, const QgsDiagramSettings &s, const QgsDiagramInterpolationSettings &interpolationSettings) const
Returns the scaled size of a diagram for a value, respecting the specified diagram interpolation sett...
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
QVariant evaluate()
Evaluate the feature and return the result.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsFields fields
Definition qgsfeature.h:68
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
bool isEmpty
Definition qgsfields.h:49
void renderPolyline(const QPolygonF &points, const QgsFeature *f, QgsRenderContext &context, int layer=-1, bool selected=false)
Renders the symbol along the line joining points, using the given render context.
Contains information about the context of a rendering operation.
double legendSize(double value, const QgsDiagramSettings &s, const QgsDiagramInterpolationSettings &interpolationSettings) const override
Returns the size of the legend item for the diagram corresponding to a specified value.
QgsStackedBarDiagram * clone() const override
Returns an instance that is equivalent to this one.
QSizeF diagramSize(const QgsAttributes &attributes, const QgsRenderContext &c, const QgsDiagramSettings &s) override
Returns the size in map units the diagram will use to render.
QString diagramName() const override
Gets a descriptive name for this diagram type.
void renderDiagram(const QgsFeature &feature, QgsRenderContext &c, const QgsDiagramSettings &s, QPointF position) override
Draws the diagram at the given position (in pixel coordinates).
static const QString DIAGRAM_NAME_STACKED_BAR
static double estimateMaxSymbolBleed(QgsSymbol *symbol, const QgsRenderContext &context)
Returns the maximum estimated bleed for the symbol.
void stopRender(QgsRenderContext &context)
Ends the rendering process.
void startRender(QgsRenderContext &context, const QgsFields &fields=QgsFields())
Begins the rendering process for the symbol.
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
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6607