Skip to content
Permalink
Browse files

Merge pull request #40745 from m-kuhn/qgsmaplayer_project

Add QgsMapLayer::project() utility method
  • Loading branch information
m-kuhn committed Dec 28, 2020
2 parents 9348e75 + 73e385f commit fcd98861bd3afe6588acccdfc52af957a75018c7
@@ -1488,6 +1488,14 @@ Sets the coordinate transform context to ``transformContext``
sipRes = PyUnicode_FromString( str.toUtf8().constData() );
%End

QgsProject *project() const;
%Docstring
Returns the parent project if this map layer is added to a project.
Otherwise returns ``None``

.. versionadded:: 3.18
%End

signals:

void beforeResolveReferences( QgsProject *project );
@@ -1981,6 +1981,15 @@ void QgsMapLayer::setRefreshOnNotifyEnabled( bool enabled )
mIsRefreshOnNofifyEnabled = enabled;
}

QgsProject *QgsMapLayer::project() const
{
if ( QgsMapLayerStore *store = qobject_cast<QgsMapLayerStore *>( parent() ) )
{
return qobject_cast<QgsProject *>( store->parent() );
}
return nullptr;
}

void QgsMapLayer::onNotifiedTriggerRepaint( const QString &message )
{
if ( refreshOnNotifyMessage().isEmpty() || refreshOnNotifyMessage() == message )
@@ -1335,6 +1335,14 @@ class CORE_EXPORT QgsMapLayer : public QObject
% End
#endif

/**
* Returns the parent project if this map layer is added to a project.
* Otherwise returns NULLPTR
*
* \since QGIS 3.18
*/
QgsProject *project() const;

signals:

/**
@@ -15,6 +15,7 @@
import tempfile
import glob
import shutil
import sip

from qgis.core import (QgsReadWriteContext,
QgsVectorLayer,
@@ -185,6 +186,20 @@ def testIsTemporary(self):
self.assertTrue(rl.isValid())
self.assertTrue(rl.isTemporary())

def testQgsMapLayerProject(self):
layer = QgsVectorLayer(os.path.join(TEST_DATA_DIR, 'points.shp'), "layer", "ogr")
self.assertIsNone(layer.project())
project = QgsProject()
project.addMapLayer(layer)
self.assertEqual(layer.project(), project)
project2 = QgsProject()
project2.addMapLayer(layer)
self.assertEqual(layer.project(), project2)
project.removeMapLayer(layer)
self.assertFalse(sip.isdeleted(layer))
project2.removeMapLayer(layer)
self.assertTrue(sip.isdeleted(layer))


if __name__ == '__main__':
unittest.main()

0 comments on commit fcd9886

Please sign in to comment.
You can’t perform that action at this time.