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