QGIS API Documentation 3.34.0-Prizren (ffbdd678812)
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 <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//
37// QgsProcessingAggregatePanelWidget
38//
39
40
41QgsProcessingAggregatePanelWidget::QgsProcessingAggregatePanelWidget( QWidget *parent )
42 : QgsPanelWidget( parent )
43{
44 setupUi( this );
45
46 mModel = mFieldsView->model();
47
48 mLayerCombo->setAllowEmptyLayer( true );
49 mLayerCombo->setFilters( Qgis::LayerFilter::VectorLayer );
50
51 connect( mResetButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::loadFieldsFromLayer );
52 connect( mAddButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::addField );
53 connect( mDeleteButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::removeSelectedFields );
54 connect( mUpButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::moveSelectedFieldsUp );
55 connect( mDownButton, &QPushButton::clicked, mFieldsView, &QgsAggregateMappingWidget::moveSelectedFieldsDown );
56 connect( mLoadLayerFieldsButton, &QPushButton::clicked, this, &QgsProcessingAggregatePanelWidget::loadLayerFields );
57
58 connect( mFieldsView, &QgsAggregateMappingWidget::changed, this, [ = ]
59 {
60 if ( !mBlockChangedSignal )
61 {
62 emit changed();
63 }
64 } );
65}
66
67void QgsProcessingAggregatePanelWidget::setLayer( QgsVectorLayer *layer )
68{
69 if ( layer == mLayer )
70 return;
71
72 mLayer = layer;
73 mFieldsView->setSourceLayer( mLayer );
74 if ( mModel->rowCount() == 0 )
75 {
76 loadFieldsFromLayer();
77 return;
78 }
79
80 QMessageBox dlg( this );
81 dlg.setText( tr( "Do you want to reset the field mapping?" ) );
82 dlg.setStandardButtons(
83 QMessageBox::StandardButtons( QMessageBox::Yes |
84 QMessageBox::No ) );
85 dlg.setDefaultButton( QMessageBox::No );
86 if ( dlg.exec() == QMessageBox::Yes )
87 {
88 loadFieldsFromLayer();
89 }
90}
91
92QgsVectorLayer *QgsProcessingAggregatePanelWidget::layer()
93{
94 return mLayer;
95}
96
97QVariant QgsProcessingAggregatePanelWidget::value() const
98{
99 const QList<QgsAggregateMappingModel::Aggregate> mapping = mFieldsView->mapping();
100
101 QVariantList results;
102 results.reserve( mapping.size() );
103 for ( const QgsAggregateMappingModel::Aggregate &aggregate : mapping )
104 {
105 QVariantMap def;
106 def.insert( QStringLiteral( "name" ), aggregate.field.name() );
107 def.insert( QStringLiteral( "type" ), static_cast< int >( aggregate.field.type() ) );
108 def.insert( QStringLiteral( "type_name" ), aggregate.field.typeName() );
109 def.insert( QStringLiteral( "length" ), aggregate.field.length() );
110 def.insert( QStringLiteral( "precision" ), aggregate.field.precision() );
111 def.insert( QStringLiteral( "sub_type" ), static_cast< int >( aggregate.field.subType() ) );
112 def.insert( QStringLiteral( "input" ), aggregate.source );
113 def.insert( QStringLiteral( "aggregate" ), aggregate.aggregate );
114 def.insert( QStringLiteral( "delimiter" ), aggregate.delimiter );
115 results.append( def );
116 }
117 return results;
118}
119
120void QgsProcessingAggregatePanelWidget::setValue( const QVariant &value )
121{
122 if ( value.type() != QVariant::List )
123 return;
124
125 QList< QgsAggregateMappingModel::Aggregate > aggregates;
126
127 const QVariantList fields = value.toList();
128 aggregates.reserve( fields.size() );
129 for ( const QVariant &field : fields )
130 {
131 const QVariantMap map = field.toMap();
132 const QgsField f( map.value( QStringLiteral( "name" ) ).toString(),
133 static_cast< QVariant::Type >( map.value( QStringLiteral( "type" ), QVariant::Invalid ).toInt() ),
134 map.value( QStringLiteral( "type_name" ), QVariant::typeToName( static_cast< QVariant::Type >( map.value( QStringLiteral( "type" ), QVariant::Invalid ).toInt() ) ) ).toString(),
135 map.value( QStringLiteral( "length" ), 0 ).toInt(),
136 map.value( QStringLiteral( "precision" ), 0 ).toInt(),
137 QString(),
138 static_cast< QVariant::Type >( map.value( QStringLiteral( "sub_type" ), QVariant::Invalid ).toInt() ) );
139
141 aggregate.field = f;
142
143 aggregate.source = map.value( QStringLiteral( "input" ) ).toString();
144 aggregate.aggregate = map.value( QStringLiteral( "aggregate" ) ).toString();
145 aggregate.delimiter = map.value( QStringLiteral( "delimiter" ) ).toString();
146
147 aggregates.append( aggregate );
148 }
149
150 mBlockChangedSignal = true;
151
152 if ( aggregates.size() > 0 )
153 mFieldsView->setMapping( aggregates );
154
155 mBlockChangedSignal = false;
156
157 emit changed();
158}
159
160void QgsProcessingAggregatePanelWidget::registerExpressionContextGenerator( const QgsExpressionContextGenerator *generator )
161{
162 mFieldsView->registerExpressionContextGenerator( generator );
163}
164
165void QgsProcessingAggregatePanelWidget::loadFieldsFromLayer()
166{
167 if ( mLayer )
168 {
169 mFieldsView->setSourceFields( mLayer->fields() );
170 }
171}
172
173void QgsProcessingAggregatePanelWidget::addField()
174{
175 const int rowCount = mModel->rowCount();
176 mModel->appendField( QgsField( QStringLiteral( "new_field" ) ) );
177 const QModelIndex index = mModel->index( rowCount, 0 );
178 mFieldsView->selectionModel()->select(
179 index,
180 QItemSelectionModel::SelectionFlags(
181 QItemSelectionModel::Clear |
182 QItemSelectionModel::Select |
183 QItemSelectionModel::Current |
184 QItemSelectionModel::Rows ) );
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, QgsProcessingParameterDefinition::Flags 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, QgsProcessingGui::WidgetType type, QWidget *parent )
263 : QgsAbstractProcessingParameterWidgetWrapper( parameter, type, parent )
264{
265}
266
267QString QgsProcessingAggregateWidgetWrapper::parameterType() const
268{
270}
271
272QgsAbstractProcessingParameterWidgetWrapper *QgsProcessingAggregateWidgetWrapper::createWidgetWrapper( const QgsProcessingParameterDefinition *parameter, QgsProcessingGui::WidgetType 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, [ = ]
284 {
285 emit widgetValueHasChanged( this );
286 } );
287
288 return mPanel;
289}
290
291QgsProcessingAbstractParameterDefinitionWidget *QgsProcessingAggregateWidgetWrapper::createParameterDefinitionWidget( QgsProcessingContext &context, const QgsProcessingParameterWidgetContext &widgetContext, const QgsProcessingParameterDefinition *definition, const QgsProcessingAlgorithm *algorithm )
292{
293 return new QgsProcessingAggregateParameterDefinitionWidget( context, widgetContext, definition, algorithm );
294}
295
296void QgsProcessingAggregateWidgetWrapper::postInitialize( const QList<QgsAbstractProcessingParameterWidgetWrapper *> &wrappers )
297{
299 switch ( type() )
300 {
303 {
304 for ( const QgsAbstractProcessingParameterWidgetWrapper *wrapper : wrappers )
305 {
306 if ( wrapper->parameterDefinition()->name() == static_cast< const QgsProcessingParameterAggregate * >( parameterDefinition() )->parentLayerParameterName() )
307 {
308 setParentLayerWrapperValue( wrapper );
310 {
311 setParentLayerWrapperValue( wrapper );
312 } );
313 break;
314 }
315 }
316 break;
317 }
318
320 break;
321 }
322}
323
324int QgsProcessingAggregateWidgetWrapper::stretch() const
325{
326 return 1;
327}
328
329void QgsProcessingAggregateWidgetWrapper::setParentLayerWrapperValue( const QgsAbstractProcessingParameterWidgetWrapper *parentWrapper )
330{
331 // evaluate value to layer
332 QgsProcessingContext *context = nullptr;
333 std::unique_ptr< QgsProcessingContext > tmpContext;
334 if ( mProcessingContextGenerator )
335 context = mProcessingContextGenerator->processingContext();
336
337 if ( !context )
338 {
339 tmpContext = std::make_unique< QgsProcessingContext >();
340 context = tmpContext.get();
341 }
342
343 QgsVectorLayer *layer = QgsProcessingParameters::parameterAsVectorLayer( parentWrapper->parameterDefinition(), parentWrapper->parameterValue(), *context );
344 if ( !layer )
345 {
346 if ( mPanel )
347 mPanel->setLayer( nullptr );
348 return;
349 }
350
351 // need to grab ownership of layer if required - otherwise layer may be deleted when context
352 // goes out of scope
353 std::unique_ptr< QgsMapLayer > ownedLayer( context->takeResultLayer( layer->id() ) );
354 if ( ownedLayer && ownedLayer->type() == Qgis::LayerType::Vector )
355 {
356 mParentLayer.reset( qobject_cast< QgsVectorLayer * >( ownedLayer.release() ) );
357 layer = mParentLayer.get();
358 }
359 else
360 {
361 // don't need ownership of this layer - it wasn't owned by context (so e.g. is owned by the project)
362 }
363
364 if ( mPanel )
365 mPanel->setLayer( layer );
366}
367
368void QgsProcessingAggregateWidgetWrapper::setWidgetValue( const QVariant &value, QgsProcessingContext & )
369{
370 if ( mPanel )
371 mPanel->setValue( value );
372}
373
374QVariant QgsProcessingAggregateWidgetWrapper::widgetValue() const
375{
376 return mPanel ? mPanel->value() : QVariant();
377}
378
379QStringList QgsProcessingAggregateWidgetWrapper::compatibleParameterTypes() const
380{
381 return QStringList()
383}
384
385QStringList QgsProcessingAggregateWidgetWrapper::compatibleOutputTypes() const
386{
387 return QStringList();
388}
389
390QString QgsProcessingAggregateWidgetWrapper::modelerExpressionFormatString() const
391{
392 return tr( "an array of map items, each containing a 'name', 'type', 'aggregate' and 'input' value (and optional 'length' and 'precision' values)." );
393}
394
395const QgsVectorLayer *QgsProcessingAggregateWidgetWrapper::linkedVectorLayer() const
396{
397 if ( mPanel && mPanel->layer() )
398 return mPanel->layer();
399
401}
402
404
405
@ Vector
Vector layer.
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() const
Returns the layer's unique ID, which is used to access this layer from QgsProject.
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.
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)