Add method to launder layer names to get them into a format

suitable for typical database layer naming
This commit is contained in:
Nyall Dawson 2022-07-21 13:46:26 +10:00
parent 567315d658
commit 60bb4b321b
4 changed files with 40 additions and 0 deletions

View File

@ -66,6 +66,18 @@ result list.
.. versionadded:: 3.26
%End
static QString launderLayerName( const QString &name );
%Docstring
Launders a layer's name, converting it into a format which is general suitable for
file names or database layer names.
Specifically this method:
- Converts the name to lowercase
- Replaces spaces by underscore characters
.. versionadded:: 3.28
%End
};

View File

@ -26,6 +26,7 @@
#include "qgslogger.h"
#include "qgsmaplayer.h"
#include "qgscoordinatetransform.h"
#include <QRegularExpression>
QgsRectangle QgsMapLayerUtils::combinedExtent( const QList<QgsMapLayer *> &layers, const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &transformContext )
{
@ -154,3 +155,15 @@ QList<QgsMapLayer *> QgsMapLayerUtils::sortLayersByType( const QList<QgsMapLayer
} );
return res;
}
QString QgsMapLayerUtils::launderLayerName( const QString &name )
{
QString laundered = name.toLower();
const thread_local QRegularExpression sRxSwapChars( QStringLiteral( "\\s" ) );
laundered.replace( sRxSwapChars, QStringLiteral( "_" ) );
const thread_local QRegularExpression sRxRemoveChars( QStringLiteral( "[^a-zA-Z0-9_]" ) );
laundered.replace( sRxRemoveChars, QString() );
return laundered;
}

View File

@ -80,6 +80,18 @@ class CORE_EXPORT QgsMapLayerUtils
*/
static QList< QgsMapLayer * > sortLayersByType( const QList< QgsMapLayer * > &layers, const QList< QgsMapLayerType > &order );
/**
* Launders a layer's name, converting it into a format which is general suitable for
* file names or database layer names.
*
* Specifically this method:
*
* - Converts the name to lowercase
* - Replaces spaces by underscore characters
*
* \since QGIS 3.28
*/
static QString launderLayerName( const QString &name );
};

View File

@ -159,6 +159,9 @@ class TestQgsMapLayerUtils(unittest.TestCase):
self.assertEqual(QgsMapLayerUtils.sortLayersByType([vl1, rl1, gp1, vl2], [QgsMapLayerType.AnnotationLayer]),
[vl1, rl1, gp1, vl2])
def test_launder_layer_name(self):
self.assertEqual(QgsMapLayerUtils.launderLayerName('abc Def4_a.h%'), 'abc_def4_ah')
if __name__ == '__main__':
unittest.main()