QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgsannotationpointtextitem.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsannotationpointtextitem.cpp
3 ----------------
4 begin : August 2020
5 copyright : (C) 2020 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
22#include "qgsapplication.h"
23#include "qgscalloutsregistry.h"
24#include "qgsrendercontext.h"
25#include "qgstextrenderer.h"
26
27#include <QString>
28
29using namespace Qt::StringLiterals;
30
36
42
44
46{
47 return u"pointtext"_s;
48}
49
51{
52 QPointF pt;
53 if ( context.coordinateTransform().isValid() )
54 {
55 double x = mPoint.x();
56 double y = mPoint.y();
57 double z = 0.0;
58 context.coordinateTransform().transformInPlace( x, y, z );
59 pt = QPointF( x, y );
60 }
61 else
62 pt = mPoint.toQPointF();
63
64 context.mapToPixel().transformInPlace( pt.rx(), pt.ry() );
65
66 double angle = mAngle;
67 switch ( mRotationMode )
68 {
70 angle += context.mapToPixel().mapRotation();
71 break;
72
74 break;
75 }
76
77 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
78
79 if ( callout() )
80 {
81 const double textWidth = QgsTextRenderer::textWidth( context, mTextFormat, displayText.split( '\n' ) );
82 const double textHeight = QgsTextRenderer::textHeight( context, mTextFormat, displayText.split( '\n' ) );
83
84 QgsCallout::QgsCalloutContext calloutContext;
85 renderCallout( context, QRectF( pt.x(), pt.y() - textHeight, textWidth, textHeight ), angle, calloutContext, feedback );
86 }
87
89 drawText( pt, -angle * M_PI / 180.0, QgsTextRenderer::convertQtHAlignment( mAlignment ), mTextFormat.allowHtmlFormatting() ? QStringList { displayText } : displayText.split( '\n' ), context, mTextFormat );
90}
91
92bool QgsAnnotationPointTextItem::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
93{
94 element.setAttribute( u"x"_s, qgsDoubleToString( mPoint.x() ) );
95 element.setAttribute( u"y"_s, qgsDoubleToString( mPoint.y() ) );
96 element.setAttribute( u"text"_s, mText );
97 element.setAttribute( u"angle"_s, qgsDoubleToString( mAngle ) );
98 element.setAttribute( u"alignment"_s, QString::number( mAlignment ) );
99 element.setAttribute( u"rotationMode"_s, qgsEnumValueToKey( mRotationMode ) );
100
101 QDomElement textFormatElem = document.createElement( u"pointTextFormat"_s );
102 textFormatElem.appendChild( mTextFormat.writeXml( document, context ) );
103 element.appendChild( textFormatElem );
104
105 writeCommonProperties( element, document, context );
106 return true;
107}
108
113
114bool QgsAnnotationPointTextItem::readXml( const QDomElement &element, const QgsReadWriteContext &context )
115{
116 const double x = element.attribute( u"x"_s ).toDouble();
117 const double y = element.attribute( u"y"_s ).toDouble();
118 mPoint = QgsPointXY( x, y );
119 mText = element.attribute( u"text"_s );
120 mAngle = element.attribute( u"angle"_s ).toDouble();
121 mAlignment = static_cast< Qt::Alignment >( element.attribute( u"alignment"_s ).toInt() );
122 mRotationMode = qgsEnumKeyToValue( element.attribute( u"rotationMode"_s ), Qgis::SymbolRotationMode::IgnoreMapRotation );
123 const QDomElement textFormatElem = element.firstChildElement( u"pointTextFormat"_s );
124 if ( !textFormatElem.isNull() )
125 {
126 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( u"text-style"_s );
127 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
128 mTextFormat.readXml( textFormatElem, context );
129 }
130
131 readCommonProperties( element, context );
132 return true;
133}
134
136{
137 auto item = std::make_unique< QgsAnnotationPointTextItem >( mText, mPoint );
138 item->setFormat( mTextFormat );
139 item->setAngle( mAngle );
140 item->setAlignment( mAlignment );
141 item->setRotationMode( mRotationMode );
142 item->copyCommonProperties( this );
143 return item.release();
144}
145
147{
148 return QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x(), mPoint.y() );
149}
150
151QgsRectangle rotateBoundingBoxAroundPoint( double cx, double cy, const QgsRectangle &original, double angleClockwiseDegrees )
152{
153 QTransform t;
154 t.translate( cx, cy );
155 const double angleRadians = -M_PI * angleClockwiseDegrees / 180.0;
156 t.rotateRadians( angleRadians );
157 t.translate( -cx, -cy );
158 const QRectF result = t.mapRect( original.toRectF() );
159 return QgsRectangle( result );
160}
161
163{
164 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
165
166 const double widthInPixels = QgsTextRenderer::textWidth( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList { displayText } : displayText.split( '\n' ) );
167 const double heightInPixels = QgsTextRenderer::textHeight( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList { displayText } : displayText.split( '\n' ) );
168
169 // text size has already been calculated using any symbology reference scale factor above -- we need
170 // to temporarily remove the reference scale here or we'll be undoing the scaling
171 QgsScopedRenderContextReferenceScaleOverride resetScaleFactor( context, -1.0 );
172 const double widthInMapUnits = context.convertToMapUnits( widthInPixels, Qgis::RenderUnit::Pixels );
173 const double heightInMapUnits = context.convertToMapUnits( heightInPixels, Qgis::RenderUnit::Pixels );
174
175 double angle = mAngle;
176 switch ( mRotationMode )
177 {
179 angle += context.mapToPixel().mapRotation();
180 break;
181
183 break;
184 }
185
186 QgsRectangle unrotatedRect;
187 switch ( mAlignment & Qt::AlignHorizontal_Mask )
188 {
189 case Qt::AlignRight:
190 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits, mPoint.y(), mPoint.x(), mPoint.y() + heightInMapUnits );
191 break;
192
193 case Qt::AlignHCenter:
194 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits * 0.5, mPoint.y(), mPoint.x() + widthInMapUnits * 0.5, mPoint.y() + heightInMapUnits );
195 break;
196
197 default:
198 unrotatedRect = QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x() + widthInMapUnits, mPoint.y() + heightInMapUnits );
199 break;
200 }
201
202 QgsRectangle textRect;
203 if ( !qgsDoubleNear( angle, 0 ) )
204 {
205 textRect = rotateBoundingBoxAroundPoint( mPoint.x(), mPoint.y(), unrotatedRect, angle );
206 }
207 else
208 {
209 textRect = unrotatedRect;
210 }
211
212 if ( callout() && !calloutAnchor().isEmpty() )
213 {
214 QgsGeometry anchor = calloutAnchor();
215 textRect.combineExtentWith( anchor.boundingBox() );
216 }
217 return textRect;
218}
219
220QList<QgsAnnotationItemNode> QgsAnnotationPointTextItem::nodesV2( const QgsAnnotationItemEditContext &context ) const
221{
222 QList<QgsAnnotationItemNode> res = { QgsAnnotationItemNode( QgsVertexId( 0, 0, 0 ), mPoint, Qgis::AnnotationItemNodeType::VertexHandle ) };
223
224 QgsPointXY calloutNodePoint;
225 if ( !calloutAnchor().isEmpty() )
226 {
227 calloutNodePoint = calloutAnchor().asPoint();
228 }
229 else
230 {
231 calloutNodePoint = context.currentItemBounds().center();
232 }
233 res.append( QgsAnnotationItemNode( QgsVertexId( 0, 0, 1 ), calloutNodePoint, Qgis::AnnotationItemNodeType::CalloutHandle ) );
234
235 return res;
236}
237
239{
240 switch ( operation->type() )
241 {
243 {
244 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
245 if ( moveOperation->nodeId().vertex == 0 )
246 {
247 mPoint = moveOperation->after();
248 }
249 else if ( moveOperation->nodeId().vertex == 1 )
250 {
251 setCalloutAnchor( QgsGeometry::fromPoint( moveOperation->after() ) );
252 if ( !callout() )
253 {
254 setCallout( QgsApplication::calloutRegistry()->defaultCallout() );
255 }
256 }
258 }
259
261 {
263 }
264
266 {
267 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
268 mPoint.setX( mPoint.x() + moveOperation->translationX() );
269 mPoint.setY( mPoint.y() + moveOperation->translationY() );
271 }
272
274 {
275 QgsAnnotationItemEditOperationRotateItem *rotateOperation = qgis::down_cast< QgsAnnotationItemEditOperationRotateItem * >( operation );
276 mAngle = std::fmod( mAngle + rotateOperation->angle(), 360.0 );
278 }
279
281 break;
282 }
283
285}
286
288{
289 switch ( operation->type() )
290 {
292 {
293 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
294 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( moveOperation->after().clone() ) );
295 }
296
298 {
299 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
300 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( new QgsPoint( mPoint.x() + moveOperation->translationX(), mPoint.y() + moveOperation->translationY() ) ) );
301 }
302
306 break;
307 }
308 return nullptr;
309}
310
312{
313 return mTextFormat;
314}
315
317{
318 mTextFormat = format;
319}
320
322{
323 return mAlignment;
324}
325
327{
328 mAlignment = alignment;
329}
330
332{
333 return mRotationMode;
334}
335
337{
338 mRotationMode = mode;
339}
SymbolRotationMode
Modes for handling how symbol and text entity rotation is handled when maps are rotated.
Definition qgis.h:812
@ RespectMapRotation
Entity is rotated along with the map.
Definition qgis.h:813
@ IgnoreMapRotation
Entity ignores map rotation.
Definition qgis.h:814
@ VertexHandle
Node is a handle for manipulating vertices.
Definition qgis.h:2597
@ CalloutHandle
Node is a handle for manipulating callouts.
Definition qgis.h:2598
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
Definition qgis.h:2554
@ SupportsCallouts
Item supports callouts.
Definition qgis.h:2556
@ SupportsReferenceScale
Item supports reference scale based rendering.
Definition qgis.h:2555
AnnotationItemEditOperationResult
Results from an edit operation on an annotation item.
Definition qgis.h:2608
@ Invalid
Operation has invalid parameters for the item, no change occurred.
Definition qgis.h:2610
@ Success
Item was modified successfully.
Definition qgis.h:2609
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
Definition qgis.h:2611
QFlags< AnnotationItemFlag > AnnotationItemFlags
Annotation item flags.
Definition qgis.h:2559
@ Pixels
Pixels.
Definition qgis.h:5343
Abstract base class for annotation item edit operations.
virtual Type type() const =0
Returns the operation type.
Encapsulates the context for an annotation item edit operation.
QgsRectangle currentItemBounds() const
Returns the current rendered bounds of the item, in the annotation layer's CRS.
Annotation item edit operation consisting of moving a node.
QgsPoint after() const
Returns the node position after the move occurred (in layer coordinates).
QgsVertexId nodeId() const
Returns the associated node ID.
Annotation item edit operation consisting of rotating an item.
double angle() const
Returns the rotation angle value (in degrees clockwise).
Encapsulates the transient results of an in-progress annotation edit operation.
Annotation item edit operation consisting of translating (moving) an item.
double translationY() const
Returns the y-axis translation, in layer units.
double translationX() const
Returns the x-axis translation, in layer units.
Contains information about a node used for editing an annotation item.
virtual bool writeCommonProperties(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes common properties from the base class into an XML element.
void setCallout(QgsCallout *callout)
Sets the item's callout renderer, responsible for drawing item callouts.
QgsGeometry calloutAnchor() const
Returns the callout's anchor geometry.
void setCalloutAnchor(const QgsGeometry &anchor)
Sets the callout's anchor geometry.
QgsCallout * callout() const
Returns the item's callout renderer, responsible for drawing item callouts.
virtual bool readCommonProperties(const QDomElement &element, const QgsReadWriteContext &context)
Reads common properties from the base class from the given DOM element.
void renderCallout(QgsRenderContext &context, const QRectF &rect, double angle, QgsCallout::QgsCalloutContext &calloutContext, QgsFeedback *feedback)
Renders the item's callout.
QString type() const override
Returns a unique (untranslated) string identifying the type of item.
QgsTextFormat format() const
Returns the text format used to render the text.
QgsPointXY point() const
Returns the point location of the text.
void setFormat(const QgsTextFormat &format)
Sets the text format used to render the text.
~QgsAnnotationPointTextItem() override
QgsAnnotationPointTextItem * clone() const override
Returns a clone of the item.
double angle() const
Returns the text's rotation angle, in degrees clockwise.
Qt::Alignment alignment() const
Returns the text's alignment relative to the reference point().
void setAlignment(Qt::Alignment alignment)
Sets the text's alignment relative to the reference point().
QgsRectangle boundingBox() const override
Returns the bounding box of the item's geographic location, in the parent layer's coordinate referenc...
static QgsAnnotationPointTextItem * create()
Creates a new text at point annotation item.
bool readXml(const QDomElement &element, const QgsReadWriteContext &context) override
Reads the item's state from the given DOM element.
QString text() const
Returns the text rendered by the item.
bool writeXml(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const override
Writes the item's state into an XML element.
Qgis::AnnotationItemFlags flags() const override
Returns item flags.
void render(QgsRenderContext &context, QgsFeedback *feedback) override
Renders the item to the specified render context.
QgsAnnotationPointTextItem(const QString &text, QgsPointXY point)
Constructor for QgsAnnotationPointTextItem, containing the specified text at the specified point.
void setRotationMode(Qgis::SymbolRotationMode mode)
Sets the rotation mode for the text item.
Qgis::SymbolRotationMode rotationMode() const
Returns the rotation mode for the text item.
QList< QgsAnnotationItemNode > nodesV2(const QgsAnnotationItemEditContext &context) const override
Returns the nodes for the item, used for editing the item.
QgsAnnotationItemEditOperationTransientResults * transientEditResultsV2(QgsAbstractAnnotationItemEditOperation *operation, const QgsAnnotationItemEditContext &context) override
Retrieves the results of a transient (in progress) edit operation on the item.
Qgis::AnnotationItemEditOperationResult applyEditV2(QgsAbstractAnnotationItemEditOperation *operation, const QgsAnnotationItemEditContext &context) override
Applies an edit operation to the item.
static QgsCalloutRegistry * calloutRegistry()
Returns the application's callout registry, used for managing callout types.
Contains additional contextual information about the context in which a callout is being rendered.
Definition qgscallout.h:248
void transformInPlace(double &x, double &y, double &z, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transforms an array of x, y and z double coordinates in place, from the source CRS to the destination...
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
static QString replaceExpressionText(const QString &action, const QgsExpressionContext *context, const QgsDistanceArea *distanceArea=nullptr)
This function replaces each expression between [% and %] in the string with the result of its evaluat...
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
A geometry is the spatial representation of a feature.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static QgsGeometry fromPoint(const QgsPoint &point)
Creates a new geometry from a QgsPoint object.
double mapRotation() const
Returns the current map rotation in degrees (clockwise).
void transformInPlace(double &x, double &y) const
Transforms map coordinates to device coordinates.
Represents a 2D point.
Definition qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition qgspoint.cpp:138
A container for the context for various read/write operations on objects.
A rectangle specified with double values.
QRectF toRectF() const
Returns a QRectF with same coordinates as the rectangle.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
QgsPointXY center
Contains information about the context of a rendering operation.
double convertToMapUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
const QgsDistanceArea & distanceArea() const
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
QgsExpressionContext & expressionContext()
Gets the expression context.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
Scoped object for temporary override of the symbologyReferenceScale property of a QgsRenderContext.
Container for all settings relating to text rendering.
static double textWidth(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, QFontMetricsF *fontMetrics=nullptr)
Returns the width of a text based on a given format.
static void drawText(const QRectF &rect, double rotation, Qgis::TextHorizontalAlignment alignment, const QStringList &textLines, QgsRenderContext &context, const QgsTextFormat &format, bool drawAsOutlines=true, Qgis::TextVerticalAlignment vAlignment=Qgis::TextVerticalAlignment::Top, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Rectangle)
Draws text within a rectangle using the specified settings.
static double textHeight(const QgsRenderContext &context, const QgsTextFormat &format, const QStringList &textLines, Qgis::TextLayoutMode mode=Qgis::TextLayoutMode::Point, QFontMetricsF *fontMetrics=nullptr, Qgis::TextRendererFlags flags=Qgis::TextRendererFlags(), double maxLineWidth=0)
Returns the height of a text based on a given format.
static Qgis::TextHorizontalAlignment convertQtHAlignment(Qt::Alignment alignment)
Converts a Qt horizontal alignment flag to a Qgis::TextHorizontalAlignment value.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
Definition qgis.h:7176
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:6893
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:7157
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6975
QgsRectangle rotateBoundingBoxAroundPoint(double cx, double cy, const QgsRectangle &original, double angleClockwiseDegrees)
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:34
int vertex
Vertex number.
Definition qgsvertexid.h:99