Skip to content

Commit

Permalink
Add threadsafe method to get featuresource from layer
Browse files Browse the repository at this point in the history
  • Loading branch information
m-kuhn committed Sep 4, 2018
1 parent a6e0e39 commit d2f52bf
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/core/qgsvectorlayerutils.cpp
Expand Up @@ -498,6 +498,34 @@ QgsFeature QgsVectorLayerUtils::duplicateFeature( QgsVectorLayer *layer, const Q
return newFeature;
}

std::unique_ptr<QgsVectorLayerFeatureSource> QgsVectorLayerUtils::getFeatureSource( QWeakPointer<QgsVectorLayer> layer )
{
std::unique_ptr<QgsVectorLayerFeatureSource> featureSource;

auto getFeatureSource = [ layer, &featureSource ]
{
QgsVectorLayer *lyr = layer.data();

if ( lyr )
{
featureSource.reset( new QgsVectorLayerFeatureSource( lyr ) );
}
};

#if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 )
// Make sure we only deal with the vector layer on the main thread where it lives.
// Anything else risks a crash.
if ( QThread::currentThread() == qApp->thread() )
getFeatureSource();
else
QMetaObject::invokeMethod( qApp, getFeatureSource, Qt::BlockingQueuedConnection );
#else
getFeatureSource();
#endif

return featureSource;
}

QList<QgsVectorLayer *> QgsVectorLayerUtils::QgsDuplicateFeatureContext::layers() const
{
QList<QgsVectorLayer *> layers;
Expand Down
12 changes: 12 additions & 0 deletions src/core/qgsvectorlayerutils.h
Expand Up @@ -19,6 +19,7 @@
#include "qgis_core.h"
#include "qgsvectorlayer.h"
#include "qgsgeometry.h"
#include "qgsvectorlayerfeatureiterator.h"

/**
* \ingroup core
Expand Down Expand Up @@ -155,6 +156,17 @@ class CORE_EXPORT QgsVectorLayerUtils
*/
static QgsFeature duplicateFeature( QgsVectorLayer *layer, const QgsFeature &feature, QgsProject *project, int depth, QgsDuplicateFeatureContext &duplicateFeatureContext SIP_OUT );

/**
* Gets the feature source from a weak QgsVectorLayer pointer.
* This method is thread-safe but will block the main thread for execution. Executing it from the main
* thread is safe too.
* This should be used in scenarios, where a ``QWeakPointer<QgsVectorLayer>`` is kept in a thread
* and features should be fetched from this layer. Using the layer directly is not safe to do.
*
* \note Requires Qt >= 5.10 to make use of the thread-safe implementation
* \since QGIS 3.4
*/
static std::unique_ptr<QgsVectorLayerFeatureSource> getFeatureSource( QWeakPointer<QgsVectorLayer> layer ) SIP_SKIP;
};


Expand Down

0 comments on commit d2f52bf

Please sign in to comment.