QGIS API Documentation  3.4.15-Madeira (e83d02e274)
qgsquickutils.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsquickutils.cpp
3  --------------------------------------
4  Date : Nov 2017
5  Copyright : (C) 2017 by Peter Petrik
6  Email : zilolv at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 #include <QDesktopWidget>
16 #include <QString>
17 
18 #include "qgis.h"
20 #include "qgscoordinatetransform.h"
21 #include "qgsdistancearea.h"
22 #include "qgslogger.h"
23 #include "qgsvectorlayer.h"
24 #include "qgsfeature.h"
25 
27 #include "qgsquickmapsettings.h"
28 #include "qgsquickutils.h"
29 #include "qgsunittypes.h"
30 
31 
32 QgsQuickUtils::QgsQuickUtils( QObject *parent )
33  : QObject( parent )
34  , mScreenDensity( calculateScreenDensity() )
35 {
36 }
37 
42 {
44 }
45 
46 QgsPointXY QgsQuickUtils::pointXY( double x, double y )
47 {
48  return QgsPointXY( x, y );
49 }
50 
51 QgsPoint QgsQuickUtils::point( double x, double y, double z, double m )
52 {
53  return QgsPoint( x, y, z, m );
54 }
55 
56 QgsPoint QgsQuickUtils::coordinateToPoint( const QGeoCoordinate &coor )
57 {
58  return QgsPoint( coor.longitude(), coor.latitude(), coor.altitude() );
59 }
60 
62  const QgsCoordinateReferenceSystem &destCrs,
63  const QgsCoordinateTransformContext &context,
64  const QgsPointXY &srcPoint )
65 {
66  QgsCoordinateTransform mTransform( srcCrs, destCrs, context );
67  QgsPointXY pt = mTransform.transform( srcPoint );
68  return pt;
69 }
70 
71 double QgsQuickUtils::screenUnitsToMeters( QgsQuickMapSettings *mapSettings, int baseLengthPixels )
72 {
73  if ( mapSettings == nullptr ) return 0.0;
74 
75  QgsDistanceArea mDistanceArea;
76  mDistanceArea.setEllipsoid( QStringLiteral( "WGS84" ) );
77  mDistanceArea.setSourceCrs( mapSettings->destinationCrs(), mapSettings->transformContext() );
78 
79  // calculate the geographic distance from the central point of extent
80  // to the specified number of points on the right side
81  QSize s = mapSettings->outputSize();
82  QPoint pointCenter( s.width() / 2, s.height() / 2 );
83  QgsPointXY p1 = mapSettings->screenToCoordinate( pointCenter );
84  QgsPointXY p2 = mapSettings->screenToCoordinate( pointCenter + QPoint( baseLengthPixels, 0 ) );
85  return mDistanceArea.measureLine( p1, p2 );
86 }
87 
88 bool QgsQuickUtils::fileExists( const QString &path )
89 {
90  QFileInfo check_file( path );
91  // check if file exists and if yes: Is it really a file and no directory?
92  return ( check_file.exists() && check_file.isFile() );
93 }
94 
95 QString QgsQuickUtils::getFileName( const QString &path )
96 {
97  QFileInfo fileInfo( path );
98  QString filename( fileInfo.fileName() );
99  return filename;
100 }
101 
102 void QgsQuickUtils::logMessage( const QString &message, const QString &tag, Qgis::MessageLevel level )
103 {
104  QgsMessageLog::logMessage( message, tag, level );
105 }
106 
108 {
109  return QgsQuickFeatureLayerPair( feature, layer );
110 }
111 
112 const QUrl QgsQuickUtils::getThemeIcon( const QString &name )
113 {
114  QString path = QStringLiteral( "qrc:/%1.svg" ).arg( name );
115  QgsDebugMsg( QStringLiteral( "Using icon %1 from %2" ).arg( name, path ) );
116  return QUrl( path );
117 }
118 
119 const QUrl QgsQuickUtils::getEditorComponentSource( const QString &widgetName )
120 {
121  QString path( "qgsquick%1.qml" );
122  QStringList supportedWidgets = { QStringLiteral( "textedit" ),
123  QStringLiteral( "valuemap" ),
124  QStringLiteral( "checkbox" ),
125  QStringLiteral( "externalresource" ),
126  QStringLiteral( "datetime" )
127  };
128  if ( supportedWidgets.contains( widgetName ) )
129  {
130  return QUrl( path.arg( widgetName ) );
131  }
132  else
133  {
134  return QUrl( path.arg( QStringLiteral( "textedit" ) ) );
135  }
136 }
137 
139  const QgsPoint &point,
141  int decimals,
142  QgsCoordinateFormatter::FormatFlags flags )
143 {
144  return QgsCoordinateFormatter::format( point, format, decimals, flags );
145 }
146 
147 QString QgsQuickUtils::formatDistance( double distance,
149  int decimals,
151 {
152  double destDistance;
153  QgsUnitTypes::DistanceUnit destUnits;
154 
155  humanReadableDistance( distance, units, destSystem, destDistance, destUnits );
156 
157  return QStringLiteral( "%1 %2" )
158  .arg( QString::number( destDistance, 'f', decimals ) )
159  .arg( QgsUnitTypes::toAbbreviatedString( destUnits ) );
160 }
161 
162 
165  double &destDistance, QgsUnitTypes::DistanceUnit &destUnits )
166 {
167  if ( ( destSystem == QgsUnitTypes::MetricSystem ) || ( destSystem == QgsUnitTypes::UnknownSystem ) )
168  {
169  return formatToMetricDistance( srcDistance, srcUnits, destDistance, destUnits );
170  }
171  else if ( destSystem == QgsUnitTypes::ImperialSystem )
172  {
173  return formatToImperialDistance( srcDistance, srcUnits, destDistance, destUnits );
174  }
175  else if ( destSystem == QgsUnitTypes::USCSSystem )
176  {
177  return formatToUSCSDistance( srcDistance, srcUnits, destDistance, destUnits );
178  }
179  else
180  {
181  Q_ASSERT( false ); //should never happen
182  }
183 }
184 
185 void QgsQuickUtils::formatToMetricDistance( double srcDistance,
187  double &destDistance,
188  QgsUnitTypes::DistanceUnit &destUnits )
189 {
190  double dist = srcDistance * QgsUnitTypes::fromUnitToUnitFactor( srcUnits, QgsUnitTypes::DistanceMillimeters );
191  if ( dist < 0 )
192  {
193  destDistance = 0;
195  return;
196  }
197 
199  if ( dist > mmToKm )
200  {
201  destDistance = dist / mmToKm;
203  return;
204  }
205 
207  if ( dist > mmToM )
208  {
209  destDistance = dist / mmToM;
210  destUnits = QgsUnitTypes::DistanceMeters;
211  return;
212  }
213 
215  if ( dist > mmToCm )
216  {
217  destDistance = dist / mmToCm;
219  return;
220  }
221 
222  destDistance = dist;
224 }
225 
226 void QgsQuickUtils::formatToImperialDistance( double srcDistance,
228  double &destDistance,
229  QgsUnitTypes::DistanceUnit &destUnits )
230 {
231  double dist = srcDistance * QgsUnitTypes::fromUnitToUnitFactor( srcUnits, QgsUnitTypes::DistanceFeet );
232  if ( dist < 0 )
233  {
234  destDistance = 0;
235  destUnits = QgsUnitTypes::DistanceFeet;
236  return;
237  }
238 
240  if ( dist > feetToMile )
241  {
242  destDistance = dist / feetToMile;
243  destUnits = QgsUnitTypes::DistanceMiles;
244  return;
245  }
246 
248  if ( dist > feetToYard )
249  {
250  destDistance = dist / feetToYard;
251  destUnits = QgsUnitTypes::DistanceYards;
252  return;
253  }
254 
255  destDistance = dist;
256  destUnits = QgsUnitTypes::DistanceFeet;
257  return;
258 }
259 
260 void QgsQuickUtils::formatToUSCSDistance( double srcDistance,
262  double &destDistance,
263  QgsUnitTypes::DistanceUnit &destUnits )
264 {
265  double dist = srcDistance * QgsUnitTypes::fromUnitToUnitFactor( srcUnits, QgsUnitTypes::DistanceFeet );
266  if ( dist < 0 )
267  {
268  destDistance = 0;
269  destUnits = QgsUnitTypes::DistanceFeet;
270  return;
271  }
272 
274  if ( dist > feetToMile )
275  {
276  destDistance = dist / feetToMile;
278  return;
279  }
280 
282  if ( dist > feetToYard )
283  {
284  destDistance = dist / feetToYard;
285  destUnits = QgsUnitTypes::DistanceYards;
286  return;
287  }
288 
289  destDistance = dist;
290  destUnits = QgsUnitTypes::DistanceFeet;
291  return;
292 }
293 
295 {
296  QRect rec = QApplication::desktop()->screenGeometry();
297  int dpiX = QApplication::desktop()->physicalDpiX();
298  int dpiY = QApplication::desktop()->physicalDpiY();
299  int height = rec.height();
300  int width = rec.width();
301  double sizeX = static_cast<double>( width ) / dpiX * 25.4;
302  double sizeY = static_cast<double>( height ) / dpiY * 25.4;
303 
304  QString msg;
305  msg += tr( "screen resolution: %1x%2 px\n" ).arg( width ).arg( height );
306  msg += tr( "screen DPI: %1x%2\n" ).arg( dpiX ).arg( dpiY );
307  msg += tr( "screen size: %1x%2 mm\n" ).arg( QString::number( sizeX, 'f', 0 ), QString::number( sizeY, 'f', 0 ) );
308  msg += tr( "screen density: %1" ).arg( mScreenDensity );
309  return msg;
310 }
311 
313 {
314  return mScreenDensity;
315 }
316 
317 qreal QgsQuickUtils::calculateScreenDensity()
318 {
319  // calculate screen density for calculation of real pixel sizes from density-independent pixels
320  int dpiX = QApplication::desktop()->physicalDpiX();
321  int dpiY = QApplication::desktop()->physicalDpiY();
322  int dpi = dpiX < dpiY ? dpiX : dpiY; // In case of asymmetrical DPI. Improbable
323  return dpi / 160.; // 160 DPI is baseline for density-independent pixels in Android
324 }
static Q_INVOKABLE const QUrl getEditorComponentSource(const QString &widgetName)
Returns url to field editor component for a feature form.
static Q_INVOKABLE QgsPoint coordinateToPoint(const QGeoCoordinate &coor)
Converts QGeoCoordinate to QgsPoint.
SystemOfMeasurement
Systems of unit measurement.
Definition: qgsunittypes.h:43
static Q_INVOKABLE QgsCoordinateReferenceSystem coordinateReferenceSystemFromEpsgId(long epsg)
Creates crs from epsg code in QML.
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
QgsPointXY transform(const QgsPointXY &point, TransformDirection direction=ForwardTransform) const SIP_THROW(QgsCsException)
Transform the point from the source CRS to the destination CRS.
A class to represent a 2D point.
Definition: qgspointxy.h:43
static Q_INVOKABLE QgsPoint point(double x, double y, double z=std::numeric_limits< double >::quiet_NaN(), double m=std::numeric_limits< double >::quiet_NaN())
Creates QgsPoint in QML.
qreal screenDensity() const
"dp" is useful for building building components that work well with different screen densities...
Q_INVOKABLE QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:55
MessageLevel
Level for messages This will be used both for message log and message bar in application.
Definition: qgis.h:79
The QgsQuickMapSettings class encapsulates QgsMapSettings class to offer settings of configuration of...
static Q_INVOKABLE double screenUnitsToMeters(QgsQuickMapSettings *mapSettings, int baseLengthPixels)
Calculates the distance in meter representing baseLengthPixels pixels on the screen based on the curr...
Format
Available formats for displaying coordinates.
Q_INVOKABLE QgsPoint screenToCoordinate(const QPointF &point) const
Convert a screen coordinate to a map coordinate.
British Imperial.
Definition: qgsunittypes.h:47
static Q_INVOKABLE QgsPointXY transformPoint(const QgsCoordinateReferenceSystem &srcCrs, const QgsCoordinateReferenceSystem &destCrs, const QgsCoordinateTransformContext &context, const QgsPointXY &srcPoint)
Transforms point between different crs from QML.
static Q_INVOKABLE QgsCoordinateReferenceSystem fromEpsgId(long epsg)
Creates a CRS from a given EPSG ID.
static Q_INVOKABLE QString toAbbreviatedString(QgsUnitTypes::DistanceUnit unit)
Returns a translated abbreviation representing a distance unit.
QString dumpScreenInfo() const
Returns a string with information about screen size and resolution - useful for debugging.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Unknown system of measurement.
Definition: qgsunittypes.h:45
static void humanReadableDistance(double srcDistance, QgsUnitTypes::DistanceUnit srcUnits, QgsUnitTypes::SystemOfMeasurement destSystem, double &destDistance, QgsUnitTypes::DistanceUnit &destUnits)
Converts distance to human readable distance in destination system of measurement.
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
static Q_INVOKABLE QString getFileName(const QString &path)
Extracts filename from path.
International System of Units (SI)
Definition: qgsunittypes.h:46
Contains information about the context in which a coordinate transform is executed.
static Q_INVOKABLE const QUrl getThemeIcon(const QString &name)
Returns QUrl to image from library&#39;s /images folder.
QgsQuickUtils(QObject *parent=nullptr)
Create new utilities.
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:37
United States customary system.
Definition: qgsunittypes.h:48
DistanceUnit
Units of distance.
Definition: qgsunittypes.h:53
QgsCoordinateReferenceSystem destinationCrs
CRS of destination coordinate reference system.
QSize outputSize
The size of the resulting map image.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations...
This class represents a coordinate reference system (CRS).
Class for doing transforms between two map coordinate systems.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
static Q_INVOKABLE QString formatDistance(double distance, QgsUnitTypes::DistanceUnit units, int decimals, QgsUnitTypes::SystemOfMeasurement destSystem=QgsUnitTypes::MetricSystem)
Converts distance to human readable distance.
static Q_INVOKABLE QgsQuickFeatureLayerPair featureFactory(const QgsFeature &feature, QgsVectorLayer *layer=nullptr)
QgsQuickFeatureLayerPair factory for tuple of QgsFeature and QgsVectorLayer used in QgsQUick library...
Pair of QgsFeature and QgsVectorLayer.
static Q_INVOKABLE QgsPointXY pointXY(double x, double y)
Creates QgsPointXY in QML.
Terrestrial miles.
Definition: qgsunittypes.h:60
static Q_INVOKABLE QString formatPoint(const QgsPoint &point, QgsCoordinateFormatter::Format format=QgsCoordinateFormatter::FormatPair, int decimals=3, QgsCoordinateFormatter::FormatFlags flags=QgsCoordinateFormatter::FlagDegreesUseStringSuffix)
Formats a point according to the specified parameters.
static Q_INVOKABLE double fromUnitToUnitFactor(QgsUnitTypes::DistanceUnit fromUnit, QgsUnitTypes::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
Represents a vector layer which manages a vector based data sets.
static Q_INVOKABLE bool fileExists(const QString &path)
Returns whether file on path exists.
static Q_INVOKABLE void logMessage(const QString &message, const QString &tag=QString("QgsQuick"), Qgis::MessageLevel level=Qgis::Warning)
Log message in QgsMessageLog.
static QString format(const QgsPointXY &point, Format format, int precision=12, FormatFlags flags=FlagDegreesUseStringSuffix)
Formats a point according to the specified parameters.