Merge pull request #40745 from m-kuhn/qgsmaplayer_project

Add QgsMapLayer::project() utility method
This commit is contained in:
Matthias Kuhn 2020-12-28 23:31:08 +01:00 committed by GitHub
commit fcd98861bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 40 additions and 0 deletions

View File

@ -1488,6 +1488,14 @@ Sets the coordinate transform context to ``transformContext``
sipRes = PyUnicode_FromString( str.toUtf8().constData() ); sipRes = PyUnicode_FromString( str.toUtf8().constData() );
%End %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: signals:
void beforeResolveReferences( QgsProject *project ); void beforeResolveReferences( QgsProject *project );

View File

@ -1981,6 +1981,15 @@ void QgsMapLayer::setRefreshOnNotifyEnabled( bool enabled )
mIsRefreshOnNofifyEnabled = 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 ) void QgsMapLayer::onNotifiedTriggerRepaint( const QString &message )
{ {
if ( refreshOnNotifyMessage().isEmpty() || refreshOnNotifyMessage() == message ) if ( refreshOnNotifyMessage().isEmpty() || refreshOnNotifyMessage() == message )

View File

@ -1335,6 +1335,14 @@ class CORE_EXPORT QgsMapLayer : public QObject
% End % End
#endif #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: signals:
/** /**

View File

@ -15,6 +15,7 @@ import qgis # NOQA
import tempfile import tempfile
import glob import glob
import shutil import shutil
import sip
from qgis.core import (QgsReadWriteContext, from qgis.core import (QgsReadWriteContext,
QgsVectorLayer, QgsVectorLayer,
@ -185,6 +186,20 @@ class TestQgsMapLayer(unittest.TestCase):
self.assertTrue(rl.isValid()) self.assertTrue(rl.isValid())
self.assertTrue(rl.isTemporary()) 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__': if __name__ == '__main__':
unittest.main() unittest.main()