QGIS API Documentation 3.36.0-Maidenhead (09951dc0acf)
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
26 , mText( text )
27 , mPoint( point )
28{
29
30}
31
32Qgis::AnnotationItemFlags QgsAnnotationPointTextItem::flags() const
33{
34 // in truth this should depend on whether the text format is scale dependent or not!
36}
37
39
41{
42 return QStringLiteral( "pointtext" );
43}
44
46{
47 QPointF pt;
48 if ( context.coordinateTransform().isValid() )
49 {
50 double x = mPoint.x();
51 double y = mPoint.y();
52 double z = 0.0;
53 context.coordinateTransform().transformInPlace( x, y, z );
54 pt = QPointF( x, y );
55 }
56 else
57 pt = mPoint.toQPointF();
58
59 context.mapToPixel().transformInPlace( pt.rx(), pt.ry() );
60
61 double angle = mAngle;
62 switch ( mRotationMode )
63 {
65 angle += context.mapToPixel().mapRotation();
66 break;
67
69 break;
70 }
71
72 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
73 QgsTextRenderer::drawText( pt, - angle * M_PI / 180.0,
75 displayText.split( '\n' ), context, mTextFormat );
76}
77
78bool QgsAnnotationPointTextItem::writeXml( QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context ) const
79{
80 element.setAttribute( QStringLiteral( "x" ), qgsDoubleToString( mPoint.x() ) );
81 element.setAttribute( QStringLiteral( "y" ), qgsDoubleToString( mPoint.y() ) );
82 element.setAttribute( QStringLiteral( "text" ), mText );
83 element.setAttribute( QStringLiteral( "angle" ), qgsDoubleToString( mAngle ) );
84 element.setAttribute( QStringLiteral( "alignment" ), QString::number( mAlignment ) );
85 element.setAttribute( QStringLiteral( "rotationMode" ), qgsEnumValueToKey( mRotationMode ) );
86
87 QDomElement textFormatElem = document.createElement( QStringLiteral( "pointTextFormat" ) );
88 textFormatElem.appendChild( mTextFormat.writeXml( document, context ) );
89 element.appendChild( textFormatElem );
90
91 writeCommonProperties( element, document, context );
92 return true;
93}
94
99
100bool QgsAnnotationPointTextItem::readXml( const QDomElement &element, const QgsReadWriteContext &context )
101{
102 const double x = element.attribute( QStringLiteral( "x" ) ).toDouble();
103 const double y = element.attribute( QStringLiteral( "y" ) ).toDouble();
104 mPoint = QgsPointXY( x, y );
105 mText = element.attribute( QStringLiteral( "text" ) );
106 mAngle = element.attribute( QStringLiteral( "angle" ) ).toDouble();
107 mAlignment = static_cast< Qt::Alignment >( element.attribute( QStringLiteral( "alignment" ) ).toInt() );
108 mRotationMode = qgsEnumKeyToValue( element.attribute( QStringLiteral( "rotationMode" ) ), Qgis::SymbolRotationMode::IgnoreMapRotation );
109 const QDomElement textFormatElem = element.firstChildElement( QStringLiteral( "pointTextFormat" ) );
110 if ( !textFormatElem.isNull() )
111 {
112 const QDomNodeList textFormatNodeList = textFormatElem.elementsByTagName( QStringLiteral( "text-style" ) );
113 const QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement();
114 mTextFormat.readXml( textFormatElem, context );
115 }
116
117 readCommonProperties( element, context );
118 return true;
119}
120
122{
123 std::unique_ptr< QgsAnnotationPointTextItem > item = std::make_unique< QgsAnnotationPointTextItem >( mText, mPoint );
124 item->setFormat( mTextFormat );
125 item->setAngle( mAngle );
126 item->setAlignment( mAlignment );
127 item->setRotationMode( mRotationMode );
128 item->copyCommonProperties( this );
129 return item.release();
130}
131
133{
134 return QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x(), mPoint.y() );
135}
136
137QgsRectangle rotateBoundingBoxAroundPoint( double cx, double cy, const QgsRectangle &original, double angleClockwiseDegrees )
138{
139 QTransform t;
140 t.translate( cx, cy );
141 const double angleRadians = -M_PI * angleClockwiseDegrees / 180.0;
142 t.rotateRadians( angleRadians );
143 t.translate( -cx, -cy );
144 const QRectF result = t.mapRect( original.toRectF() );
145 return QgsRectangle( result );
146}
147
149{
150 const QString displayText = QgsExpression::replaceExpressionText( mText, &context.expressionContext(), &context.distanceArea() );
151
152 const double widthInPixels = QgsTextRenderer::textWidth( context, mTextFormat, displayText.split( '\n' ) );
153 const double heightInPixels = QgsTextRenderer::textHeight( context, mTextFormat, displayText.split( '\n' ) );
154
155 // text size has already been calculated using any symbology reference scale factor above -- we need
156 // to temporarily remove the reference scale here or we'll be undoing the scaling
157 QgsScopedRenderContextReferenceScaleOverride resetScaleFactor( context, -1.0 );
158 const double widthInMapUnits = context.convertToMapUnits( widthInPixels, Qgis::RenderUnit::Pixels );
159 const double heightInMapUnits = context.convertToMapUnits( heightInPixels, Qgis::RenderUnit::Pixels );
160
161 double angle = mAngle;
162 switch ( mRotationMode )
163 {
165 angle += context.mapToPixel().mapRotation();
166 break;
167
169 break;
170 }
171
172 QgsRectangle unrotatedRect;
173 switch ( mAlignment & Qt::AlignHorizontal_Mask )
174 {
175 case Qt::AlignRight:
176 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits, mPoint.y(), mPoint.x(), mPoint.y() + heightInMapUnits );
177 break;
178
179 case Qt::AlignHCenter:
180 unrotatedRect = QgsRectangle( mPoint.x() - widthInMapUnits * 0.5, mPoint.y(), mPoint.x() + widthInMapUnits * 0.5, mPoint.y() + heightInMapUnits );
181 break;
182
183 default:
184 unrotatedRect = QgsRectangle( mPoint.x(), mPoint.y(), mPoint.x() + widthInMapUnits, mPoint.y() + heightInMapUnits );
185 break;
186 }
187
188 if ( !qgsDoubleNear( angle, 0 ) )
189 {
190 return rotateBoundingBoxAroundPoint( mPoint.x(), mPoint.y(), unrotatedRect, angle );
191 }
192 else
193 {
194 return unrotatedRect;
195 }
196}
197
198QList<QgsAnnotationItemNode> QgsAnnotationPointTextItem::nodes() const
199{
201}
202
204{
205 switch ( operation->type() )
206 {
208 {
209 QgsAnnotationItemEditOperationMoveNode *moveOperation = dynamic_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
210 mPoint = moveOperation->after();
212 }
213
215 {
217 }
218
220 {
221 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
222 mPoint.setX( mPoint.x() + moveOperation->translationX() );
223 mPoint.setY( mPoint.y() + moveOperation->translationY() );
225 }
226
228 break;
229 }
230
232}
233
235{
236 switch ( operation->type() )
237 {
239 {
240 QgsAnnotationItemEditOperationMoveNode *moveOperation = dynamic_cast< QgsAnnotationItemEditOperationMoveNode * >( operation );
241 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( moveOperation->after().clone() ) );
242 }
243
245 {
246 QgsAnnotationItemEditOperationTranslateItem *moveOperation = qgis::down_cast< QgsAnnotationItemEditOperationTranslateItem * >( operation );
247 return new QgsAnnotationItemEditOperationTransientResults( QgsGeometry( new QgsPoint( mPoint.x() + moveOperation->translationX(), mPoint.y() + moveOperation->translationY() ) ) );
248 }
249
252 break;
253 }
254 return nullptr;
255}
256
258{
259 return mTextFormat;
260}
261
263{
264 mTextFormat = format;
265}
266
268{
269 return mAlignment;
270}
271
272void QgsAnnotationPointTextItem::setAlignment( Qt::Alignment alignment )
273{
274 mAlignment = alignment;
275}
276
278{
279 return mRotationMode;
280}
281
283{
284 mRotationMode = mode;
285}
SymbolRotationMode
Modes for handling how symbol and text entity rotation is handled when maps are rotated.
Definition qgis.h:574
@ RespectMapRotation
Entity is rotated along with the map.
@ IgnoreMapRotation
Entity ignores map rotation.
@ VertexHandle
Node is a handle for manipulating vertices.
@ ScaleDependentBoundingBox
Item's bounding box will vary depending on map scale.
AnnotationItemEditOperationResult
Results from an edit operation on an annotation item.
Definition qgis.h:2020
@ 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...
Abstract base class for annotation item edit operations.
@ TranslateItem
Translate (move) an item.
virtual Type type() const =0
Returns the operation type.
Annotation item edit operation consisting of moving a node.
QgsPoint after() const
Returns the node position after the move occurred (in layer coordinates).
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.
bool writeCommonProperties(QDomElement &element, QDomDocument &document, const QgsReadWriteContext &context) const
Writes common properties from the base class into an XML element.
bool readCommonProperties(const QDomElement &element, const QgsReadWriteContext &context)
Reads common properties from the base class from the given DOM element.
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...
QList< QgsAnnotationItemNode > nodes() const override
Returns the nodes for the item, used for editing the item.
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.
QgsAnnotationItemEditOperationTransientResults * transientEditResults(QgsAbstractAnnotationItemEditOperation *operation) override
Retrieves the results of a transient (in progress) edit operation on the item.
Qgis::AnnotationItemEditOperationResult applyEdit(QgsAbstractAnnotationItemEditOperation *operation) override
Applies an edit operation to the item.
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.
double mapRotation() const
Returns the current map rotation in degrees (clockwise).
void transformInPlace(double &x, double &y) const
Transforms device coordinates to map 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:130
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:120
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:166
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.
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.
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:5354
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:5061
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:5335
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:5144
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