QGIS API Documentation 3.99.0-Master (357b655ed83)
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
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_qgsprocessingaggregatewidgetwrapper.cpp"
33
34using namespace Qt::StringLiterals;
35
37
38
39//
40// QgsProcessingAggregatePanelWidget
41//
42
43
44QgsProcessingAggregatePanelWidget::QgsProcessingAggregatePanelWidget( QWidget *parent )
45 : QgsPanelWidget( parent )
46{
47 setupUi( this );
48
49 mModel = mFieldsView->model();
50
51 mLayerCombo->setAllowEmptyLayer( true );
52 mLayerCombo->setFilters( Qgis::LayerFilter::VectorLayer );
53
54 connect( mResetButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::loadFieldsFromLayer );
55 connect( mAddButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::addField );
56 connect( mDeleteButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::removeSelectedFields );
57 connect( mUpButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::moveSelectedFieldsUp );
58 connect( mDownButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::moveSelectedFieldsDown );
59 connect( mLoadLayerFieldsButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::loadLayerFields );
60
61 connect( mFieldsView, &QgsAggregateMappingWidget::changed, this, [this] {
62 if ( !mBlockChangedSignal )
63 {
64 emit changed();
65 }
66 } );
67}
68
69void QgsProcessingAggregatePanelWidget::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 if ( mSkipConfirmDialog )
83 {
84 return;
85 }
86
87 QMessageBox dlg( this );
88 dlg.setText( tr( "Do you want to reset the field mapping?" ) );
89 dlg.setStandardButtons(
90 QMessageBox::StandardButtons( QMessageBox::Yes | QMessageBox::No )
91 );
92 dlg.setDefaultButton( QMessageBox::No );
93 if ( dlg.exec() == QMessageBox::Yes )
94 {
95 loadFieldsFromLayer();
96 }
97}
98
99QgsVectorLayer *QgsProcessingAggregatePanelWidget::layer()
100{
101 return mLayer;
102}
103
104QVariant QgsProcessingAggregatePanelWidget::value() const
105{
106 const QList<QgsAggregateMappingModel::Aggregate> mapping = mFieldsView->mapping();
107
108 QVariantList results;
109 results.reserve( mapping.size() );
110 for ( const QgsAggregateMappingModel::Aggregate &aggregate : mapping )
111 {
112 QVariantMap def;
113 def.insert( u"name"_s, aggregate.field.name() );
114 def.insert( u"type"_s, static_cast<int>( aggregate.field.type() ) );
115 def.insert( u"type_name"_s, aggregate.field.typeName() );
116 def.insert( u"length"_s, aggregate.field.length() );
117 def.insert( u"precision"_s, aggregate.field.precision() );
118 def.insert( u"sub_type"_s, static_cast<int>( aggregate.field.subType() ) );
119 def.insert( u"input"_s, aggregate.source );
120 def.insert( u"aggregate"_s, aggregate.aggregate );
121 def.insert( u"delimiter"_s, aggregate.delimiter );
122 results.append( def );
123 }
124 return results;
125}
126
127void QgsProcessingAggregatePanelWidget::setValue( const QVariant &value )
128{
129 if ( value.userType() != QMetaType::Type::QVariantList )
130 return;
131
132 QList<QgsAggregateMappingModel::Aggregate> aggregates;
133
134 const QVariantList fields = value.toList();
135 aggregates.reserve( fields.size() );
136 for ( const QVariant &field : fields )
137 {
138 const QVariantMap map = field.toMap();
139 const 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() ) );
140
142 aggregate.field = f;
143
144 aggregate.source = map.value( u"input"_s ).toString();
145 aggregate.aggregate = map.value( u"aggregate"_s ).toString();
146 aggregate.delimiter = map.value( u"delimiter"_s ).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( u"new_field"_s ) );
178 const QModelIndex index = mModel->index( rowCount, 0 );
179 mFieldsView->selectionModel()->select(
180 index,
181 QItemSelectionModel::SelectionFlags(
182 QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current | QItemSelectionModel::Rows
183 )
184 );
185 mFieldsView->scrollTo( index );
186}
187
188void QgsProcessingAggregatePanelWidget::loadLayerFields()
189{
190 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( mLayerCombo->currentLayer() ) )
191 {
192 mFieldsView->setSourceFields( vl->fields() );
193 }
194}
195
196//
197// QgsProcessingAggregateParameterDefinitionWidget
198//
199
200QgsProcessingAggregateParameterDefinitionWidget::QgsProcessingAggregateParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm, QWidget *parent )
201 : QgsProcessingAbstractParameterDefinitionWidget( context, widgetContext, definition, algorithm, parent )
202{
203 QVBoxLayout *vlayout = new QVBoxLayout();
204 vlayout->setContentsMargins( 0, 0, 0, 0 );
205
206 vlayout->addWidget( new QLabel( tr( "Parent layer" ) ) );
207
208 mParentLayerComboBox = new QComboBox();
209 mParentLayerComboBox->addItem( tr( "None" ), QVariant() );
210
211 QString initialParent;
212 if ( const QgsProcessingParameterAggregate *aggregateParam = dynamic_cast<const QgsProcessingParameterAggregate *>( definition ) )
213 initialParent = aggregateParam->parentLayerParameterName();
214
215 if ( auto *lModel = widgetContext.model() )
216 {
217 // populate combo box with other model input choices
218 const QMap<QString, QgsProcessingModelParameter> components = lModel->parameterComponents();
219 for ( auto it = components.constBegin(); it != components.constEnd(); ++it )
220 {
221 if ( const QgsProcessingParameterFeatureSource *definition = dynamic_cast<const QgsProcessingParameterFeatureSource *>( lModel->parameterDefinition( it.value().parameterName() ) ) )
222 {
223 mParentLayerComboBox->addItem( definition->description(), definition->name() );
224 if ( !initialParent.isEmpty() && initialParent == definition->name() )
225 {
226 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
227 }
228 }
229 else if ( const QgsProcessingParameterVectorLayer *definition = dynamic_cast<const QgsProcessingParameterVectorLayer *>( lModel->parameterDefinition( it.value().parameterName() ) ) )
230 {
231 mParentLayerComboBox->addItem( definition->description(), definition->name() );
232 if ( !initialParent.isEmpty() && initialParent == definition->name() )
233 {
234 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
235 }
236 }
237 }
238 }
239
240 if ( mParentLayerComboBox->count() == 1 && !initialParent.isEmpty() )
241 {
242 // if no parent candidates found, we just add the existing one as a placeholder
243 mParentLayerComboBox->addItem( initialParent, initialParent );
244 mParentLayerComboBox->setCurrentIndex( mParentLayerComboBox->count() - 1 );
245 }
246
247 vlayout->addWidget( mParentLayerComboBox );
248 setLayout( vlayout );
249}
250
251QgsProcessingParameterDefinition *QgsProcessingAggregateParameterDefinitionWidget::createParameter( const QString &name, const QString &description, Qgis::ProcessingParameterFlags flags ) const
252{
253 auto param = std::make_unique<QgsProcessingParameterAggregate>( name, description, mParentLayerComboBox->currentData().toString() );
254 param->setFlags( flags );
255 return param.release();
256}
257
258//
259// QgsProcessingAggregateWidgetWrapper
260//
261
262QgsProcessingAggregateWidgetWrapper::QgsProcessingAggregateWidgetWrapper( const QgsProcessingParameterDefinition *parameter, Qgis::ProcessingMode type, QWidget *parent )
263 : QgsAbstractProcessingParameterWidgetWrapper( parameter, type, parent )
264{
265}
266
267QString QgsProcessingAggregateWidgetWrapper::parameterType() const
268{
270}
271
272QgsAbstractProcessingParameterWidgetWrapper *QgsProcessingAggregateWidgetWrapper::createWidgetWrapper( const QgsProcessingParameterDefinition *parameter, Qgis::ProcessingMode type )
273{
274 return new QgsProcessingAggregateWidgetWrapper( parameter, type );
275}
276
277QWidget *QgsProcessingAggregateWidgetWrapper::createWidget()
278{
279 mPanel = new QgsProcessingAggregatePanelWidget( nullptr );
280 mPanel->setToolTip( parameterDefinition()->toolTip() );
281 mPanel->registerExpressionContextGenerator( this );
282
283 connect( mPanel, &QgsProcessingAggregatePanelWidget::changed, this, [this] {
284 emit widgetValueHasChanged( this );
285 } );
286
287 return mPanel;
288}
289
290QgsProcessingAbstractParameterDefinitionWidget *QgsProcessingAggregateWidgetWrapper::createParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm )
291{
292 return new QgsProcessingAggregateParameterDefinitionWidget( context, widgetContext, definition, algorithm );
293}
294
295void QgsProcessingAggregateWidgetWrapper::postInitialize( const QList<QgsAbstractProcessingParameterWidgetWrapper *> &wrappers )
296{
298 switch ( type() )
299 {
302 {
303 for ( const QgsAbstractProcessingParameterWidgetWrapper *wrapper : wrappers )
304 {
305 if ( wrapper->parameterDefinition()->name() == static_cast<const QgsProcessingParameterAggregate *>( parameterDefinition() )->parentLayerParameterName() )
306 {
307 setParentLayerWrapperValue( wrapper );
308 connect( wrapper, &QgsAbstractProcessingParameterWidgetWrapper::widgetValueHasChanged, this, [this, wrapper] {
309 setParentLayerWrapperValue( wrapper );
310 } );
311 break;
312 }
313 }
314 break;
315 }
316
318 break;
319 }
320}
321
322int QgsProcessingAggregateWidgetWrapper::stretch() const
323{
324 return 1;
325}
326
327void QgsProcessingAggregateWidgetWrapper::setParentLayerWrapperValue( const QgsAbstractProcessingParameterWidgetWrapper *parentWrapper )
328{
329 // evaluate value to layer
330 QgsProcessingContext *context = nullptr;
331 std::unique_ptr<QgsProcessingContext> tmpContext;
332 if ( mProcessingContextGenerator )
333 context = mProcessingContextGenerator->processingContext();
334
335 if ( !context )
336 {
337 tmpContext = std::make_unique<QgsProcessingContext>();
338 context = tmpContext.get();
339 }
340
341 QgsVectorLayer *layer = QgsProcessingParameters::parameterAsVectorLayer( parentWrapper->parameterDefinition(), parentWrapper->parameterValue(), *context );
342 if ( !layer )
343 {
344 if ( mPanel )
345 mPanel->setLayer( nullptr );
346 return;
347 }
348
349 // need to grab ownership of layer if required - otherwise layer may be deleted when context
350 // goes out of scope
351 std::unique_ptr<QgsMapLayer> ownedLayer( context->takeResultLayer( layer->id() ) );
352 if ( ownedLayer && ownedLayer->type() == Qgis::LayerType::Vector )
353 {
354 mParentLayer.reset( qobject_cast<QgsVectorLayer *>( ownedLayer.release() ) );
355 layer = mParentLayer.get();
356 }
357 else
358 {
359 // don't need ownership of this layer - it wasn't owned by context (so e.g. is owned by the project)
360 }
361
362 if ( mPanel )
363 mPanel->setLayer( layer );
364}
365
366void QgsProcessingAggregateWidgetWrapper::setWidgetValue( const QVariant &value, QgsProcessingContext & )
367{
368 if ( mPanel )
369 mPanel->setValue( value );
370}
371
372QVariant QgsProcessingAggregateWidgetWrapper::widgetValue() const
373{
374 return mPanel ? mPanel->value() : QVariant();
375}
376
377QString QgsProcessingAggregateWidgetWrapper::modelerExpressionFormatString() const
378{
379 return tr( "an array of map items, each containing a 'name', 'type', 'aggregate' and 'input' value (and optional 'length' and 'precision' values)." );
380}
381
382const QgsVectorLayer *QgsProcessingAggregateWidgetWrapper::linkedVectorLayer() const
383{
384 if ( mPanel && mPanel->layer() )
385 return mPanel->layer();
386
388}
389
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.
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:56
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...
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 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 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).