QGIS API Documentation 3.41.0-Master (45a0abf3bec)
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#include "qgstextrenderer.h"
22#include "qgsrendercontext.h"
23#include "qgsapplication.h"
24#include "qgscalloutsregistry.h"
25
28 , mText( text )
29 , mPoint( point )
30{
31
32}
33
41
43
45{
46 return QStringLiteral( "pointtext" );
47}
48
50{
51 QPointF pt;
52 if ( context.coordinateTransform().isValid() )
53 {
54 double x = mPoint.x();
55 double y = mPoint.y();
56 double z = 0.0;
57 context.coordinateTransform().transformInPlace( x, y, z );
58 pt = QPointF( x, y );
59 }
60 else
61 pt = mPoint.toQPointF();
62
63 context.mapToPixel().transformInPlace( pt.rx(), pt.ry() );
64
65 double angle = mAngle;
66 switch ( mRotationMode )
67 {
69 angle += context.mapToPixel().mapRotation();
70 break;
71
73 break;
74 }
75
76 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
77
78 if ( callout() )
79 {
80 const double textWidth = QgsTextRenderer::textWidth(
81 context, mTextFormat, displayText.split( '\n' ) );
82 const double textHeight = QgsTextRenderer::textHeight(
83 context, mTextFormat, displayText.split( '\n' ) );
84
85 QgsCallout::QgsCalloutContext calloutContext;
86 renderCallout( context, QRectF( pt.x(), pt.y() - textHeight, textWidth, textHeight ), angle, calloutContext, feedback );
87 }
88
89 QgsTextRenderer::drawText( pt, - angle * M_PI / 180.0,
91 mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ), context, mTextFormat );
92}
93
94bool QgsAnnotationPointTextItem::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
95{
96 element.setAttribute( QStringLiteral( "x" ), qgsDoubleToString( mPoint.x() ) );
97 element.setAttribute( QStringLiteral( "y" ), qgsDoubleToString( mPoint.y() ) );
98 element.setAttribute( QStringLiteral( "text" ), mText );
99 element.setAttribute( QStringLiteral( "angle" ), qgsDoubleToString( mAngle ) );
100 element.setAttribute( QStringLiteral( "alignment" ), QString::number( mAlignment ) );
101 element.setAttribute( QStringLiteral( "rotationMode" ), qgsEnumValueToKey( mRotationMode ) );
102
103 QDomElement textFormatElem = document.createElement( QStringLiteral( "pointTextFormat" ) );
104 textFormatElem.appendChild( mTextFormat.writeXml( document, context ) );
105 element.appendChild( textFormatElem );
106
107 writeCommonProperties( element, document, context );
108 return true;
109}
110
115
116bool QgsAnnotationPointTextItem::readXml( const QDomElement &element, const QgsReadWriteContext &context )
117{
118 const double x = element.attribute( QStringLiteral( "x" ) ).toDouble();
119 const double y = element.attribute( QStringLiteral( "y" ) ).toDouble();
120 mPoint = QgsPointXY( x, y );
121 mText = element.attribute( QStringLiteral( "text" ) );
122 mAngle = element.attribute( QStringLiteral( "angle" ) ).toDouble();
123 mAlignment = static_cast< Qt::Alignment >( element.attribute( QStringLiteral( "alignment" ) ).toInt() );
124 mRotationMode = qgsEnumKeyToValue( element.attribute( QStringLiteral( "rotationMode" ) ), Qgis::SymbolRotationMode::IgnoreMapRotation );
125 const QDomElement textFormatElem = element.firstChildElement( QStringLiteral( "pointTextFormat" ) );
126 if ( !textFormatElem.isNull() )
127 {
128 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( QStringLiteral( "text-style" ) );
129 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
130 mTextFormat.readXml( textFormatElem, context );
131 }
132
133 readCommonProperties( element, context );
134 return true;
135}
136
138{
139 std::unique_ptr< QgsAnnotationPointTextItem > item = std::make_unique< QgsAnnotationPointTextItem >( mText, mPoint );
140 item->setFormat( mTextFormat );
141 item->setAngle( mAngle );
142 item->setAlignment( mAlignment );
143 item->setRotationMode( mRotationMode );
144 item->copyCommonProperties( this );
145 return item.release();
146}
147
149{
150 return QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x(), mPoint.y() );
151}
152
153QgsRectangle rotateBoundingBoxAroundPoint( double cx, double cy, const QgsRectangle &original, double angleClockwiseDegrees )
154{
155 QTransform t;
156 t.translate( cx, cy );
157 const double angleRadians = -M_PI * angleClockwiseDegrees / 180.0;
158 t.rotateRadians( angleRadians );
159 t.translate( -cx, -cy );
160 const QRectF result = t.mapRect( original.toRectF() );
161 return QgsRectangle( result );
162}
163
165{
166 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
167
168 const double widthInPixels = QgsTextRenderer::textWidth( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ) );
169 const double heightInPixels = QgsTextRenderer::textHeight( context, mTextFormat, mTextFormat.allowHtmlFormatting() ? QStringList{displayText }: displayText.split( '\n' ) );
170
171 // text size has already been calculated using any symbology reference scale factor above -- we need
172 // to temporarily remove the reference scale here or we'll be undoing the scaling
173 QgsScopedRenderContextReferenceScaleOverride resetScaleFactor( context, -1.0 );
174 const double widthInMapUnits = context.convertToMapUnits( widthInPixels, Qgis::RenderUnit::Pixels );
175 const double heightInMapUnits = context.convertToMapUnits( heightInPixels, Qgis::RenderUnit::Pixels );
176
177 double angle = mAngle;
178 switch ( mRotationMode )
179 {
181 angle += context.mapToPixel().mapRotation();
182 break;
183
185 break;
186 }
187
188 QgsRectangle unrotatedRect;
189 switch ( mAlignment & Qt::AlignHorizontal_Mask )
190 {
191 case Qt::AlignRight:
192 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits, mPoint.y(), mPoint.x(), mPoint.y() + heightInMapUnits );
193 break;
194
195 case Qt::AlignHCenter:
196 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits * 0.5, mPoint.y(), mPoint.x() + widthInMapUnits * 0.5, mPoint.y() + heightInMapUnits );
197 break;
198
199 default:
200 unrotatedRect = QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x() + widthInMapUnits, mPoint.y() + heightInMapUnits );
201 break;
202 }
203
204 QgsRectangle textRect;
205 if ( !qgsDoubleNear( angle, 0 ) )
206 {
207 textRect = rotateBoundingBoxAroundPoint( mPoint.x(), mPoint.y(), unrotatedRect, angle );
208 }
209 else
210 {
211 textRect = unrotatedRect;
212 }
213
214 if ( callout() && !calloutAnchor().isEmpty() )
215 {
216 QgsGeometry anchor = calloutAnchor();
217 textRect.combineExtentWith( anchor.boundingBox() );
218 }
219 return textRect;
220}
221
222QList<QgsAnnotationItemNode> QgsAnnotationPointTextItem::nodesV2( const QgsAnnotationItemEditContext &context ) const
223{
224 QList<QgsAnnotationItemNode> res = { QgsAnnotationItemNode( QgsVertexId( 0, 0, 0 ), mPoint, Qgis::AnnotationItemNodeType::VertexHandle )};
225
226 QgsPointXY calloutNodePoint;
227 if ( !calloutAnchor().isEmpty() )
228 {
229 calloutNodePoint = calloutAnchor().asPoint();
230 }
231 else
232 {
233 calloutNodePoint = context.currentItemBounds().center();
234 }
235 res.append( QgsAnnotationItemNode( QgsVertexId( 0, 0, 1 ), calloutNodePoint, Qgis::AnnotationItemNodeType::CalloutHandle ) );
236
237 return res;
238}
239
241{
242 switch ( operation->type() )
243 {
245 {
246 QgsAnnotationItemEditOperationMoveNode *moveOperation = dynamic_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
247 if ( moveOperation->nodeId().vertex == 0 )
248 {
249 mPoint = moveOperation->after();
250 }
251 else if ( moveOperation->nodeId().vertex == 1 )
252 {
253 setCalloutAnchor( QgsGeometry::fromPoint( moveOperation->after() ) );
254 if ( !callout() )
255 {
256 setCallout( QgsApplication::calloutRegistry()->defaultCallout() );
257 }
258 }
260 }
261
263 {
265 }
266
268 {
269 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
270 mPoint.setX( mPoint.x() + moveOperation->translationX() );
271 mPoint.setY( mPoint.y() + moveOperation->translationY() );
273 }
274
276 break;
277 }
278
280}
281
283{
284 switch ( operation->type() )
285 {
287 {
288 QgsAnnotationItemEditOperationMoveNode *moveOperation = dynamic_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
289 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( moveOperation->after().clone() ) );
290 }
291
293 {
294 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
295 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( new QgsPoint( mPoint.x() + moveOperation->translationX(), mPoint.y() + moveOperation->translationY() ) ) );
296 }
297
300 break;
301 }
302 return nullptr;
303}
304
306{
307 return mTextFormat;
308}
309
311{
312 mTextFormat = format;
313}
314
316{
317 return mAlignment;
318}
319
320void QgsAnnotationPointTextItem::setAlignment( Qt::Alignment alignment )
321{
322 mAlignment = alignment;
323}
324
326{
327 return mRotationMode;
328}
329
331{
332 mRotationMode = mode;
333}
SymbolRotationMode
Modes for handling how symbol and text entity rotation is handled when maps are rotated.
Definition qgis.h:750
@ RespectMapRotation
Entity is rotated along with the map.
@ IgnoreMapRotation
Entity ignores map rotation.
@ VertexHandle
Node is a handle for manipulating vertices.
@ CalloutHandle
Node is a handle for manipulating callouts.
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
@ SupportsCallouts
Item supports callouts.
@ SupportsReferenceScale
Item supports reference scale based rendering.
AnnotationItemEditOperationResult
Results from an edit operation on an annotation item.
Definition qgis.h:2351
@ Invalid
Operation has invalid parameters for the item, no change occurred.
@ Success
Item was modified successfully.
@ ItemCleared
The operation results in the item being cleared, and the item should be removed from the layer as a r...
QFlags< AnnotationItemFlag > AnnotationItemFlags
Annotation item flags.
Definition qgis.h:2302
Abstract base class for annotation item edit operations.
@ TranslateItem
Translate (move) an item.
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.
Abstract base class for annotation items which are drawn with QgsAnnotationLayers.
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.
An annotation item which renders a text string at a point location.
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.
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.
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:249
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.
A class to represent a 2D point.
Definition qgspointxy.h:60
void setY(double y)
Sets the y value of the point.
Definition qgspointxy.h:129
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
void setX(double x)
Sets the x value of the point.
Definition qgspointxy.h:119
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:165
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:105
The class is used as a container of context for various read/write operations on other objects.
A rectangle specified with double values.
QRectF toRectF() const
Returns a QRectF with same coordinates as the rectangle.
QgsPointXY center() const
Returns the center point of the rectangle.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
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.
void readXml(const QDomElement &elem, const QgsReadWriteContext &context)
Read settings from a DOM element.
bool allowHtmlFormatting() const
Returns true if text should be treated as a HTML document and HTML tags should be used for formatting...
QDomElement writeXml(QDomDocument &doc, const QgsReadWriteContext &context) const
Write settings into a DOM element.
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:6168
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:5875
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:6149
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:5958
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