QGIS API Documentation 3.99.0-Master (26c88405ac0)
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
29 , mText( text )
30 , mPoint( point )
31{
32
33}
34
42
44
46{
47 return QStringLiteral( "pointtext" );
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(
82 context, mTextFormat, displayText.split( '\n' ) );
83 const double textHeight = QgsTextRenderer::textHeight(
84 context, mTextFormat, displayText.split( '\n' ) );
85
86 QgsCallout::QgsCalloutContext calloutContext;
87 renderCallout( context, QRectF( pt.x(), pt.y() - textHeight, textWidth, textHeight ), angle, calloutContext, feedback );
88 }
89
90 QgsTextRenderer::drawText( pt, - angle * M_PI / 180.0,
92 mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ), context, mTextFormat );
93}
94
95bool QgsAnnotationPointTextItem::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
96{
97 element.setAttribute( QStringLiteral( "x" ), qgsDoubleToString( mPoint.x() ) );
98 element.setAttribute( QStringLiteral( "y" ), qgsDoubleToString( mPoint.y() ) );
99 element.setAttribute( QStringLiteral( "text" ), mText );
100 element.setAttribute( QStringLiteral( "angle" ), qgsDoubleToString( mAngle ) );
101 element.setAttribute( QStringLiteral( "alignment" ), QString::number( mAlignment ) );
102 element.setAttribute( QStringLiteral( "rotationMode" ), qgsEnumValueToKey( mRotationMode ) );
103
104 QDomElement textFormatElem = document.createElement( QStringLiteral( "pointTextFormat" ) );
105 textFormatElem.appendChild( mTextFormat.writeXml( document, context ) );
106 element.appendChild( textFormatElem );
107
108 writeCommonProperties( element, document, context );
109 return true;
110}
111
116
117bool QgsAnnotationPointTextItem::readXml( const QDomElement &element, const QgsReadWriteContext &context )
118{
119 const double x = element.attribute( QStringLiteral( "x" ) ).toDouble();
120 const double y = element.attribute( QStringLiteral( "y" ) ).toDouble();
121 mPoint = QgsPointXY( x, y );
122 mText = element.attribute( QStringLiteral( "text" ) );
123 mAngle = element.attribute( QStringLiteral( "angle" ) ).toDouble();
124 mAlignment = static_cast< Qt::Alignment >( element.attribute( QStringLiteral( "alignment" ) ).toInt() );
125 mRotationMode = qgsEnumKeyToValue( element.attribute( QStringLiteral( "rotationMode" ) ), Qgis::SymbolRotationMode::IgnoreMapRotation );
126 const QDomElement textFormatElem = element.firstChildElement( QStringLiteral( "pointTextFormat" ) );
127 if ( !textFormatElem.isNull() )
128 {
129 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( QStringLiteral( "text-style" ) );
130 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
131 mTextFormat.readXml( textFormatElem, context );
132 }
133
134 readCommonProperties( element, context );
135 return true;
136}
137
139{
140 auto item = std::make_unique< QgsAnnotationPointTextItem >( mText, mPoint );
141 item->setFormat( mTextFormat );
142 item->setAngle( mAngle );
143 item->setAlignment( mAlignment );
144 item->setRotationMode( mRotationMode );
145 item->copyCommonProperties( this );
146 return item.release();
147}
148
150{
151 return QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x(), mPoint.y() );
152}
153
154QgsRectangle rotateBoundingBoxAroundPoint( double cx, double cy, const QgsRectangle &original, double angleClockwiseDegrees )
155{
156 QTransform t;
157 t.translate( cx, cy );
158 const double angleRadians = -M_PI * angleClockwiseDegrees / 180.0;
159 t.rotateRadians( angleRadians );
160 t.translate( -cx, -cy );
161 const QRectF result = t.mapRect( original.toRectF() );
162 return QgsRectangle( result );
163}
164
166{
167 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
168
169 const double widthInPixels = QgsTextRenderer::textWidth( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ) );
170 const double heightInPixels = QgsTextRenderer::textHeight( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ) );
171
172 // text size has already been calculated using any symbology reference scale factor above -- we need
173 // to temporarily remove the reference scale here or we'll be undoing the scaling
174 QgsScopedRenderContextReferenceScaleOverride resetScaleFactor( context, -1.0 );
175 const double widthInMapUnits = context.convertToMapUnits( widthInPixels, Qgis::RenderUnit::Pixels );
176 const double heightInMapUnits = context.convertToMapUnits( heightInPixels, Qgis::RenderUnit::Pixels );
177
178 double angle = mAngle;
179 switch ( mRotationMode )
180 {
182 angle += context.mapToPixel().mapRotation();
183 break;
184
186 break;
187 }
188
189 QgsRectangle unrotatedRect;
190 switch ( mAlignment & Qt::AlignHorizontal_Mask )
191 {
192 case Qt::AlignRight:
193 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits, mPoint.y(), mPoint.x(), mPoint.y() + heightInMapUnits );
194 break;
195
196 case Qt::AlignHCenter:
197 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits * 0.5, mPoint.y(), mPoint.x() + widthInMapUnits * 0.5, mPoint.y() + heightInMapUnits );
198 break;
199
200 default:
201 unrotatedRect = QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x() + widthInMapUnits, mPoint.y() + heightInMapUnits );
202 break;
203 }
204
205 QgsRectangle textRect;
206 if ( !qgsDoubleNear( angle, 0 ) )
207 {
208 textRect = rotateBoundingBoxAroundPoint( mPoint.x(), mPoint.y(), unrotatedRect, angle );
209 }
210 else
211 {
212 textRect = unrotatedRect;
213 }
214
215 if ( callout() && !calloutAnchor().isEmpty() )
216 {
217 QgsGeometry anchor = calloutAnchor();
218 textRect.combineExtentWith( anchor.boundingBox() );
219 }
220 return textRect;
221}
222
223QList<QgsAnnotationItemNode> QgsAnnotationPointTextItem::nodesV2( const QgsAnnotationItemEditContext &context ) const
224{
225 QList<QgsAnnotationItemNode> res = { QgsAnnotationItemNode( QgsVertexId( 0, 0, 0 ), mPoint, Qgis::AnnotationItemNodeType::VertexHandle )};
226
227 QgsPointXY calloutNodePoint;
228 if ( !calloutAnchor().isEmpty() )
229 {
230 calloutNodePoint = calloutAnchor().asPoint();
231 }
232 else
233 {
234 calloutNodePoint = context.currentItemBounds().center();
235 }
236 res.append( QgsAnnotationItemNode( QgsVertexId( 0, 0, 1 ), calloutNodePoint, Qgis::AnnotationItemNodeType::CalloutHandle ) );
237
238 return res;
239}
240
242{
243 switch ( operation->type() )
244 {
246 {
247 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
248 if ( moveOperation->nodeId().vertex == 0 )
249 {
250 mPoint = moveOperation->after();
251 }
252 else if ( moveOperation->nodeId().vertex == 1 )
253 {
254 setCalloutAnchor( QgsGeometry::fromPoint( moveOperation->after() ) );
255 if ( !callout() )
256 {
257 setCallout( QgsApplication::calloutRegistry()->defaultCallout() );
258 }
259 }
261 }
262
264 {
266 }
267
269 {
270 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
271 mPoint.setX( mPoint.x() + moveOperation->translationX() );
272 mPoint.setY( mPoint.y() + moveOperation->translationY() );
274 }
275
277 break;
278 }
279
281}
282
284{
285 switch ( operation->type() )
286 {
288 {
289 QgsAnnotationItemEditOperationMoveNode *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
290 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( moveOperation->after().clone() ) );
291 }
292
294 {
295 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
296 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( new QgsPoint( mPoint.x() + moveOperation->translationX(), mPoint.y() + moveOperation->translationY() ) ) );
297 }
298
301 break;
302 }
303 return nullptr;
304}
305
307{
308 return mTextFormat;
309}
310
312{
313 mTextFormat = format;
314}
315
317{
318 return mAlignment;
319}
320
322{
323 mAlignment = alignment;
324}
325
327{
328 return mRotationMode;
329}
330
332{
333 mRotationMode = mode;
334}
SymbolRotationMode
Modes for handling how symbol and text entity rotation is handled when maps are rotated.
Definition qgis.h:786
@ RespectMapRotation
Entity is rotated along with the map.
Definition qgis.h:787
@ IgnoreMapRotation
Entity ignores map rotation.
Definition qgis.h:788
@ VertexHandle
Node is a handle for manipulating vertices.
Definition qgis.h:2508
@ CalloutHandle
Node is a handle for manipulating callouts.
Definition qgis.h:2509
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
Definition qgis.h:2465
@ SupportsCallouts
Item supports callouts.
Definition qgis.h:2467
@ SupportsReferenceScale
Item supports reference scale based rendering.
Definition qgis.h:2466
AnnotationItemEditOperationResult
Results from an edit operation on an annotation item.
Definition qgis.h:2519
@ Invalid
Operation has invalid parameters for the item, no change occurred.
Definition qgis.h:2521
@ Success
Item was modified successfully.
Definition qgis.h:2520
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
Definition qgis.h:2522
QFlags< AnnotationItemFlag > AnnotationItemFlags
Annotation item flags.
Definition qgis.h:2470
@ Pixels
Pixels.
Definition qgis.h:5186
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.
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:60
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition qgspoint.cpp:108
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:6817
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:6524
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:6798
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
QgsRectangle rotateBoundingBoxAroundPoint(double cx, double cy, const QgsRectangle &original, double angleClockwiseDegrees)
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30
int vertex
Vertex number.
Definition qgsvertexid.h:94