QGIS API Documentation 3.99.0-Master (d270888f95f)
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
33 , mText( text )
34 , mPoint( point )
35{
36
37}
38
46
48
50{
51 return u"pointtext"_s;
52}
53
55{
56 QPointF pt;
57 if ( context.coordinateTransform().isValid() )
58 {
59 double x = mPoint.x();
60 double y = mPoint.y();
61 double z = 0.0;
62 context.coordinateTransform().transformInPlace( x, y, z );
63 pt = QPointF( x, y );
64 }
65 else
66 pt = mPoint.toQPointF();
67
68 context.mapToPixel().transformInPlace( pt.rx(), pt.ry() );
69
70 double angle = mAngle;
71 switch ( mRotationMode )
72 {
74 angle += context.mapToPixel().mapRotation();
75 break;
76
78 break;
79 }
80
81 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
82
83 if ( callout() )
84 {
85 const double textWidth = QgsTextRenderer::textWidth(
86 context, mTextFormat, displayText.split( '\n' ) );
87 const double textHeight = QgsTextRenderer::textHeight(
88 context, mTextFormat, displayText.split( '\n' ) );
89
90 QgsCallout::QgsCalloutContext calloutContext;
91 renderCallout( context, QRectF( pt.x(), pt.y() - textHeight, textWidth, textHeight ), angle, calloutContext, feedback );
92 }
93
94 QgsTextRenderer::drawText( pt, - angle * M_PI / 180.0,
96 mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ), context, mTextFormat );
97}
98
99bool QgsAnnotationPointTextItem::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
100{
101 element.setAttribute( u"x"_s, qgsDoubleToString( mPoint.x() ) );
102 element.setAttribute( u"y"_s, qgsDoubleToString( mPoint.y() ) );
103 element.setAttribute( u"text"_s, mText );
104 element.setAttribute( u"angle"_s, qgsDoubleToString( mAngle ) );
105 element.setAttribute( u"alignment"_s, QString::number( mAlignment ) );
106 element.setAttribute( u"rotationMode"_s, qgsEnumValueToKey( mRotationMode ) );
107
108 QDomElement textFormatElem = document.createElement( u"pointTextFormat"_s );
109 textFormatElem.appendChild( mTextFormat.writeXml( document, context ) );
110 element.appendChild( textFormatElem );
111
112 writeCommonProperties( element, document, context );
113 return true;
114}
115
120
121bool QgsAnnotationPointTextItem::readXml( const QDomElement &element, const QgsReadWriteContext &context )
122{
123 const double x = element.attribute( u"x"_s ).toDouble();
124 const double y = element.attribute( u"y"_s ).toDouble();
125 mPoint = QgsPointXY( x, y );
126 mText = element.attribute( u"text"_s );
127 mAngle = element.attribute( u"angle"_s ).toDouble();
128 mAlignment = static_cast< Qt::Alignment >( element.attribute( u"alignment"_s ).toInt() );
129 mRotationMode = qgsEnumKeyToValue( element.attribute( u"rotationMode"_s ), Qgis::SymbolRotationMode::IgnoreMapRotation );
130 const QDomElement textFormatElem = element.firstChildElement( u"pointTextFormat"_s );
131 if ( !textFormatElem.isNull() )
132 {
133 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( u"text-style"_s );
134 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
135 mTextFormat.readXml( textFormatElem, context );
136 }
137
138 readCommonProperties( element, context );
139 return true;
140}
141
143{
144 auto item = std::make_unique< QgsAnnotationPointTextItem >( mText, mPoint );
145 item->setFormat( mTextFormat );
146 item->setAngle( mAngle );
147 item->setAlignment( mAlignment );
148 item->setRotationMode( mRotationMode );
149 item->copyCommonProperties( this );
150 return item.release();
151}
152
154{
155 return QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x(), mPoint.y() );
156}
157
158QgsRectangle rotateBoundingBoxAroundPoint( double cx, double cy, const QgsRectangle &original, double angleClockwiseDegrees )
159{
160 QTransform t;
161 t.translate( cx, cy );
162 const double angleRadians = -M_PI * angleClockwiseDegrees / 180.0;
163 t.rotateRadians( angleRadians );
164 t.translate( -cx, -cy );
165 const QRectF result = t.mapRect( original.toRectF() );
166 return QgsRectangle( result );
167}
168
170{
171 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
172
173 const double widthInPixels = QgsTextRenderer::textWidth( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ) );
174 const double heightInPixels = QgsTextRenderer::textHeight( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ) );
175
176 // text size has already been calculated using any symbology reference scale factor above -- we need
177 // to temporarily remove the reference scale here or we'll be undoing the scaling
178 QgsScopedRenderContextReferenceScaleOverride resetScaleFactor( context, -1.0 );
179 const double widthInMapUnits = context.convertToMapUnits( widthInPixels, Qgis::RenderUnit::Pixels );
180 const double heightInMapUnits = context.convertToMapUnits( heightInPixels, Qgis::RenderUnit::Pixels );
181
182 double angle = mAngle;
183 switch ( mRotationMode )
184 {
186 angle += context.mapToPixel().mapRotation();
187 break;
188
190 break;
191 }
192
193 QgsRectangle unrotatedRect;
194 switch ( mAlignment & Qt::AlignHorizontal_Mask )
195 {
196 case Qt::AlignRight:
197 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits, mPoint.y(), mPoint.x(), mPoint.y() + heightInMapUnits );
198 break;
199
200 case Qt::AlignHCenter:
201 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits * 0.5, mPoint.y(), mPoint.x() + widthInMapUnits * 0.5, mPoint.y() + heightInMapUnits );
202 break;
203
204 default:
205 unrotatedRect = QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x() + widthInMapUnits, mPoint.y() + heightInMapUnits );
206 break;
207 }
208
209 QgsRectangle textRect;
210 if ( !qgsDoubleNear( angle, 0 ) )
211 {
212 textRect = rotateBoundingBoxAroundPoint( mPoint.x(), mPoint.y(), unrotatedRect, angle );
213 }
214 else
215 {
216 textRect = unrotatedRect;
217 }
218
219 if ( callout() && !calloutAnchor().isEmpty() )
220 {
221 QgsGeometry anchor = calloutAnchor();
222 textRect.combineExtentWith( anchor.boundingBox() );
223 }
224 return textRect;
225}
226
227QList<QgsAnnotationItemNode> QgsAnnotationPointTextItem::nodesV2( const QgsAnnotationItemEditContext &context ) const
228{
229 QList<QgsAnnotationItemNode> res = { QgsAnnotationItemNode( QgsVertexId( 0, 0, 0 ), mPoint, Qgis::AnnotationItemNodeType::VertexHandle )};
230
231 QgsPointXY calloutNodePoint;
232 if ( !calloutAnchor().isEmpty() )
233 {
234 calloutNodePoint = calloutAnchor().asPoint();
235 }
236 else
237 {
238 calloutNodePoint = context.currentItemBounds().center();
239 }
240 res.append( QgsAnnotationItemNode( QgsVertexId( 0, 0, 1 ), calloutNodePoint, Qgis::AnnotationItemNodeType::CalloutHandle ) );
241
242 return res;
243}
244
246{
247 switch ( operation->type() )
248 {
250 {
251 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
252 if ( moveOperation->nodeId().vertex == 0 )
253 {
254 mPoint = moveOperation->after();
255 }
256 else if ( moveOperation->nodeId().vertex == 1 )
257 {
258 setCalloutAnchor( QgsGeometry::fromPoint( moveOperation->after() ) );
259 if ( !callout() )
260 {
261 setCallout( QgsApplication::calloutRegistry()->defaultCallout() );
262 }
263 }
265 }
266
268 {
270 }
271
273 {
274 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
275 mPoint.setX( mPoint.x() + moveOperation->translationX() );
276 mPoint.setY( mPoint.y() + moveOperation->translationY() );
278 }
279
281 {
282 QgsAnnotationItemEditOperationRotateItem *rotateOperation = qgis::down_cast< QgsAnnotationItemEditOperationRotateItem * >( operation );
283 mAngle = std::fmod( mAngle + rotateOperation->angle(), 360.0 );
285 }
286
288 break;
289 }
290
292}
293
295{
296 switch ( operation->type() )
297 {
299 {
300 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
301 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( moveOperation->after().clone() ) );
302 }
303
305 {
306 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
307 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( new QgsPoint( mPoint.x() + moveOperation->translationX(), mPoint.y() + moveOperation->translationY() ) ) );
308 }
309
313 break;
314 }
315 return nullptr;
316}
317
319{
320 return mTextFormat;
321}
322
324{
325 mTextFormat = format;
326}
327
329{
330 return mAlignment;
331}
332
334{
335 mAlignment = alignment;
336}
337
339{
340 return mRotationMode;
341}
342
344{
345 mRotationMode = mode;
346}
SymbolRotationMode
Modes for handling how symbol and text entity rotation is handled when maps are rotated.
Definition qgis.h:805
@ RespectMapRotation
Entity is rotated along with the map.
Definition qgis.h:806
@ IgnoreMapRotation
Entity ignores map rotation.
Definition qgis.h:807
@ VertexHandle
Node is a handle for manipulating vertices.
Definition qgis.h:2566
@ CalloutHandle
Node is a handle for manipulating callouts.
Definition qgis.h:2567
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
Definition qgis.h:2523
@ SupportsCallouts
Item supports callouts.
Definition qgis.h:2525
@ SupportsReferenceScale
Item supports reference scale based rendering.
Definition qgis.h:2524
AnnotationItemEditOperationResult
Results from an edit operation on an annotation item.
Definition qgis.h:2577
@ Invalid
Operation has invalid parameters for the item, no change occurred.
Definition qgis.h:2579
@ Success
Item was modified successfully.
Definition qgis.h:2578
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
Definition qgis.h:2580
QFlags< AnnotationItemFlag > AnnotationItemFlags
Annotation item flags.
Definition qgis.h:2528
@ Pixels
Pixels.
Definition qgis.h:5258
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:250
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:111
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:7110
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:6817
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:7091
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6900
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:98