QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsprocessingfieldmapwidgetwrapper.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsprocessingfieldmapwidgetwrapper.cpp
3 ---------------------
4 Date : June 2020
5 Copyright : (C) 2020 by Nyall Dawson
6 Email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
18#include "qgspanelwidget.h"
22
23#include <QBoxLayout>
24#include <QItemSelectionModel>
25#include <QLineEdit>
26#include <QMessageBox>
27#include <QPushButton>
28#include <QStandardItemModel>
29#include <QString>
30#include <QToolButton>
31
32#include "moc_qgsprocessingfieldmapwidgetwrapper.cpp"
33
34using namespace Qt::StringLiterals;
35
37
38//
39// QgsProcessingFieldMapPanelWidget
40//
41
42
43QgsProcessingFieldMapPanelWidget::QgsProcessingFieldMapPanelWidget( QWidget *parent )
44 : QgsPanelWidget( parent )
45{
46 setupUi( this );
47
48 mModel = mFieldsView->model();
49 mFieldsView->setDestinationEditable( true );
50
51 mLayerCombo->setAllowEmptyLayer( true );
52 mLayerCombo->setFilters( Qgis::LayerFilter::VectorLayer );
53
54 connect( mResetButton, &QPushButton::clicked, this, &QgsProcessingFieldMapPanelWidget::loadFieldsFromLayer );
55 connect( mAddButton, &QPushButton::clicked, this, &QgsProcessingFieldMapPanelWidget::addField );
56 connect( mDeleteButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::removeSelectedFields );
57 connect( mUpButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::moveSelectedFieldsUp );
58 connect( mDownButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::moveSelectedFieldsDown );
59 connect( mInvertSelectionButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::invertSelection );
60 connect( mLoadLayerFieldsButton, &QPushButton::clicked, this, &QgsProcessingFieldMapPanelWidget::loadLayerFields );
61
62
63 connect( mFieldsView, &QgsFieldMappingWidget::changed, this, [this] {
64 if ( !mBlockChangedSignal )
65 {
66 emit changed();
67 }
68 } );
69}
70
71void QgsProcessingFieldMapPanelWidget::setLayer( QgsVectorLayer *layer )
72{
73 if ( layer == mLayer )
74 return;
75
76 mLayer = layer;
77 mFieldsView->setSourceLayer( mLayer );
78 if ( mModel->rowCount() == 0 )
79 {
80 loadFieldsFromLayer();
81 return;
82 }
83
84 if ( mSkipConfirmDialog )
85 {
86 return;
87 }
88
89 QMessageBox dlg( this );
90 dlg.setText( tr( "Do you want to reset the field mapping?" ) );
91 dlg.setStandardButtons(
92 QMessageBox::StandardButtons( QMessageBox::Yes | QMessageBox::No )
93 );
94 dlg.setDefaultButton( QMessageBox::No );
95 if ( dlg.exec() == QMessageBox::Yes )
96 {
97 loadFieldsFromLayer();
98 }
99}
100
101QgsVectorLayer *QgsProcessingFieldMapPanelWidget::layer()
102{
103 return mLayer;
104}
105
106QVariant QgsProcessingFieldMapPanelWidget::value() const
107{
108 const QList<QgsFieldMappingModel::Field> mapping = mFieldsView->mapping();
109
110 QVariantList results;
111 results.reserve( mapping.size() );
112 for ( const QgsFieldMappingModel::Field &field : mapping )
113 {
114 QVariantMap def;
115 def.insert( u"name"_s, field.field.name() );
116 def.insert( u"type"_s, static_cast<int>( field.field.type() ) );
117 def.insert( u"type_name"_s, field.field.typeName() );
118 def.insert( u"length"_s, field.field.length() );
119 def.insert( u"precision"_s, field.field.precision() );
120 def.insert( u"sub_type"_s, static_cast<int>( field.field.subType() ) );
121 def.insert( u"expression"_s, field.expression );
122 def.insert( u"alias"_s, field.field.alias() );
123 def.insert( u"comment"_s, field.field.comment() );
124 results.append( def );
125 }
126 return results;
127}
128
129void QgsProcessingFieldMapPanelWidget::setValue( const QVariant &value )
130{
131 if ( value.userType() != QMetaType::Type::QVariantList )
132 return;
133
134 QgsFields destinationFields;
135 QMap<QString, QString> expressions;
136
137 const QgsFields layerFields = mLayer ? mLayer->fields() : QgsFields();
138 const QVariantList fields = value.toList();
139 for ( const QVariant &field : fields )
140 {
141 const QVariantMap map = field.toMap();
142 QgsField f( map.value( u"name"_s ).toString(), static_cast<QMetaType::Type>( map.value( u"type"_s, static_cast<int>( QMetaType::Type::UnknownType ) ).toInt() ), map.value( u"type_name"_s, QVariant::typeToName( static_cast<QMetaType::Type>( map.value( u"type"_s, static_cast<int>( QMetaType::Type::UnknownType ) ).toInt() ) ) ).toString(), map.value( u"length"_s, 0 ).toInt(), map.value( u"precision"_s, 0 ).toInt(), QString(), static_cast<QMetaType::Type>( map.value( u"sub_type"_s, QgsVariantUtils::createNullVariant( QMetaType::Type::UnknownType ) ).toInt() ) );
143 f.setAlias( map.value( u"alias"_s ).toString() );
144 f.setComment( map.value( u"comment"_s ).toString() );
145
146 if ( map.contains( u"constraints"_s ) )
147 {
148 const QgsFieldConstraints::Constraints constraints = static_cast<QgsFieldConstraints::Constraints>( map.value( u"constraints"_s, 0 ).toInt() );
149 QgsFieldConstraints fieldConstraints;
150
151 if ( constraints & QgsFieldConstraints::ConstraintNotNull )
153 if ( constraints & QgsFieldConstraints::ConstraintUnique )
157
158 f.setConstraints( fieldConstraints );
159 }
160
161 if ( !map.value( u"expression"_s ).toString().isEmpty() )
162 {
163 expressions.insert( f.name(), map.value( u"expression"_s ).toString() );
164 }
165
166 destinationFields.append( f );
167 }
168
169 mBlockChangedSignal = true;
170 if ( destinationFields.size() > 0 )
171 mFieldsView->setDestinationFields( destinationFields, expressions );
172 mBlockChangedSignal = false;
173
174 emit changed();
175}
176
177void QgsProcessingFieldMapPanelWidget::registerExpressionContextGenerator( const QgsExpressionContextGenerator *generator )
178{
179 mFieldsView->registerExpressionContextGenerator( generator );
180}
181
182void QgsProcessingFieldMapPanelWidget::loadFieldsFromLayer()
183{
184 if ( mLayer )
185 {
186 mFieldsView->setSourceFields( mLayer->fields() );
187 mFieldsView->setDestinationFields( mLayer->fields() );
188 }
189}
190
191void QgsProcessingFieldMapPanelWidget::addField()
192{
193 const int rowCount = mModel->rowCount();
194 mModel->appendField( QgsField( u"new_field"_s ) );
195 const QModelIndex index = mModel->index( rowCount, 0 );
196 mFieldsView->selectionModel()->select(
197 index,
198 QItemSelectionModel::SelectionFlags(
199 QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current | QItemSelectionModel::Rows
200 )
201 );
202 mFieldsView->scrollTo( index );
203}
204
205void QgsProcessingFieldMapPanelWidget::loadLayerFields()
206{
207 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( mLayerCombo->currentLayer() ) )
208 {
209 mFieldsView->setDestinationFields( vl->fields() );
210 }
211}
212
213//
214// QgsProcessingFieldMapParameterDefinitionWidget
215//
216
217QgsProcessingFieldMapParameterDefinitionWidget::QgsProcessingFieldMapParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm, QWidget *parent )
218 : QgsProcessingAbstractParameterDefinitionWidget( context, widgetContext, definition, algorithm, parent )
219{
220 QVBoxLayout *vlayout = new QVBoxLayout();
221 vlayout->setContentsMargins( 0, 0, 0, 0 );
222
223 vlayout->addWidget( new QLabel( tr( "Parent layer" ) ) );
224
225 mParentLayerComboBox = new QComboBox();
226 mParentLayerComboBox->addItem( tr( "None" ), QVariant() );
227
228 QString initialParent;
229 if ( const QgsProcessingParameterFieldMapping *mapParam = dynamic_cast<const QgsProcessingParameterFieldMapping *>( definition ) )
230 initialParent = mapParam->parentLayerParameterName();
231
232 if ( auto *lModel = widgetContext.model() )
233 {
234 // populate combo box with other model input choices
235 const QMap<QString, QgsProcessingModelParameter> components = lModel->parameterComponents();
236 for ( auto it = components.constBegin(); it != components.constEnd(); ++it )
237 {
238 if ( const QgsProcessingParameterFeatureSource *definition = dynamic_cast<const QgsProcessingParameterFeatureSource *>( lModel->parameterDefinition( it.value().parameterName() ) ) )
239 {
240 mParentLayerComboBox->addItem( definition->description(), definition->name() );
241 if ( !initialParent.isEmpty() && initialParent == definition->name() )
242 {
243 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
244 }
245 }
246 else if ( const QgsProcessingParameterVectorLayer *definition = dynamic_cast<const QgsProcessingParameterVectorLayer *>( lModel->parameterDefinition( it.value().parameterName() ) ) )
247 {
248 mParentLayerComboBox->addItem( definition->description(), definition->name() );
249 if ( !initialParent.isEmpty() && initialParent == definition->name() )
250 {
251 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
252 }
253 }
254 }
255 }
256
257 if ( mParentLayerComboBox->count() == 1 && !initialParent.isEmpty() )
258 {
259 // if no parent candidates found, we just add the existing one as a placeholder
260 mParentLayerComboBox->addItem( initialParent, initialParent );
261 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
262 }
263
264 vlayout->addWidget( mParentLayerComboBox );
265 setLayout( vlayout );
266}
267
268QgsProcessingParameterDefinition *QgsProcessingFieldMapParameterDefinitionWidget::createParameter( const QString &name, const QString &description, Qgis::ProcessingParameterFlags flags ) const
269{
270 auto param = std::make_unique<QgsProcessingParameterFieldMapping>( name, description, mParentLayerComboBox->currentData().toString() );
271 param->setFlags( flags );
272 return param.release();
273}
274
275//
276// QgsProcessingFieldMapWidgetWrapper
277//
278
279QgsProcessingFieldMapWidgetWrapper::QgsProcessingFieldMapWidgetWrapper( const QgsProcessingParameterDefinition *parameter, Qgis::ProcessingMode type, QWidget *parent )
280 : QgsAbstractProcessingParameterWidgetWrapper( parameter, type, parent )
281{
282}
283
284QString QgsProcessingFieldMapWidgetWrapper::parameterType() const
285{
287}
288
289QgsAbstractProcessingParameterWidgetWrapper *QgsProcessingFieldMapWidgetWrapper::createWidgetWrapper( const QgsProcessingParameterDefinition *parameter, Qgis::ProcessingMode type )
290{
291 return new QgsProcessingFieldMapWidgetWrapper( parameter, type );
292}
293
294QWidget *QgsProcessingFieldMapWidgetWrapper::createWidget()
295{
296 mPanel = new QgsProcessingFieldMapPanelWidget( nullptr );
297 mPanel->setToolTip( parameterDefinition()->toolTip() );
298 mPanel->registerExpressionContextGenerator( this );
299
300 connect( mPanel, &QgsProcessingFieldMapPanelWidget::changed, this, [this] {
301 emit widgetValueHasChanged( this );
302 } );
303
304 return mPanel;
305}
306
307QgsProcessingAbstractParameterDefinitionWidget *QgsProcessingFieldMapWidgetWrapper::createParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm )
308{
309 return new QgsProcessingFieldMapParameterDefinitionWidget( context, widgetContext, definition, algorithm );
310}
311
312void QgsProcessingFieldMapWidgetWrapper::postInitialize( const QList<QgsAbstractProcessingParameterWidgetWrapper *> &wrappers )
313{
315 switch ( type() )
316 {
319 {
320 for ( const QgsAbstractProcessingParameterWidgetWrapper *wrapper : wrappers )
321 {
322 if ( wrapper->parameterDefinition()->name() == static_cast<const QgsProcessingParameterFieldMapping *>( parameterDefinition() )->parentLayerParameterName() )
323 {
324 setParentLayerWrapperValue( wrapper );
325 connect( wrapper, &QgsAbstractProcessingParameterWidgetWrapper::widgetValueHasChanged, this, [this, wrapper] {
326 setParentLayerWrapperValue( wrapper );
327 } );
328 break;
329 }
330 }
331 break;
332 }
333
335 break;
336 }
337}
338
339int QgsProcessingFieldMapWidgetWrapper::stretch() const
340{
341 return 1;
342}
343
344void QgsProcessingFieldMapWidgetWrapper::setParentLayerWrapperValue( const QgsAbstractProcessingParameterWidgetWrapper *parentWrapper )
345{
346 // evaluate value to layer
347 QgsProcessingContext *context = nullptr;
348 std::unique_ptr<QgsProcessingContext> tmpContext;
349 if ( mProcessingContextGenerator )
350 context = mProcessingContextGenerator->processingContext();
351
352 if ( !context )
353 {
354 tmpContext = std::make_unique<QgsProcessingContext>();
355 context = tmpContext.get();
356 }
357
358 QgsVectorLayer *layer = QgsProcessingParameters::parameterAsVectorLayer( parentWrapper->parameterDefinition(), parentWrapper->parameterValue(), *context );
359 if ( !layer )
360 {
361 if ( mPanel )
362 mPanel->setLayer( nullptr );
363 return;
364 }
365
366 // need to grab ownership of layer if required - otherwise layer may be deleted when context
367 // goes out of scope
368 std::unique_ptr<QgsMapLayer> ownedLayer( context->takeResultLayer( layer->id() ) );
369 if ( ownedLayer && ownedLayer->type() == Qgis::LayerType::Vector )
370 {
371 mParentLayer.reset( qobject_cast<QgsVectorLayer *>( ownedLayer.release() ) );
372 layer = mParentLayer.get();
373 }
374 else
375 {
376 // don't need ownership of this layer - it wasn't owned by context (so e.g. is owned by the project)
377 }
378
379 if ( mPanel )
380 mPanel->setLayer( layer );
381}
382
383void QgsProcessingFieldMapWidgetWrapper::setWidgetValue( const QVariant &value, QgsProcessingContext & )
384{
385 if ( mPanel )
386 mPanel->setValue( value );
387}
388
389QVariant QgsProcessingFieldMapWidgetWrapper::widgetValue() const
390{
391 return mPanel ? mPanel->value() : QVariant();
392}
393
394QString QgsProcessingFieldMapWidgetWrapper::modelerExpressionFormatString() const
395{
396 return tr( "an array of map items, each containing a 'name', 'type' and 'expression' values (and optional 'length' and 'precision' values)." );
397}
398
399const QgsVectorLayer *QgsProcessingFieldMapWidgetWrapper::linkedVectorLayer() const
400{
401 if ( mPanel && mPanel->layer() )
402 return mPanel->layer();
403
405}
406
ProcessingMode
Types of modes which Processing widgets can be created for.
Definition qgis.h:3742
@ Batch
Batch processing mode.
Definition qgis.h:3744
@ Modeler
Modeler mode.
Definition qgis.h:3745
@ Standard
Standard (single-run) algorithm mode.
Definition qgis.h:3743
@ Vector
Vector layer.
Definition qgis.h:194
QFlags< ProcessingParameterFlag > ProcessingParameterFlags
Flags which dictate the behavior of Processing parameters.
Definition qgis.h:3848
A widget wrapper for Processing parameter value widgets.
QVariant parameterValue() const
Returns the current value of the parameter.
void widgetValueHasChanged(QgsAbstractProcessingParameterWidgetWrapper *wrapper)
Emitted whenever the parameter value (as defined by the wrapped widget) is changed.
virtual void postInitialize(const QList< QgsAbstractProcessingParameterWidgetWrapper * > &wrappers)
Called after all wrappers have been created within a particular dialog or context,...
virtual const QgsVectorLayer * linkedVectorLayer() const
Returns the optional vector layer associated with this widget wrapper, or nullptr if no vector layer ...
const QgsProcessingParameterDefinition * parameterDefinition() const
Returns the parameter definition associated with this wrapper.
Abstract interface for generating an expression context.
Stores information about constraints which may be present on a field.
@ ConstraintNotNull
Field may not be null.
@ ConstraintUnique
Field must have a unique value.
@ ConstraintExpression
Field has an expression constraint set. See constraintExpression().
void setConstraint(Constraint constraint, ConstraintOrigin origin=ConstraintOriginLayer)
Sets a constraint on the field.
QFlags< Constraint > Constraints
bool removeSelectedFields()
Removes the currently selected field from the model.
bool moveSelectedFieldsDown()
Moves down the currently selected field.
bool moveSelectedFieldsUp()
Moves up currently selected field.
void invertSelection()
Invert the field selection state.
void changed()
Emitted when the fields defined in the widget are changed.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:76
int size() const
Returns number of items.
QString id
Definition qgsmaplayer.h:86
Base class for any widget that can be shown as an inline panel.
Abstract base class for widgets which allow users to specify the properties of a Processing parameter...
Abstract base class for processing algorithms.
Contains information about the context in which a processing algorithm is executed.
QgsMapLayer * takeResultLayer(const QString &id)
Takes the result map layer with matching id from the context and transfers ownership of it back to th...
Base class for the definition of processing parameters.
QString description() const
Returns the description for the parameter.
QString name() const
Returns the name of the parameter.
An input feature source (such as vector layers) parameter for processing algorithms.
A parameter for "field mapping" configurations, which consist of a definition of desired output field...
static QString typeName()
Returns the type name for the parameter class.
A vector layer (with or without geometry) parameter for processing algorithms.
Contains settings which reflect the context in which a Processing parameter widget is shown.
QgsProcessingModelAlgorithm * model() const
Returns the model which the parameter widget is associated with.
static QgsVectorLayer * parameterAsVectorLayer(const QgsProcessingParameterDefinition *definition, const QVariantMap &parameters, QgsProcessingContext &context)
Evaluates the parameter with matching definition to a vector layer.
static QVariant createNullVariant(QMetaType::Type metaType)
Helper method to properly create a null QVariant from a metaType Returns the created QVariant.
Represents a vector layer which manages a vector based dataset.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into allowing algorithms to be written in pure substantial changes are required in order to port existing x Processing algorithms for QGIS x The most significant changes are outlined not GeoAlgorithm For algorithms which operate on features one by consider subclassing the QgsProcessingFeatureBasedAlgorithm class This class allows much of the boilerplate code for looping over features from a vector layer to be bypassed and instead requires implementation of a processFeature method Ensure that your algorithm(or algorithm 's parent class) implements the new pure virtual createInstance(self) call
The Field struct holds information about a mapped field.