QGIS API Documentation 3.41.0-Master (fda2aa46e9a)
Loading...
Searching...
No Matches
qgsprocessingaggregatewidgetwrapper.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsprocessingaggregatewidgetwrapper.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_qgsprocessingaggregatewidgetwrapper.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//
38// QgsProcessingAggregatePanelWidget
39//
40
41
42QgsProcessingAggregatePanelWidget::QgsProcessingAggregatePanelWidget( QWidget *parent )
43 : QgsPanelWidget( parent )
44{
45 setupUi( this );
46
47 mModel = mFieldsView->model();
48
49 mLayerCombo->setAllowEmptyLayer( true );
50 mLayerCombo->setFilters( Qgis::LayerFilter::VectorLayer );
51
52 connect( mResetButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::loadFieldsFromLayer );
53 connect( mAddButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::addField );
54 connect( mDeleteButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::removeSelectedFields );
55 connect( mUpButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::moveSelectedFieldsUp );
56 connect( mDownButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::moveSelectedFieldsDown );
57 connect( mLoadLayerFieldsButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::loadLayerFields );
58
59 connect( mFieldsView, &QgsAggregateMappingWidget::changed, this, [ = ]
60 {
61 if ( !mBlockChangedSignal )
62 {
63 emit changed();
64 }
65 } );
66}
67
68void QgsProcessingAggregatePanelWidget::setLayer( QgsVectorLayer *layer )
69{
70 if ( layer == mLayer )
71 return;
72
73 mLayer = layer;
74 mFieldsView->setSourceLayer( mLayer );
75 if ( mModel->rowCount() == 0 )
76 {
77 loadFieldsFromLayer();
78 return;
79 }
80
81 QMessageBox dlg( this );
82 dlg.setText( tr( "Do you want to reset the field mapping?" ) );
83 dlg.setStandardButtons(
84 QMessageBox::StandardButtons( QMessageBox::Yes |
85 QMessageBox::No ) );
86 dlg.setDefaultButton( QMessageBox::No );
87 if ( dlg.exec() == QMessageBox::Yes )
88 {
89 loadFieldsFromLayer();
90 }
91}
92
93QgsVectorLayer *QgsProcessingAggregatePanelWidget::layer()
94{
95 return mLayer;
96}
97
98QVariant QgsProcessingAggregatePanelWidget::value() const
99{
100 const QList<QgsAggregateMappingModel::Aggregate> mapping = mFieldsView->mapping();
101
102 QVariantList results;
103 results.reserve( mapping.size() );
104 for ( const QgsAggregateMappingModel::Aggregate &aggregate : mapping )
105 {
106 QVariantMap def;
107 def.insert( QStringLiteral( "name" ), aggregate.field.name() );
108 def.insert( QStringLiteral( "type" ), static_cast< int >( aggregate.field.type() ) );
109 def.insert( QStringLiteral( "type_name" ), aggregate.field.typeName() );
110 def.insert( QStringLiteral( "length" ), aggregate.field.length() );
111 def.insert( QStringLiteral( "precision" ), aggregate.field.precision() );
112 def.insert( QStringLiteral( "sub_type" ), static_cast< int >( aggregate.field.subType() ) );
113 def.insert( QStringLiteral( "input" ), aggregate.source );
114 def.insert( QStringLiteral( "aggregate" ), aggregate.aggregate );
115 def.insert( QStringLiteral( "delimiter" ), aggregate.delimiter );
116 results.append( def );
117 }
118 return results;
119}
120
121void QgsProcessingAggregatePanelWidget::setValue( const QVariant &value )
122{
123 if ( value.userType() != QMetaType::Type::QVariantList )
124 return;
125
126 QList< QgsAggregateMappingModel::Aggregate > aggregates;
127
128 const QVariantList fields = value.toList();
129 aggregates.reserve( fields.size() );
130 for ( const QVariant &field : fields )
131 {
132 const QVariantMap map = field.toMap();
133 const QgsField f( map.value( QStringLiteral( "name" ) ).toString(),
134 static_cast< QMetaType::Type >( map.value( QStringLiteral( "type" ), static_cast< int >( QMetaType::Type::UnknownType ) ).toInt() ),
135 map.value( QStringLiteral( "type_name" ), QVariant::typeToName( static_cast< QMetaType::Type >( map.value( QStringLiteral( "type" ), static_cast< int >( QMetaType::Type::UnknownType ) ).toInt() ) ) ).toString(),
136 map.value( QStringLiteral( "length" ), 0 ).toInt(),
137 map.value( QStringLiteral( "precision" ), 0 ).toInt(),
138 QString(),
139 static_cast< QMetaType::Type >( map.value( QStringLiteral( "sub_type" ), QgsVariantUtils::createNullVariant( QMetaType::Type::UnknownType ) ).toInt() ) );
140
142 aggregate.field = f;
143
144 aggregate.source = map.value( QStringLiteral( "input" ) ).toString();
145 aggregate.aggregate = map.value( QStringLiteral( "aggregate" ) ).toString();
146 aggregate.delimiter = map.value( QStringLiteral( "delimiter" ) ).toString();
147
148 aggregates.append( aggregate );
149 }
150
151 mBlockChangedSignal = true;
152
153 if ( aggregates.size() > 0 )
154 mFieldsView->setMapping( aggregates );
155
156 mBlockChangedSignal = false;
157
158 emit changed();
159}
160
161void QgsProcessingAggregatePanelWidget::registerExpressionContextGenerator( const QgsExpressionContextGenerator *generator )
162{
163 mFieldsView->registerExpressionContextGenerator( generator );
164}
165
166void QgsProcessingAggregatePanelWidget::loadFieldsFromLayer()
167{
168 if ( mLayer )
169 {
170 mFieldsView->setSourceFields( mLayer->fields() );
171 }
172}
173
174void QgsProcessingAggregatePanelWidget::addField()
175{
176 const int rowCount = mModel->rowCount();
177 mModel->appendField( QgsField( QStringLiteral( "new_field" ) ) );
178 const QModelIndex index = mModel->index( rowCount, 0 );
179 mFieldsView->selectionModel()->select(
180 index,
181 QItemSelectionModel::SelectionFlags(
182 QItemSelectionModel::Clear |
183 QItemSelectionModel::Select |
184 QItemSelectionModel::Current |
185 QItemSelectionModel::Rows ) );
186 mFieldsView->scrollTo( index );
187}
188
189void QgsProcessingAggregatePanelWidget::loadLayerFields()
190{
191 if ( QgsVectorLayer *vl = qobject_cast< QgsVectorLayer * >( mLayerCombo->currentLayer() ) )
192 {
193 mFieldsView->setSourceFields( vl->fields() );
194 }
195}
196
197//
198// QgsProcessingAggregateParameterDefinitionWidget
199//
200
201QgsProcessingAggregateParameterDefinitionWidget::QgsProcessingAggregateParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm, QWidget *parent )
202 : QgsProcessingAbstractParameterDefinitionWidget( context, widgetContext, definition, algorithm, parent )
203{
204 QVBoxLayout *vlayout = new QVBoxLayout();
205 vlayout->setContentsMargins( 0, 0, 0, 0 );
206
207 vlayout->addWidget( new QLabel( tr( "Parent layer" ) ) );
208
209 mParentLayerComboBox = new QComboBox();
210 mParentLayerComboBox->addItem( tr( "None" ), QVariant() );
211
212 QString initialParent;
213 if ( const QgsProcessingParameterAggregate *aggregateParam = dynamic_cast<const QgsProcessingParameterAggregate *>( definition ) )
214 initialParent = aggregateParam->parentLayerParameterName();
215
216 if ( auto *lModel = widgetContext.model() )
217 {
218 // populate combo box with other model input choices
219 const QMap<QString, QgsProcessingModelParameter> components = lModel->parameterComponents();
220 for ( auto it = components.constBegin(); it != components.constEnd(); ++it )
221 {
222 if ( const QgsProcessingParameterFeatureSource *definition = dynamic_cast< const QgsProcessingParameterFeatureSource * >( lModel->parameterDefinition( it.value().parameterName() ) ) )
223 {
224 mParentLayerComboBox-> addItem( definition->description(), definition->name() );
225 if ( !initialParent.isEmpty() && initialParent == definition->name() )
226 {
227 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
228 }
229 }
230 else if ( const QgsProcessingParameterVectorLayer *definition = dynamic_cast< const QgsProcessingParameterVectorLayer * >( lModel->parameterDefinition( it.value().parameterName() ) ) )
231 {
232 mParentLayerComboBox-> addItem( definition->description(), definition->name() );
233 if ( !initialParent.isEmpty() && initialParent == definition->name() )
234 {
235 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
236 }
237 }
238 }
239 }
240
241 if ( mParentLayerComboBox->count() == 1 && !initialParent.isEmpty() )
242 {
243 // if no parent candidates found, we just add the existing one as a placeholder
244 mParentLayerComboBox->addItem( initialParent, initialParent );
245 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
246 }
247
248 vlayout->addWidget( mParentLayerComboBox );
249 setLayout( vlayout );
250}
251
252QgsProcessingParameterDefinition *QgsProcessingAggregateParameterDefinitionWidget::createParameter( const QString &name, const QString &description, Qgis::ProcessingParameterFlags flags ) const
253{
254 auto param = std::make_unique< QgsProcessingParameterAggregate >( name, description, mParentLayerComboBox->currentData().toString() );
255 param->setFlags( flags );
256 return param.release();
257}
258
259//
260// QgsProcessingAggregateWidgetWrapper
261//
262
263QgsProcessingAggregateWidgetWrapper::QgsProcessingAggregateWidgetWrapper( const QgsProcessingParameterDefinition *parameter, QgsProcessingGui::WidgetType type, QWidget *parent )
264 : QgsAbstractProcessingParameterWidgetWrapper( parameter, type, parent )
265{
266}
267
268QString QgsProcessingAggregateWidgetWrapper::parameterType() const
269{
271}
272
273QgsAbstractProcessingParameterWidgetWrapper *QgsProcessingAggregateWidgetWrapper::createWidgetWrapper( const QgsProcessingParameterDefinition *parameter, QgsProcessingGui::WidgetType type )
274{
275 return new QgsProcessingAggregateWidgetWrapper( parameter, type );
276}
277
278QWidget *QgsProcessingAggregateWidgetWrapper::createWidget()
279{
280 mPanel = new QgsProcessingAggregatePanelWidget( nullptr );
281 mPanel->setToolTip( parameterDefinition()->toolTip() );
282 mPanel->registerExpressionContextGenerator( this );
283
284 connect( mPanel, &QgsProcessingAggregatePanelWidget::changed, this, [ = ]
285 {
286 emit widgetValueHasChanged( this );
287 } );
288
289 return mPanel;
290}
291
292QgsProcessingAbstractParameterDefinitionWidget *QgsProcessingAggregateWidgetWrapper::createParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm )
293{
294 return new QgsProcessingAggregateParameterDefinitionWidget( context, widgetContext, definition, algorithm );
295}
296
297void QgsProcessingAggregateWidgetWrapper::postInitialize( const QList<QgsAbstractProcessingParameterWidgetWrapper *> &wrappers )
298{
300 switch ( type() )
301 {
304 {
305 for ( const QgsAbstractProcessingParameterWidgetWrapper *wrapper : wrappers )
306 {
307 if ( wrapper->parameterDefinition()->name() == static_cast< const QgsProcessingParameterAggregate * >( parameterDefinition() )->parentLayerParameterName() )
308 {
309 setParentLayerWrapperValue( wrapper );
311 {
312 setParentLayerWrapperValue( wrapper );
313 } );
314 break;
315 }
316 }
317 break;
318 }
319
321 break;
322 }
323}
324
325int QgsProcessingAggregateWidgetWrapper::stretch() const
326{
327 return 1;
328}
329
330void QgsProcessingAggregateWidgetWrapper::setParentLayerWrapperValue( const QgsAbstractProcessingParameterWidgetWrapper *parentWrapper )
331{
332 // evaluate value to layer
333 QgsProcessingContext *context = nullptr;
334 std::unique_ptr< QgsProcessingContext > tmpContext;
335 if ( mProcessingContextGenerator )
336 context = mProcessingContextGenerator->processingContext();
337
338 if ( !context )
339 {
340 tmpContext = std::make_unique< QgsProcessingContext >();
341 context = tmpContext.get();
342 }
343
344 QgsVectorLayer *layer = QgsProcessingParameters::parameterAsVectorLayer( parentWrapper->parameterDefinition(), parentWrapper->parameterValue(), *context );
345 if ( !layer )
346 {
347 if ( mPanel )
348 mPanel->setLayer( nullptr );
349 return;
350 }
351
352 // need to grab ownership of layer if required - otherwise layer may be deleted when context
353 // goes out of scope
354 std::unique_ptr< QgsMapLayer > ownedLayer( context->takeResultLayer( layer->id() ) );
355 if ( ownedLayer && ownedLayer->type() == Qgis::LayerType::Vector )
356 {
357 mParentLayer.reset( qobject_cast< QgsVectorLayer * >( ownedLayer.release() ) );
358 layer = mParentLayer.get();
359 }
360 else
361 {
362 // don't need ownership of this layer - it wasn't owned by context (so e.g. is owned by the project)
363 }
364
365 if ( mPanel )
366 mPanel->setLayer( layer );
367}
368
369void QgsProcessingAggregateWidgetWrapper::setWidgetValue( const QVariant &value, QgsProcessingContext & )
370{
371 if ( mPanel )
372 mPanel->setValue( value );
373}
374
375QVariant QgsProcessingAggregateWidgetWrapper::widgetValue() const
376{
377 return mPanel ? mPanel->value() : QVariant();
378}
379
380QStringList QgsProcessingAggregateWidgetWrapper::compatibleParameterTypes() const
381{
382 return QStringList()
384}
385
386QStringList QgsProcessingAggregateWidgetWrapper::compatibleOutputTypes() const
387{
388 return QStringList();
389}
390
391QString QgsProcessingAggregateWidgetWrapper::modelerExpressionFormatString() const
392{
393 return tr( "an array of map items, each containing a 'name', 'type', 'aggregate' and 'input' value (and optional 'length' and 'precision' values)." );
394}
395
396const QgsVectorLayer *QgsProcessingAggregateWidgetWrapper::linkedVectorLayer() const
397{
398 if ( mPanel && mPanel->layer() )
399 return mPanel->layer();
400
402}
403
@ 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.
void changed()
Emitted when the aggregates defined in the widget are changed.
bool moveSelectedFieldsDown()
Moves down currently selected field.
bool moveSelectedFieldsUp()
Moves up currently selected field.
bool removeSelectedFields()
Removes the currently selected field from the model.
Abstract interface for generating an expression context.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
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.
A parameter for "aggregate" configurations, which consist of a definition of desired output fields,...
static QString typeName()
Returns the type name for the parameter class.
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 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 Aggregate struct holds information about an aggregate column.
QString source
The source expression used as the input for the aggregate calculation.
QgsField field
The field in its current status (it might have been renamed)