Skip to content

Commit d2f52bf

Browse files
committed
Add threadsafe method to get featuresource from layer
1 parent a6e0e39 commit d2f52bf

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/core/qgsvectorlayerutils.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,34 @@ QgsFeature QgsVectorLayerUtils::duplicateFeature( QgsVectorLayer *layer, const Q
498498
return newFeature;
499499
}
500500

501+
std::unique_ptr<QgsVectorLayerFeatureSource> QgsVectorLayerUtils::getFeatureSource( QWeakPointer<QgsVectorLayer> layer )
502+
{
503+
std::unique_ptr<QgsVectorLayerFeatureSource> featureSource;
504+
505+
auto getFeatureSource = [ layer, &featureSource ]
506+
{
507+
QgsVectorLayer *lyr = layer.data();
508+
509+
if ( lyr )
510+
{
511+
featureSource.reset( new QgsVectorLayerFeatureSource( lyr ) );
512+
}
513+
};
514+
515+
#if QT_VERSION >= QT_VERSION_CHECK( 5, 10, 0 )
516+
// Make sure we only deal with the vector layer on the main thread where it lives.
517+
// Anything else risks a crash.
518+
if ( QThread::currentThread() == qApp->thread() )
519+
getFeatureSource();
520+
else
521+
QMetaObject::invokeMethod( qApp, getFeatureSource, Qt::BlockingQueuedConnection );
522+
#else
523+
getFeatureSource();
524+
#endif
525+
526+
return featureSource;
527+
}
528+
501529
QList<QgsVectorLayer *> QgsVectorLayerUtils::QgsDuplicateFeatureContext::layers() const
502530
{
503531
QList<QgsVectorLayer *> layers;

src/core/qgsvectorlayerutils.h

+12
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include "qgis_core.h"
2020
#include "qgsvectorlayer.h"
2121
#include "qgsgeometry.h"
22+
#include "qgsvectorlayerfeatureiterator.h"
2223

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

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

160172

0 commit comments

Comments
 (0)