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