Automatically removed attached layer sources when layer is deleted

This commit is contained in:
Sandro Mani 2021-12-15 11:40:17 +01:00
parent 68a1470ea1
commit 792ce7f962
4 changed files with 26 additions and 0 deletions

View File

@ -1273,6 +1273,11 @@ Attaches a file to the project
:return: The path to the file where the contents can be written to.
.. note::
If the attachment file is used as a source for a project layer, the attachment will be removed
automatically when the layer is deleted.
.. versionadded:: 3.22
%End

View File

@ -1341,6 +1341,8 @@ class CORE_EXPORT QgsProject : public QObject, public QgsExpressionContextGenera
* Attaches a file to the project
* \param nameTemplate Any filename template, used as a basename for attachment file, i.e. "myfile.ext"
* \return The path to the file where the contents can be written to.
* \note If the attachment file is used as a source for a project layer, the attachment will be removed
* automatically when the layer is deleted.
* \since QGIS 3.22
*/
QString createAttachedFile( const QString &nameTemplate );

View File

@ -98,6 +98,11 @@ QgsMapLayer::QgsMapLayer( QgsMapLayerType type,
QgsMapLayer::~QgsMapLayer()
{
if ( project() && project()->pathResolver().writePath( mDataSource ).startsWith( "attachment:" ) )
{
project()->removeAttachedFile( mDataSource );
}
delete m3DRenderer;
delete mLegend;
delete mStyleManager;

View File

@ -812,6 +812,13 @@ void TestQgsProject::testAttachmentsQgs()
QVERIFY( p2.attachedFiles().size() == 1 );
QVERIFY( p2.mapLayers().size() == 1 );
QVERIFY( p2.mapLayer( p2.mapLayers().firstKey() )->source() == p2.attachedFiles().first() );
// Verify that attachment file is removed when layer is deleted
QgsMapLayer *p2layer = p2.mapLayer( p2.mapLayers().firstKey() );
QString path = p2layer->source();
QVERIFY( QFile( path ).exists() );
p2.removeMapLayer( p2layer->id() );
QVERIFY( !QFile( path ).exists() );
}
}
@ -882,6 +889,13 @@ void TestQgsProject::testAttachmentsQgz()
QVERIFY( p2.attachedFiles().size() == 1 );
QVERIFY( p2.mapLayers().size() == 1 );
QVERIFY( p2.mapLayer( p2.mapLayers().firstKey() )->source() == p2.attachedFiles().first() );
// Verify that attachment file is removed when layer is deleted
QgsMapLayer *p2layer = p2.mapLayer( p2.mapLayers().firstKey() );
QString path = p2layer->source();
QVERIFY( QFile( path ).exists() );
p2.removeMapLayer( p2layer->id() );
QVERIFY( !QFile( path ).exists() );
}
}