QGIS API Documentation 3.99.0-Master (e9821da5c6b)
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#include <QString>
26
27using namespace Qt::StringLiterals;
28
29const QString QgsStackedBarDiagram::DIAGRAM_NAME_STACKED_BAR = u"Stacked"_s;
30
32{
33 mCategoryBrush.setStyle( Qt::SolidPattern );
34 mPen.setStyle( Qt::SolidLine );
35}
36
41
43{
44 if ( qgsDoubleNear( is.upperValue, is.lowerValue ) )
45 return QSizeF(); // invalid value range => zero size
46
47 QVariant attrVal;
49 {
50 QgsExpressionContext expressionContext = c.expressionContext();
51 if ( !feature.fields().isEmpty() )
52 expressionContext.setFields( feature.fields() );
53 expressionContext.setFeature( feature );
54
55 QgsExpression *expression = getExpression( is.classificationAttributeExpression, expressionContext );
56 attrVal = expression->evaluate( &expressionContext );
57 }
58 else
59 {
60 attrVal = feature.attribute( is.classificationField );
61 }
62
63 bool ok = false;
64 double value = fabs( attrVal.toDouble( &ok ) );
65 if ( !ok )
66 {
67 return QSizeF(); //zero size if attribute is missing
68 }
69
70 QSizeF size = sizeForValue( value, s, is );
71
72 // eh - this method returns size in unknown units ...! We'll have to fake it and use a rough estimation of
73 // a conversion factor to painter units...
74 // TODO QGIS 5.0 -- these methods should all use painter units, dependent on the render context scaling...
75 double painterUnitConversionScale = c.convertToPainterUnits( 1, s.sizeType );
76
77 const double spacing = c.convertToPainterUnits( s.spacing(), s.spacingUnit(), s.spacingMapUnitScale() ) / painterUnitConversionScale;
78 mApplySpacingAdjust = true;
79
80 switch ( s.diagramOrientation )
81 {
84 {
85 const double totalBarLength = size.height() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 );
86 size = QSizeF( s.barWidth, totalBarLength );
87 break;
88 }
89
92 {
93 const double totalBarLength = size.width() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 );
94 size = QSizeF( totalBarLength, s.barWidth );
95 break;
96 }
97 }
98
99 if ( s.showAxis() && s.axisLineSymbol() )
100 {
101 const double maxBleed = QgsSymbolLayerUtils::estimateMaxSymbolBleed( s.axisLineSymbol(), c ) / painterUnitConversionScale;
102 size.setWidth( size.width() + 2 * maxBleed );
103 size.setHeight( size.height() + 2 * maxBleed );
104 }
105
106 return size;
107}
108
110{
111 if ( qgsDoubleNear( is.upperValue, is.lowerValue ) )
112 return s.minimumSize; // invalid value range => zero size
113
114 // Scale, if extension is smaller than the specified minimum
115 if ( value < s.minimumSize )
116 {
117 value = s.minimumSize;
118 }
119
120 double scaleFactor = ( ( is.upperSize.width() - is.lowerSize.width() ) / ( is.upperValue - is.lowerValue ) );
121 return value * scaleFactor;
122}
123
128
130{
131 Q_UNUSED( c )
132 QSizeF size;
133
134 if ( attributes.isEmpty() )
135 {
136 return QSizeF(); //zero size if no attributes
137 }
138
139 // eh - this method returns size in unknown units ...! We'll have to fake it and use a rough estimation of
140 // a conversion factor to painter units...
141 // TODO QGIS 5.0 -- these methods should all use painter units, dependent on the render context scaling...
142 double painterUnitConversionScale = c.convertToPainterUnits( 1, s.sizeType );
143
144 const double spacing = c.convertToPainterUnits( s.spacing(), s.spacingUnit(), s.spacingMapUnitScale() ) / painterUnitConversionScale;
145
146 switch ( s.diagramOrientation )
147 {
150 size.scale( s.barWidth, s.size.height() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 ), Qt::IgnoreAspectRatio );
151 break;
152
155 size.scale( s.size.width() + spacing * std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 ), s.barWidth, Qt::IgnoreAspectRatio );
156 break;
157 }
158
159 return size;
160}
161
162void QgsStackedBarDiagram::renderDiagram( const QgsFeature &feature, QgsRenderContext &c, const QgsDiagramSettings &s, QPointF position )
163{
164 QPainter *p = c.painter();
165 if ( !p )
166 {
167 return;
168 }
169
170 QList< QPair<double, QColor> > values;
171 QList< QPair<double, QColor> > negativeValues;
172
173 QgsExpressionContext expressionContext = c.expressionContext();
174 expressionContext.setFeature( feature );
175 if ( !feature.fields().isEmpty() )
176 expressionContext.setFields( feature.fields() );
177
178 values.reserve( s.categoryAttributes.size() );
179 double total = 0;
180 double negativeTotal = 0;
181
182 QList< QColor >::const_iterator colIt = s.categoryColors.constBegin();
183 for ( const QString &cat : std::as_const( s.categoryAttributes ) )
184 {
185 QgsExpression *expression = getExpression( cat, expressionContext );
186 double currentVal = expression->evaluate( &expressionContext ).toDouble();
187 total += fabs( currentVal );
188 if ( currentVal >= 0 )
189 {
190 values.push_back( qMakePair( currentVal, *colIt ) );
191 }
192 else
193 {
194 negativeTotal += currentVal;
195 negativeValues.push_back( qMakePair( -currentVal, *colIt ) );
196 }
197 ++colIt;
198 }
199
200
201 const double spacing = c.convertToPainterUnits( s.spacing(), s.spacingUnit(), s.spacingMapUnitScale() );
202 const double totalSpacing = std::max( 0, static_cast<int>( s.categoryAttributes.size() ) - 1 ) * spacing;
203
204 double scaledMaxVal = 0;
205 switch ( s.diagramOrientation )
206 {
209 scaledMaxVal = sizePainterUnits( s.size.height(), s, c );
210 break;
211
214 scaledMaxVal = sizePainterUnits( s.size.width(), s, c );
215 break;
216 }
217 if ( mApplySpacingAdjust )
218 scaledMaxVal -= totalSpacing;
219
220 double axisOffset = 0;
221 if ( !negativeValues.isEmpty() )
222 {
223 axisOffset = -negativeTotal / total * scaledMaxVal + ( negativeValues.size() - 1 ) * spacing;
224 }
225 double scaledWidth = sizePainterUnits( s.barWidth, s, c );
226
227 double baseX = position.x();
228 double baseY = position.y();
229
230 if ( s.showAxis() && s.axisLineSymbol() )
231 {
232 // if showing axis, the diagram position needs shifting from the default base x so that the axis
233 // line stroke sits within the desired label engine rect (otherwise we risk overlaps of the axis line stroke)
234 const double maxBleed = QgsSymbolLayerUtils::estimateMaxSymbolBleed( s.axisLineSymbol(), c );
235 baseX += maxBleed;
236 baseY -= maxBleed;
237 }
238
239 mPen.setColor( s.penColor );
240 setPenWidth( mPen, s, c );
241 p->setPen( mPen );
242
243 while ( !negativeValues.isEmpty() )
244 {
245 values.push_front( negativeValues.takeLast() );
246 }
247
248 double currentOffset = 0;
249 QList< QPair<double, QColor> >::const_iterator valIt = values.constBegin();
250 for ( ; valIt != values.constEnd(); ++valIt )
251 {
252 double length = valIt->first / total * scaledMaxVal;
253
254 QColor brushColor( valIt->second );
255 brushColor.setAlphaF( brushColor.alphaF() * s.opacity );
256 mCategoryBrush.setColor( brushColor );
257 p->setBrush( mCategoryBrush );
258
259 switch ( s.diagramOrientation )
260 {
262 p->drawRect( QRectF( baseX, baseY - currentOffset, scaledWidth, length * -1 ) );
263 break;
264
266 p->drawRect( QRectF( baseX, baseY + currentOffset - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ), scaledWidth, length ) );
267 break;
268
270 p->drawRect( QRectF( baseX + currentOffset, baseY - scaledWidth, length, scaledWidth ) );
271 break;
272
274 p->drawRect( QRectF( baseX + scaledMaxVal - currentOffset + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ), baseY - scaledWidth, 0 - length, scaledWidth ) );
275 break;
276 }
277
278 currentOffset += length + spacing;
279 }
280
281 if ( s.showAxis() && s.axisLineSymbol() )
282 {
284 QPolygonF axisPoints;
285 switch ( s.diagramOrientation )
286 {
288 axisPoints << QPointF( baseX, baseY - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) )
289 << QPointF( baseX, baseY - axisOffset )
290 << QPointF( baseX + scaledWidth, baseY - axisOffset );
291 break;
292
294 axisPoints << QPointF( baseX, baseY )
295 << QPointF( baseX, baseY - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) + axisOffset )
296 << QPointF( baseX + scaledWidth, baseY - scaledMaxVal - spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) + axisOffset );
297 break;
298
300 axisPoints << QPointF( baseX + scaledMaxVal + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ), baseY - scaledWidth )
301 << QPointF( baseX + axisOffset, baseY - scaledWidth )
302 << QPointF( baseX + axisOffset, baseY );
303 break;
304
306 axisPoints << QPointF( baseX, baseY - scaledWidth )
307 << QPointF( baseX + scaledMaxVal + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) - axisOffset, baseY - scaledWidth )
308 << QPointF( baseX + scaledMaxVal + spacing * std::max( 0, static_cast<int>( values.size() ) - 1 ) - axisOffset, baseY );
309 break;
310 }
311
312 s.axisLineSymbol()->renderPolyline( axisPoints, nullptr, c );
314 }
315}
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:60
QgsFields fields
Definition qgsfeature.h:70
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:6924