QGIS API Documentation 3.41.0-Master (45a0abf3bec)
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#include "moc_qgsprocessingfieldmapwidgetwrapper.cpp"
18
19#include <QBoxLayout>
20#include <QLineEdit>
21#include <QMessageBox>
22#include <QPushButton>
23#include <QStandardItemModel>
24#include <QToolButton>
25#include <QItemSelectionModel>
26
27#include "qgspanelwidget.h"
28
31
33
35
36//
37// QgsProcessingFieldMapPanelWidget
38//
39
40
41QgsProcessingFieldMapPanelWidget::QgsProcessingFieldMapPanelWidget( QWidget *parent )
42 : QgsPanelWidget( parent )
43{
44 setupUi( this );
45
46 mModel = mFieldsView->model();
47 mFieldsView->setDestinationEditable( true );
48
49 mLayerCombo->setAllowEmptyLayer( true );
50 mLayerCombo->setFilters( Qgis::LayerFilter::VectorLayer );
51
52 connect( mResetButton, &QPushButton::clicked, this, &QgsProcessingFieldMapPanelWidget::loadFieldsFromLayer );
53 connect( mAddButton, &QPushButton::clicked, this, &QgsProcessingFieldMapPanelWidget::addField );
54 connect( mDeleteButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::removeSelectedFields );
55 connect( mUpButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::moveSelectedFieldsUp );
56 connect( mDownButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::moveSelectedFieldsDown );
57 connect( mInvertSelectionButton, &QPushButton::clicked, mFieldsView, &QgsFieldMappingWidget::invertSelection );
58 connect( mLoadLayerFieldsButton, &QPushButton::clicked, this, &QgsProcessingFieldMapPanelWidget::loadLayerFields );
59
60
61 connect( mFieldsView, &QgsFieldMappingWidget::changed, this, [ = ]
62 {
63 if ( !mBlockChangedSignal )
64 {
65 emit changed();
66 }
67 } );
68}
69
70void QgsProcessingFieldMapPanelWidget::setLayer( QgsVectorLayer *layer )
71{
72 if ( layer == mLayer )
73 return;
74
75 mLayer = layer;
76 mFieldsView->setSourceLayer( mLayer );
77 if ( mModel->rowCount() == 0 )
78 {
79 loadFieldsFromLayer();
80 return;
81 }
82
83 QMessageBox dlg( this );
84 dlg.setText( tr( "Do you want to reset the field mapping?" ) );
85 dlg.setStandardButtons(
86 QMessageBox::StandardButtons( QMessageBox::Yes |
87 QMessageBox::No ) );
88 dlg.setDefaultButton( QMessageBox::No );
89 if ( dlg.exec() == QMessageBox::Yes )
90 {
91 loadFieldsFromLayer();
92 }
93}
94
95QgsVectorLayer *QgsProcessingFieldMapPanelWidget::layer()
96{
97 return mLayer;
98}
99
100QVariant QgsProcessingFieldMapPanelWidget::value() const
101{
102 const QList<QgsFieldMappingModel::Field> mapping = mFieldsView->mapping();
103
104 QVariantList results;
105 results.reserve( mapping.size() );
106 for ( const QgsFieldMappingModel::Field &field : mapping )
107 {
108 QVariantMap def;
109 def.insert( QStringLiteral( "name" ), field.field.name() );
110 def.insert( QStringLiteral( "type" ), static_cast< int >( field.field.type() ) );
111 def.insert( QStringLiteral( "type_name" ), field.field.typeName() );
112 def.insert( QStringLiteral( "length" ), field.field.length() );
113 def.insert( QStringLiteral( "precision" ), field.field.precision() );
114 def.insert( QStringLiteral( "sub_type" ), static_cast< int >( field.field.subType() ) );
115 def.insert( QStringLiteral( "expression" ), field.expression );
116 def.insert( QStringLiteral( "alias" ), field.field.alias() );
117 def.insert( QStringLiteral( "comment" ), field.field.comment() );
118 results.append( def );
119 }
120 return results;
121}
122
123void QgsProcessingFieldMapPanelWidget::setValue( const QVariant &value )
124{
125 if ( value.userType() != QMetaType::Type::QVariantList )
126 return;
127
128 QgsFields destinationFields;
129 QMap<QString, QString> expressions;
130
131 const QgsFields layerFields = mLayer ? mLayer->fields() : QgsFields();
132 const QVariantList fields = value.toList();
133 for ( const QVariant &field : fields )
134 {
135 const QVariantMap map = field.toMap();
136 QgsField f( map.value( QStringLiteral( "name" ) ).toString(),
137 static_cast< QMetaType::Type >( map.value( QStringLiteral( "type" ), static_cast< int >( QMetaType::Type::UnknownType ) ).toInt() ),
138 map.value( QStringLiteral( "type_name" ), QVariant::typeToName( static_cast< QMetaType::Type >( map.value( QStringLiteral( "type" ), static_cast< int >( QMetaType::Type::UnknownType ) ).toInt() ) ) ).toString(),
139 map.value( QStringLiteral( "length" ), 0 ).toInt(),
140 map.value( QStringLiteral( "precision" ), 0 ).toInt(),
141 QString(),
142 static_cast< QMetaType::Type >( map.value( QStringLiteral( "sub_type" ), QgsVariantUtils::createNullVariant( QMetaType::Type::UnknownType ) ).toInt() ) );
143 f.setAlias( map.value( QStringLiteral( "alias" ) ).toString() );
144 f.setComment( map.value( QStringLiteral( "comment" ) ).toString() );
145
146 if ( map.contains( QStringLiteral( "constraints" ) ) )
147 {
148 const QgsFieldConstraints::Constraints constraints = static_cast<QgsFieldConstraints::Constraints>( map.value( QStringLiteral( "constraints" ), 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( QStringLiteral( "expression" ) ).toString().isEmpty() )
162 {
163 expressions.insert( f.name(), map.value( QStringLiteral( "expression" ) ).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( QStringLiteral( "new_field" ) ) );
195 const QModelIndex index = mModel->index( rowCount, 0 );
196 mFieldsView->selectionModel()->select(
197 index,
198 QItemSelectionModel::SelectionFlags(
199 QItemSelectionModel::Clear |
200 QItemSelectionModel::Select |
201 QItemSelectionModel::Current |
202 QItemSelectionModel::Rows ) );
203 mFieldsView->scrollTo( index );
204}
205
206void QgsProcessingFieldMapPanelWidget::loadLayerFields()
207{
208 if ( QgsVectorLayer *vl = qobject_cast< QgsVectorLayer * >( mLayerCombo->currentLayer() ) )
209 {
210 mFieldsView->setSourceFields( vl->fields() );
211 mFieldsView->setDestinationFields( vl->fields() );
212 }
213}
214
215//
216// QgsProcessingFieldMapParameterDefinitionWidget
217//
218
219QgsProcessingFieldMapParameterDefinitionWidget::QgsProcessingFieldMapParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm, QWidget *parent )
220 : QgsProcessingAbstractParameterDefinitionWidget( context, widgetContext, definition, algorithm, parent )
221{
222 QVBoxLayout *vlayout = new QVBoxLayout();
223 vlayout->setContentsMargins( 0, 0, 0, 0 );
224
225 vlayout->addWidget( new QLabel( tr( "Parent layer" ) ) );
226
227 mParentLayerComboBox = new QComboBox();
228 mParentLayerComboBox->addItem( tr( "None" ), QVariant() );
229
230 QString initialParent;
231 if ( const QgsProcessingParameterFieldMapping *mapParam = dynamic_cast<const QgsProcessingParameterFieldMapping *>( definition ) )
232 initialParent = mapParam->parentLayerParameterName();
233
234 if ( auto *lModel = widgetContext.model() )
235 {
236 // populate combo box with other model input choices
237 const QMap<QString, QgsProcessingModelParameter> components = lModel->parameterComponents();
238 for ( auto it = components.constBegin(); it != components.constEnd(); ++it )
239 {
240 if ( const QgsProcessingParameterFeatureSource *definition = dynamic_cast< const QgsProcessingParameterFeatureSource * >( lModel->parameterDefinition( it.value().parameterName() ) ) )
241 {
242 mParentLayerComboBox-> addItem( definition->description(), definition->name() );
243 if ( !initialParent.isEmpty() && initialParent == definition->name() )
244 {
245 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
246 }
247 }
248 else if ( const QgsProcessingParameterVectorLayer *definition = dynamic_cast< const QgsProcessingParameterVectorLayer * >( lModel->parameterDefinition( it.value().parameterName() ) ) )
249 {
250 mParentLayerComboBox-> addItem( definition->description(), definition->name() );
251 if ( !initialParent.isEmpty() && initialParent == definition->name() )
252 {
253 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
254 }
255 }
256 }
257 }
258
259 if ( mParentLayerComboBox->count() == 1 && !initialParent.isEmpty() )
260 {
261 // if no parent candidates found, we just add the existing one as a placeholder
262 mParentLayerComboBox->addItem( initialParent, initialParent );
263 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
264 }
265
266 vlayout->addWidget( mParentLayerComboBox );
267 setLayout( vlayout );
268}
269
270QgsProcessingParameterDefinition *QgsProcessingFieldMapParameterDefinitionWidget::createParameter( const QString &name, const QString &description, Qgis::ProcessingParameterFlags flags ) const
271{
272 auto param = std::make_unique< QgsProcessingParameterFieldMapping >( name, description, mParentLayerComboBox->currentData().toString() );
273 param->setFlags( flags );
274 return param.release();
275}
276
277//
278// QgsProcessingFieldMapWidgetWrapper
279//
280
281QgsProcessingFieldMapWidgetWrapper::QgsProcessingFieldMapWidgetWrapper( const QgsProcessingParameterDefinition *parameter, QgsProcessingGui::WidgetType type, QWidget *parent )
282 : QgsAbstractProcessingParameterWidgetWrapper( parameter, type, parent )
283{
284}
285
286QString QgsProcessingFieldMapWidgetWrapper::parameterType() const
287{
289}
290
291QgsAbstractProcessingParameterWidgetWrapper *QgsProcessingFieldMapWidgetWrapper::createWidgetWrapper( const QgsProcessingParameterDefinition *parameter, QgsProcessingGui::WidgetType type )
292{
293 return new QgsProcessingFieldMapWidgetWrapper( parameter, type );
294}
295
296QWidget *QgsProcessingFieldMapWidgetWrapper::createWidget()
297{
298 mPanel = new QgsProcessingFieldMapPanelWidget( nullptr );
299 mPanel->setToolTip( parameterDefinition()->toolTip() );
300 mPanel->registerExpressionContextGenerator( this );
301
302 connect( mPanel, &QgsProcessingFieldMapPanelWidget::changed, this, [ = ]
303 {
304 emit widgetValueHasChanged( this );
305 } );
306
307 return mPanel;
308}
309
310QgsProcessingAbstractParameterDefinitionWidget *QgsProcessingFieldMapWidgetWrapper::createParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm )
311{
312 return new QgsProcessingFieldMapParameterDefinitionWidget( context, widgetContext, definition, algorithm );
313}
314
315void QgsProcessingFieldMapWidgetWrapper::postInitialize( const QList<QgsAbstractProcessingParameterWidgetWrapper *> &wrappers )
316{
318 switch ( type() )
319 {
322 {
323 for ( const QgsAbstractProcessingParameterWidgetWrapper *wrapper : wrappers )
324 {
325 if ( wrapper->parameterDefinition()->name() == static_cast< const QgsProcessingParameterFieldMapping * >( parameterDefinition() )->parentLayerParameterName() )
326 {
327 setParentLayerWrapperValue( wrapper );
329 {
330 setParentLayerWrapperValue( wrapper );
331 } );
332 break;
333 }
334 }
335 break;
336 }
337
339 break;
340 }
341}
342
343int QgsProcessingFieldMapWidgetWrapper::stretch() const
344{
345 return 1;
346}
347
348void QgsProcessingFieldMapWidgetWrapper::setParentLayerWrapperValue( const QgsAbstractProcessingParameterWidgetWrapper *parentWrapper )
349{
350 // evaluate value to layer
351 QgsProcessingContext *context = nullptr;
352 std::unique_ptr< QgsProcessingContext > tmpContext;
353 if ( mProcessingContextGenerator )
354 context = mProcessingContextGenerator->processingContext();
355
356 if ( !context )
357 {
358 tmpContext = std::make_unique< QgsProcessingContext >();
359 context = tmpContext.get();
360 }
361
362 QgsVectorLayer *layer = QgsProcessingParameters::parameterAsVectorLayer( parentWrapper->parameterDefinition(), parentWrapper->parameterValue(), *context );
363 if ( !layer )
364 {
365 if ( mPanel )
366 mPanel->setLayer( nullptr );
367 return;
368 }
369
370 // need to grab ownership of layer if required - otherwise layer may be deleted when context
371 // goes out of scope
372 std::unique_ptr< QgsMapLayer > ownedLayer( context->takeResultLayer( layer->id() ) );
373 if ( ownedLayer && ownedLayer->type() == Qgis::LayerType::Vector )
374 {
375 mParentLayer.reset( qobject_cast< QgsVectorLayer * >( ownedLayer.release() ) );
376 layer = mParentLayer.get();
377 }
378 else
379 {
380 // don't need ownership of this layer - it wasn't owned by context (so e.g. is owned by the project)
381 }
382
383 if ( mPanel )
384 mPanel->setLayer( layer );
385}
386
387void QgsProcessingFieldMapWidgetWrapper::setWidgetValue( const QVariant &value, QgsProcessingContext & )
388{
389 if ( mPanel )
390 mPanel->setValue( value );
391}
392
393QVariant QgsProcessingFieldMapWidgetWrapper::widgetValue() const
394{
395 return mPanel ? mPanel->value() : QVariant();
396}
397
398QStringList QgsProcessingFieldMapWidgetWrapper::compatibleParameterTypes() const
399{
400 return QStringList()
402}
403
404QStringList QgsProcessingFieldMapWidgetWrapper::compatibleOutputTypes() const
405{
406 return QStringList();
407}
408
409QString QgsProcessingFieldMapWidgetWrapper::modelerExpressionFormatString() const
410{
411 return tr( "an array of map items, each containing a 'name', 'type' and 'expression' values (and optional 'length' and 'precision' values)." );
412}
413
414const QgsVectorLayer *QgsProcessingFieldMapWidgetWrapper::linkedVectorLayer() const
415{
416 if ( mPanel && mPanel->layer() )
417 return mPanel->layer();
418
420}
421
@ Vector
Vector layer.
QFlags< ProcessingParameterFlag > ProcessingParameterFlags
Flags which dictate the behavior of Processing parameters.
Definition qgis.h:3499
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:53
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:70
int size() const
Returns number of items.
QString id
Definition qgsmaplayer.h:79
Base class for any widget that can be shown as a 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...
WidgetType
Types of dialogs which Processing widgets can be created for.
@ Modeler
Modeler dialog.
@ Standard
Standard algorithm dialog.
@ Batch
Batch processing dialog.
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 data sets.
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.