QGIS API Documentation 4.3.0-Master (91d4a333d5d)
Loading...
Searching...
No Matches
qgsattributeform.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsattributeform.cpp
3 --------------------------------------
4 Date : 3.5.2014
5 Copyright : (C) 2014 Matthias Kuhn
6 Email : matthias at opengis dot ch
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
16#include "qgsattributeform.h"
17
19#include "qgsapplication.h"
36#include "qgsfeatureiterator.h"
37#include "qgsfeaturerequest.h"
38#include "qgsfieldmodel.h"
39#include "qgsgui.h"
41#include "qgslogger.h"
42#include "qgsmessagebar.h"
43#include "qgsmessagebaritem.h"
45#include "qgsproject.h"
46#include "qgsprojectutils.h"
47#include "qgspythonrunner.h"
48#include "qgsqmlwidgetwrapper.h"
49#include "qgsrelationmanager.h"
51#include "qgsscrollarea.h"
55#include "qgstabwidget.h"
56#include "qgstexteditwrapper.h"
61#include "qgsvectorlayerutils.h"
62
63#include <QDir>
64#include <QFile>
65#include <QFileInfo>
66#include <QFormLayout>
67#include <QGridLayout>
68#include <QKeyEvent>
69#include <QLabel>
70#include <QMenu>
71#include <QMessageBox>
72#include <QPushButton>
73#include <QString>
74#include <QSvgWidget>
75#include <QTextStream>
76#include <QToolButton>
77#include <QToolTip>
78#include <QUiLoader>
79
80#include "moc_qgsattributeform.cpp"
81
82using namespace Qt::StringLiterals;
83
84int QgsAttributeForm::sFormCounter = 0;
85
87 : QWidget( parent )
88 , mLayer( vl )
89 , mContext( context )
90 , mFormNr( sFormCounter++ )
91 , mEditCommandMessage( tr( "Attributes changed" ) )
92{
93 init();
94 initPython();
96
97 connect( vl, &QgsVectorLayer::updatedFields, this, &QgsAttributeForm::onUpdatedFields );
98 connect( vl, &QgsVectorLayer::beforeAddingExpressionField, this, &QgsAttributeForm::preventFeatureRefresh );
99 connect( vl, &QgsVectorLayer::beforeRemovingExpressionField, this, &QgsAttributeForm::preventFeatureRefresh );
100 connect( vl, &QgsVectorLayer::selectionChanged, this, &QgsAttributeForm::layerSelectionChanged );
101 connect( this, &QgsAttributeForm::modeChanged, this, &QgsAttributeForm::updateContainersVisibility );
102
103 updateContainersVisibility();
104 updateLabels();
105 updateEditableState();
106}
107
109{
110 cleanPython();
111 qDeleteAll( mInterfaces );
112}
113
115{
116 mButtonBox->hide();
117
118 // Make sure that changes are taken into account if somebody tries to figure out if there have been some
121}
122
124{
125 mButtonBox->show();
126
127 disconnect( mLayer, &QgsVectorLayer::beforeModifiedCheck, this, &QgsAttributeForm::save );
128}
129
131{
132 disconnect( mButtonBox, &QDialogButtonBox::accepted, this, &QgsAttributeForm::save );
133 disconnect( mButtonBox, &QDialogButtonBox::rejected, this, &QgsAttributeForm::resetValues );
134}
135
137{
138 mInterfaces.append( iface );
139}
140
142{
143 bool isEditable = false;
144 switch ( mMode )
145 {
152 isEditable = mFeature.isValid() && mLayer->isEditable();
153 break;
154
156 isEditable = mLayer->isEditable();
157 break;
158
160 isEditable = true;
161 break;
162 }
163
164 return isEditable;
165}
166
168{
169 if ( mode == mMode )
170 return;
171
173 {
174 //switching out of multi edit mode triggers a save
175 if ( mUnsavedMultiEditChanges )
176 {
177 // prompt for save
178 int res = QMessageBox::question( this, tr( "Multiedit Attributes" ), tr( "Apply changes to edited features?" ), QMessageBox::Yes | QMessageBox::No );
179 if ( res == QMessageBox::Yes )
180 {
181 save();
182 }
183 }
184 clearMultiEditMessages();
185 }
186 mUnsavedMultiEditChanges = false;
187
188 mMode = mode;
189
190 if ( mButtonBox->isVisible() && mMode == QgsAttributeEditorContext::SingleEditMode )
191 {
193 }
194 else
195 {
196 disconnect( mLayer, &QgsVectorLayer::beforeModifiedCheck, this, &QgsAttributeForm::save );
197 }
198
199 //update all form editor widget modes to match
200 for ( QgsAttributeFormWidget *w : std::as_const( mFormWidgets ) )
201 {
202 switch ( mode )
203 {
206 break;
207
210 break;
211
214 break;
215
218 break;
219
222 break;
223
226 break;
227
230 break;
231
234 break;
235 }
236 }
237 //update all form editor widget modes to match
238 for ( QgsWidgetWrapper *w : std::as_const( mWidgets ) )
239 {
240 QgsAttributeEditorContext newContext = w->context();
241 newContext.setAttributeFormMode( mMode );
242 w->setContext( newContext );
243 }
244
245 auto setRelationWidgetsVisible = [this]( bool relationWidgetsVisible ) {
246 for ( QgsAttributeFormRelationEditorWidget *w : findChildren<QgsAttributeFormRelationEditorWidget *>() )
247 {
248 w->setVisible( relationWidgetsVisible );
249 }
250 };
251
252 switch ( mode )
253 {
255 setRelationWidgetsVisible( true );
256 setFeature( mFeature );
257 mSearchButtonBox->setVisible( false );
258 break;
259
261 setRelationWidgetsVisible( true );
262 synchronizeState();
263 mSearchButtonBox->setVisible( false );
264 break;
265
267 setRelationWidgetsVisible( true );
268 synchronizeState();
269 mSearchButtonBox->setVisible( false );
270 break;
271
273 setRelationWidgetsVisible( true );
274 resetMultiEdit( false );
275 synchronizeState();
276 mSearchButtonBox->setVisible( false );
277 break;
278
280 setRelationWidgetsVisible( true );
281 mSearchButtonBox->setVisible( true );
282 synchronizeState();
284 break;
285
287 setRelationWidgetsVisible( false );
288 mSearchButtonBox->setVisible( false );
289 synchronizeState();
291 break;
292
294 setRelationWidgetsVisible( true );
295 setFeature( mFeature );
296 synchronizeState();
297 mSearchButtonBox->setVisible( false );
298 break;
299
301 setRelationWidgetsVisible( false );
302 synchronizeState();
303 mSearchButtonBox->setVisible( false );
304 break;
305 }
306
307 emit modeChanged( mMode );
308}
309
310void QgsAttributeForm::changeAttribute( const QString &field, const QVariant &value, const QString &hintText )
311{
312 const auto constMWidgets = mWidgets;
313 for ( QgsWidgetWrapper *ww : constMWidgets )
314 {
315 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
316 if ( eww )
317 {
318 if ( eww->field().name() == field )
319 {
320 eww->setValues( value, QVariantList() );
321 eww->setHint( hintText );
322 }
323 // see if the field is present in additional fields of the editor widget
324 int index = eww->additionalFields().indexOf( field );
325 if ( index >= 0 )
326 {
327 QVariant mainValue = eww->value();
328 QVariantList additionalFieldValues = eww->additionalFieldValues();
329 additionalFieldValues[index] = value;
330 eww->setValues( mainValue, additionalFieldValues );
331 eww->setHint( hintText );
332 }
333 }
334 }
335}
336
338{
339 mCurrentFormFeature.setGeometry( geometry );
340}
341
343{
344 mIsSettingFeature = true;
345 mFeature = feature;
346 mCurrentFormFeature = feature;
347
348 switch ( mMode )
349 {
355 {
356 resetValues();
357
358 synchronizeState();
359
360 // Settings of feature is done when we trigger the attribute form interface
361 // Issue https://github.com/qgis/QGIS/issues/29667
362 mIsSettingFeature = false;
363 const auto constMInterfaces = mInterfaces;
364 for ( QgsAttributeFormInterface *iface : constMInterfaces )
365 {
366 iface->featureChanged();
367 }
368 break;
369 }
372 {
373 resetValues();
374 break;
375 }
377 {
378 //ignore setFeature
379 break;
380 }
381 }
382 mIsSettingFeature = false;
383}
384
385bool QgsAttributeForm::saveEdits( QString *error )
386{
387 bool success = true;
388 bool changedLayer = false;
389
390 QgsFeature updatedFeature = QgsFeature( mFeature );
391 const bool updatedFeatureChangedGeometry = !mFeature.geometry().isExactlyEqual( mCurrentFormFeature.geometry() );
392 if ( updatedFeatureChangedGeometry )
393 {
394 mFeature.setGeometry( mCurrentFormFeature.geometry() );
395 }
396
397 if ( mFeature.isValid() || mMode == QgsAttributeEditorContext::AddFeatureMode )
398 {
399 bool doUpdate = false;
400
401 // An add dialog should perform an action by default
402 // and not only if attributes have "changed"
404 {
405 doUpdate = true;
406 }
407
408 QgsAttributes src = mFeature.attributes();
409 QgsAttributes dst = mFeature.attributes();
410
411 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
412 {
413 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
414 if ( eww )
415 {
416 // check for invalid JSON values
417 QgsTextEditWrapper *textEdit = qobject_cast<QgsTextEditWrapper *>( eww );
418 if ( textEdit && textEdit->isInvalidJSON() )
419 {
420 if ( error )
421 *error = tr( "JSON value for %1 is invalid and has not been saved" ).arg( eww->field().name() );
422 return false;
423 }
424 QVariantList dstVars = QVariantList() << dst.at( eww->fieldIdx() );
425 QVariantList srcVars = QVariantList() << eww->value();
426 QList<int> fieldIndexes = QList<int>() << eww->fieldIdx();
427
428 // append additional fields
429 const QStringList additionalFields = eww->additionalFields();
430 for ( const QString &fieldName : additionalFields )
431 {
432 int idx = eww->layer()->fields().lookupField( fieldName );
433 fieldIndexes << idx;
434 dstVars << dst.at( idx );
435 }
436 srcVars.append( eww->additionalFieldValues() );
437
438 Q_ASSERT( dstVars.count() == srcVars.count() );
439
440 for ( int i = 0; i < dstVars.count(); i++ )
441 {
442 if ( !qgsVariantEqual( dstVars[i], srcVars[i] ) && srcVars[i].isValid() )
443 {
444 dst[fieldIndexes[i]] = srcVars[i];
445
446 doUpdate = true;
447 }
448 }
449 }
450 }
451
452 updatedFeature.setAttributes( dst );
453
454 const auto constMInterfaces = mInterfaces;
455 for ( QgsAttributeFormInterface *iface : constMInterfaces )
456 {
457 if ( !iface->acceptChanges( updatedFeature ) )
458 {
459 doUpdate = false;
460 }
461 }
462
463 if ( doUpdate )
464 {
466 {
467 mFeature = updatedFeature;
468 }
470 {
471 mFeature.setValid( true );
472 mLayer->beginEditCommand( mEditCommandMessage );
473 bool res = mLayer->addFeature( updatedFeature );
474 if ( res )
475 {
476 mFeature.setAttributes( updatedFeature.attributes() );
477 mLayer->endEditCommand();
478
479 const QgsFields fields = mLayer->fields();
480 const QgsAttributes newValues = updatedFeature.attributes();
481 const QVariant lastUsedValuesVariant = mLayer->property( "AttributeFormLastUsedValues" );
482 QgsAttributeMap lastUsedValues = lastUsedValuesVariant.isValid() ? lastUsedValuesVariant.value<QgsAttributeMap>() : QgsAttributeMap();
483 const bool reuseAllLastValues = QgsSettingsRegistryCore::settingsDigitizingReuseLastValues->value();
484 for ( int idx = 0; idx < fields.count(); ++idx )
485 {
486 const Qgis::AttributeFormReuseLastValuePolicy reusePolicy = mLayer->editFormConfig().reuseLastValuePolicy( idx );
487 if ( reuseAllLastValues || reusePolicy != Qgis::AttributeFormReuseLastValuePolicy::NotAllowed )
488 {
489 const QVariant rememberLastUsedValuesVariant = mLayer->property( "AttributeFormRememberLastUsedValues" );
490 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
491 if ( !rememberLastUsedValues.contains( idx ) )
492 {
493 const bool remember = reuseAllLastValues || reusePolicy == Qgis::AttributeFormReuseLastValuePolicy::AllowedDefaultOn;
494 rememberLastUsedValues[idx] = remember;
495 mLayer->setProperty( "AttributeFormRememberLastUsedValues", QVariant::fromValue<QMap<int, bool>>( rememberLastUsedValues ) );
496 }
497
498 const QVariant newValue = rememberLastUsedValues[idx] ? newValues.at( idx ) : QVariant();
499 if ( !lastUsedValues.contains( idx ) || lastUsedValues[idx] != newValue )
500 {
501 lastUsedValues[idx] = newValue;
502 QgsDebugMsgLevel( u"Saving %1 for %2"_s.arg( ( newValue.toString() ).arg( idx ) ), 2 );
503 }
504 }
505 }
506 mLayer->setProperty( "AttributeFormLastUsedValues", QVariant::fromValue<QgsAttributeMap>( lastUsedValues ) );
507
509 changedLayer = true;
510 }
511 else
512 mLayer->destroyEditCommand();
513 }
514 else
515 {
516 mLayer->beginEditCommand( mEditCommandMessage );
517
518 QgsAttributeMap newValues;
519 QgsAttributeMap oldValues;
520
521 int editedCount = 0;
522 for ( int i = 0; i < dst.count(); ++i )
523 {
524 if ( qgsVariantEqual( dst.at( i ), src.at( i ) ) // If field is not changed...
525 || !dst.at( i ).isValid() // or the widget returns invalid (== do not change)
526 || !fieldIsEditable( i ) ) // or the field cannot be edited ...
527 {
528 continue;
529 }
530
531 QgsDebugMsgLevel( u"Updating field %1"_s.arg( i ), 2 );
532 QgsDebugMsgLevel( u"dst:'%1' (type:%2, isNull:%3, isValid:%4)"_s.arg( dst.at( i ).toString(), dst.at( i ).typeName() ).arg( QgsVariantUtils::isNull( dst.at( i ) ) ).arg( dst.at( i ).isValid() ), 2 );
533 QgsDebugMsgLevel( u"src:'%1' (type:%2, isNull:%3, isValid:%4)"_s.arg( src.at( i ).toString(), src.at( i ).typeName() ).arg( QgsVariantUtils::isNull( src.at( i ) ) ).arg( src.at( i ).isValid() ), 2 );
534
535 newValues[i] = dst.at( i );
536 oldValues[i] = src.at( i );
537
538 editedCount++;
539 }
540
541 auto context = std::make_unique<QgsVectorLayerToolsContext>();
542 QgsExpressionContext expressionContext = createExpressionContext( updatedFeature );
543 context->setExpressionContext( &expressionContext );
544 success = mLayer->changeAttributeValues( mFeature.id(), newValues, oldValues, false, context.get() ) && editedCount > 0;
545 if ( success )
546 {
547 mFeature.setAttributes( dst );
548 }
549
550 if ( updatedFeatureChangedGeometry && ( success || editedCount == 0 ) )
551 {
552 QgsGeometry geometry = updatedFeature.geometry();
553 success = success || mLayer->changeGeometry( mFeature.id(), geometry, false );
554 if ( success )
555 {
556 mFeature.setGeometry( geometry );
557 }
558 }
559
560 if ( success )
561 {
562 mLayer->endEditCommand();
563 changedLayer = true;
564 }
565 else
566 {
567 mLayer->destroyEditCommand();
568 }
569 }
570 }
571 }
572
573 emit featureSaved( updatedFeature );
574
575 // [MD] Refresh canvas only when absolutely necessary - it interferes with other stuff (#11361).
576 // This code should be revisited - and the signals should be fired (+ layer repainted)
577 // only when actually doing any changes. I am unsure if it is actually a good idea
578 // to call save() whenever some code asks for vector layer's modified status
579 // (which is the case when attribute table is open)
580 if ( changedLayer )
581 mLayer->triggerRepaint();
582
583 return success;
584}
585
586QgsFeature QgsAttributeForm::getUpdatedFeature() const
587{
588 // create updated Feature
589 QgsFeature updatedFeature = QgsFeature( mFeature );
590
591 QgsAttributes featureAttributes = mFeature.attributes();
592 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
593 {
594 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
595 if ( !eww )
596 continue;
597
598 QVariantList dstVars = QVariantList() << featureAttributes.at( eww->fieldIdx() );
599 QVariantList srcVars = QVariantList() << eww->value();
600 QList<int> fieldIndexes = QList<int>() << eww->fieldIdx();
601
602 // append additional fields
603 const QStringList additionalFields = eww->additionalFields();
604 for ( const QString &fieldName : additionalFields )
605 {
606 int idx = eww->layer()->fields().lookupField( fieldName );
607 fieldIndexes << idx;
608 dstVars << featureAttributes.at( idx );
609 }
610 srcVars.append( eww->additionalFieldValues() );
611
612 Q_ASSERT( dstVars.count() == srcVars.count() );
613
614 for ( int i = 0; i < dstVars.count(); i++ )
615 {
616 if ( !qgsVariantEqual( dstVars[i], srcVars[i] ) && srcVars[i].isValid() )
617 featureAttributes[fieldIndexes[i]] = srcVars[i];
618 }
619 }
620 updatedFeature.setAttributes( featureAttributes );
621
622 return updatedFeature;
623}
624
625void QgsAttributeForm::updateValuesDependencies( const int originIdx )
626{
627 updateValuesDependenciesDefaultValues( originIdx );
628 updateValuesDependenciesVirtualFields( originIdx );
629}
630
631void QgsAttributeForm::updateValuesDependenciesDefaultValues( const int originIdx )
632{
633 if ( !mDefaultValueDependencies.contains( originIdx ) )
634 return;
635
636 if ( !mFeature.isValid() )
637 {
638 switch ( mMode )
639 {
646 return;
647
650 break;
651 }
652 }
653
654 // create updated Feature
655 QgsFeature updatedFeature = getUpdatedFeature();
656
657 // go through depending fields and update the fields with defaultexpression
658 QList<QgsWidgetWrapper *> relevantWidgets = mDefaultValueDependencies.values( originIdx );
659 for ( QgsWidgetWrapper *ww : std::as_const( relevantWidgets ) )
660 {
661 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
662 if ( eww )
663 {
664 // Update only on form opening (except when applyOnUpdate is activated)
665 if ( mValuesInitialized && !eww->field().defaultValueDefinition().applyOnUpdate() )
666 continue;
667
668 // Update only when mMode is AddFeatureMode (except when applyOnUpdate is activated)
670 {
671 continue;
672 }
673
674 //do not update when this widget is already updating (avoid recursions)
675 if ( mAlreadyUpdatedFields.contains( eww->fieldIdx() ) )
676 continue;
677
678 QgsExpressionContext context = createExpressionContext( updatedFeature );
679
680 const QVariant value = mLayer->defaultValue( eww->fieldIdx(), updatedFeature, &context );
681 eww->setValue( value );
682 mCurrentFormFeature.setAttribute( eww->field().name(), value );
683 }
684 }
685}
686
687void QgsAttributeForm::updateValuesDependenciesVirtualFields( const int originIdx )
688{
689 if ( !mVirtualFieldsDependencies.contains( originIdx ) )
690 return;
691
692 if ( !mFeature.isValid() )
693 return;
694
695 // create updated Feature
696 QgsFeature updatedFeature = getUpdatedFeature();
697
698 // go through depending fields and update the virtual field with its expression
699 const QList<QgsWidgetWrapper *> relevantWidgets = mVirtualFieldsDependencies.values( originIdx );
700 for ( QgsWidgetWrapper *ww : relevantWidgets )
701 {
702 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
703 if ( !eww )
704 continue;
705
706 //do not update when this widget is already updating (avoid recursions)
707 if ( mAlreadyUpdatedFields.contains( eww->fieldIdx() ) )
708 continue;
709
710 // Update value
711 QgsExpressionContext context = createExpressionContext( updatedFeature );
712 QgsExpression exp( mLayer->expressionField( eww->fieldIdx() ) );
713 const QVariant value = exp.evaluate( &context );
714 updatedFeature.setAttribute( eww->fieldIdx(), value );
715 eww->setValue( value );
716 }
717}
718
719void QgsAttributeForm::updateValuesDependenciesParent()
720{
721 // create updated Feature
722 QgsFeature updatedFeature = getUpdatedFeature();
723 QList<int> updatedFields;
724
725 // go through fields dependent to parent feature value(s)
726 const QSet<QgsEditorWidgetWrapper *> relevantWidgets = mParentDependencies;
727 for ( QgsEditorWidgetWrapper *eww : relevantWidgets )
728 {
729 //do not update when this widget is already updating (avoid recursions)
730 if ( updatedFields.contains( eww->fieldIdx() ) )
731 continue;
732
733 // Update value
734 updatedFields << eww->fieldIdx();
735 QgsExpressionContext context = createExpressionContext( updatedFeature );
736 const QVariant value = mLayer->defaultValue( eww->fieldIdx(), updatedFeature, &context );
737 eww->setValue( value );
738 }
739}
740
741void QgsAttributeForm::updateRelatedLayerFields()
742{
743 // Synchronize dependencies
744 updateRelatedLayerFieldsDependencies();
745
746 if ( mRelatedLayerFieldsDependencies.isEmpty() )
747 return;
748
749 if ( !mFeature.isValid() )
750 return;
751
752 // create updated Feature
753 QgsFeature updatedFeature = getUpdatedFeature();
754
755 // go through depending fields and update the fields with virtual field
756 const QSet<QgsEditorWidgetWrapper *> relevantWidgets = mRelatedLayerFieldsDependencies;
757 for ( QgsEditorWidgetWrapper *eww : relevantWidgets )
758 {
759 //do not update when this widget is already updating (avoid recursions)
760 if ( mAlreadyUpdatedFields.contains( eww->fieldIdx() ) )
761 continue;
762
763 // Update value
764 QgsExpressionContext context = createExpressionContext( updatedFeature );
765 QgsExpression exp( mLayer->expressionField( eww->fieldIdx() ) );
766 QVariant value = exp.evaluate( &context );
767 eww->setValue( value );
768 }
769}
770
771void QgsAttributeForm::resetMultiEdit( bool promptToSave )
772{
773 if ( promptToSave )
774 save();
775
776 mUnsavedMultiEditChanges = false;
777 setMultiEditFeatureIds( mLayer->selectedFeatureIds() );
778}
779
780void QgsAttributeForm::multiEditMessageClicked( const QString &link )
781{
782 clearMultiEditMessages();
783 resetMultiEdit( link == "#apply"_L1 );
784}
785
786void QgsAttributeForm::filterTriggered()
787{
788 QString filter = createFilterExpression();
789 emit filterExpressionSet( filter, ReplaceFilter );
790 if ( mContext.formMode() == QgsAttributeEditorContext::Embed )
792}
793
794void QgsAttributeForm::searchZoomTo()
795{
796 QString filter = createFilterExpression();
797 if ( filter.isEmpty() )
798 return;
799
800 emit zoomToFeatures( filter );
801}
802
803void QgsAttributeForm::searchFlash()
804{
805 QString filter = createFilterExpression();
806 if ( filter.isEmpty() )
807 return;
808
809 emit flashFeatures( filter );
810}
811
812void QgsAttributeForm::filterAndTriggered()
813{
814 QString filter = createFilterExpression();
815 if ( filter.isEmpty() )
816 return;
817
818 if ( mContext.formMode() == QgsAttributeEditorContext::Embed )
820 emit filterExpressionSet( filter, FilterAnd );
821}
822
823void QgsAttributeForm::filterOrTriggered()
824{
825 QString filter = createFilterExpression();
826 if ( filter.isEmpty() )
827 return;
828
829 if ( mContext.formMode() == QgsAttributeEditorContext::Embed )
831 emit filterExpressionSet( filter, FilterOr );
832}
833
834void QgsAttributeForm::pushSelectedFeaturesMessage()
835{
836 int count = mLayer->selectedFeatureCount();
837 if ( count > 0 )
838 {
839 mMessageBar->pushMessage( QString(), tr( "%n matching feature(s) selected", "matching features", count ), Qgis::MessageLevel::Info );
840 }
841 else
842 {
843 mMessageBar->pushMessage( QString(), tr( "No matching features found" ), Qgis::MessageLevel::Info );
844 }
845}
846
847void QgsAttributeForm::displayWarning( const QString &message )
848{
849 mMessageBar->pushMessage( QString(), message, Qgis::MessageLevel::Warning );
850}
851
852void QgsAttributeForm::runSearchSelect( Qgis::SelectBehavior behavior )
853{
854 QString filter = createFilterExpression();
855 if ( filter.isEmpty() )
856 return;
857
858 mLayer->selectByExpression( filter, behavior );
859 pushSelectedFeaturesMessage();
860 if ( mContext.formMode() == QgsAttributeEditorContext::Embed )
862}
863
864void QgsAttributeForm::searchSetSelection()
865{
866 runSearchSelect( Qgis::SelectBehavior::SetSelection );
867}
868
869void QgsAttributeForm::searchAddToSelection()
870{
871 runSearchSelect( Qgis::SelectBehavior::AddToSelection );
872}
873
874void QgsAttributeForm::searchRemoveFromSelection()
875{
877}
878
879void QgsAttributeForm::searchIntersectSelection()
880{
882}
883
884bool QgsAttributeForm::saveMultiEdits()
885{
886 //find changed attributes
887 QgsAttributeMap newAttributeValues;
888 const QList<int> fieldIndexes = mFormEditorWidgets.uniqueKeys();
889 for ( int fieldIndex : fieldIndexes )
890 {
891 const QList<QgsAttributeFormEditorWidget *> widgets = mFormEditorWidgets.values( fieldIndex );
892 if ( !widgets.first()->hasChanged() )
893 continue;
894
895 if ( !widgets.first()->currentValue().isValid() // if the widget returns invalid (== do not change)
896 || !fieldIsEditable( fieldIndex ) ) // or the field cannot be edited ...
897 {
898 continue;
899 }
900
901 // let editor know we've accepted the changes
902 for ( QgsAttributeFormEditorWidget *widget : widgets )
903 widget->changesCommitted();
904
905 newAttributeValues.insert( fieldIndex, widgets.first()->currentValue() );
906 }
907
908 if ( newAttributeValues.isEmpty() )
909 {
910 //nothing to change
911 return true;
912 }
913
914#if 0
915 // prompt for save
916 int res = QMessageBox::information( this, tr( "Multiedit Attributes" ),
917 tr( "Edits will be applied to all selected features." ), QMessageBox::Ok | QMessageBox::Cancel );
918 if ( res != QMessageBox::Ok )
919 {
920 resetMultiEdit();
921 return false;
922 }
923#endif
924
925 mLayer->beginEditCommand( tr( "Updated multiple feature attributes" ) );
926
927 bool success = true;
928
929 const auto constMultiEditFeatureIds = mMultiEditFeatureIds;
930 for ( QgsFeatureId fid : constMultiEditFeatureIds )
931 {
932 QgsAttributeMap::const_iterator aIt = newAttributeValues.constBegin();
933 for ( ; aIt != newAttributeValues.constEnd(); ++aIt )
934 {
935 success &= mLayer->changeAttributeValue( fid, aIt.key(), aIt.value() );
936 }
937 }
938
939 clearMultiEditMessages();
940 if ( success )
941 {
942 mLayer->endEditCommand();
943 mLayer->triggerRepaint();
944 mMultiEditMessageBarItem = new QgsMessageBarItem( tr( "Attribute changes for multiple features applied." ), Qgis::MessageLevel::Success, -1 );
945 }
946 else
947 {
948 mLayer->destroyEditCommand();
949 mMultiEditMessageBarItem = new QgsMessageBarItem( tr( "Changes could not be applied." ), Qgis::MessageLevel::Warning, 0 );
950 }
951
952 if ( !mButtonBox->isVisible() )
953 mMessageBar->pushItem( mMultiEditMessageBarItem );
954 return success;
955}
956
958{
959 return saveWithDetails( nullptr );
960}
961
963{
964 if ( error )
965 error->clear();
966
967 if ( mIsSaving )
968 return true;
969
970 if ( mContext.formMode() == QgsAttributeEditorContext::Embed && !mValidConstraints )
971 {
972 // the feature isn't saved (as per the warning provided), but we return true
973 // so switching features still works
974 return true;
975 }
976
977 for ( QgsWidgetWrapper *wrapper : std::as_const( mWidgets ) )
978 {
979 wrapper->notifyAboutToSave();
980 }
981
982 // only do the dirty checks when editing an existing feature - for new
983 // features we need to add them even if the attributes are unchanged from the initial
984 // default values
985 switch ( mMode )
986 {
991 if ( !mDirty )
992 return true;
993 break;
994
998 break;
999
1001 return true;
1002 }
1003
1004 mIsSaving = true;
1005
1006 bool success = true;
1007
1008 emit beforeSave( success );
1009
1010 // Somebody wants to prevent this form from saving
1011 if ( !success )
1012 return false;
1013
1014 switch ( mMode )
1015 {
1022 success = saveEdits( error );
1023 break;
1024
1026 success = saveMultiEdits();
1027 break;
1028
1030 break;
1031 }
1032
1033 mIsSaving = false;
1034 mUnsavedMultiEditChanges = false;
1035 mDirty = false;
1036
1037 return success;
1038}
1039
1040
1042{
1043 mValuesInitialized = false;
1044 const auto constMWidgets = mWidgets;
1045 for ( QgsWidgetWrapper *ww : constMWidgets )
1046 {
1047 ww->setFeature( mFeature );
1048 }
1049
1050 // Update dependent virtual fields (not default values / not referencing layer values)
1051 for ( QgsWidgetWrapper *ww : constMWidgets )
1052 {
1053 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1054 if ( !eww )
1055 continue;
1056
1057 // Append field index here, so it's not updated recursively
1058 mAlreadyUpdatedFields.append( eww->fieldIdx() );
1059 updateValuesDependenciesVirtualFields( eww->fieldIdx() );
1060 mAlreadyUpdatedFields.removeAll( eww->fieldIdx() );
1061 }
1062
1063 mValuesInitialized = true;
1064 mDirty = false;
1065}
1066
1068{
1069 const auto widgets { findChildren<QgsAttributeFormEditorWidget *>() };
1070 for ( QgsAttributeFormEditorWidget *w : widgets )
1071 {
1072 w->resetSearch();
1073 }
1074}
1075
1076void QgsAttributeForm::clearMultiEditMessages()
1077{
1078 if ( mMultiEditUnsavedMessageBarItem )
1079 {
1080 if ( !mButtonBox->isVisible() )
1081 mMessageBar->popWidget( mMultiEditUnsavedMessageBarItem );
1082 mMultiEditUnsavedMessageBarItem = nullptr;
1083 }
1084 if ( mMultiEditMessageBarItem )
1085 {
1086 if ( !mButtonBox->isVisible() )
1087 mMessageBar->popWidget( mMultiEditMessageBarItem );
1088 mMultiEditMessageBarItem = nullptr;
1089 }
1090}
1091
1092QString QgsAttributeForm::createFilterExpression() const
1093{
1094 QStringList filters;
1095 for ( QgsAttributeFormWidget *w : std::as_const( mFormWidgets ) )
1096 {
1097 QString filter = w->currentFilterExpression();
1098 if ( !filter.isEmpty() )
1099 filters << filter;
1100 }
1101
1102 if ( filters.isEmpty() )
1103 return QString();
1104
1105 QString filter = filters.join( ") AND ("_L1 ).prepend( '(' ).append( ')' );
1106 return filter;
1107}
1108
1109QgsExpressionContext QgsAttributeForm::createExpressionContext( const QgsFeature &feature ) const
1110{
1111 QgsExpressionContext context;
1113 context.appendScope( QgsExpressionContextUtils::formScope( feature, mContext.attributeFormModeString() ) );
1114 if ( mExtraContextScope )
1115 {
1116 context.appendScope( new QgsExpressionContextScope( *mExtraContextScope.get() ) );
1117 }
1118 if ( mContext.parentFormFeature().isValid() )
1119 {
1120 context.appendScope( QgsExpressionContextUtils::parentFormScope( mContext.parentFormFeature() ) );
1121 }
1122 context.setFeature( feature );
1123 return context;
1124}
1125
1126
1127void QgsAttributeForm::onAttributeChanged( const QVariant &value, const QVariantList &additionalFieldValues )
1128{
1129 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( sender() );
1130 Q_ASSERT( eww );
1131
1132 bool signalEmitted = false;
1133
1134 if ( mValuesInitialized )
1135 mDirty = true;
1136
1137 mCurrentFormFeature.setAttribute( eww->field().name(), value );
1138
1139 // Update other widgets pointing to the same field, required to happen now to insure
1140 // currentFormValuesFeature() gets the right value when processing constraints
1141 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( eww->fieldIdx() );
1142 for ( QgsAttributeFormEditorWidget *formEditorWidget : std::as_const( formEditorWidgets ) )
1143 {
1144 if ( formEditorWidget->editorWidget() == eww )
1145 continue;
1146
1147 // formEditorWidget and eww points to the same field, so update its value
1148 formEditorWidget->editorWidget()->setValue( value );
1149 }
1150
1151 switch ( mMode )
1152 {
1158 {
1160 emit attributeChanged( eww->field().name(), value );
1162 emit widgetValueChanged( eww->field().name(), value, !mIsSettingFeature );
1163
1164 // also emit the signal for additional values
1165 const QStringList additionalFields = eww->additionalFields();
1166 for ( int i = 0; i < additionalFields.count(); i++ )
1167 {
1168 const QString fieldName = additionalFields.at( i );
1169 const QVariant value = additionalFieldValues.at( i );
1170 emit widgetValueChanged( fieldName, value, !mIsSettingFeature );
1171 }
1172
1173 signalEmitted = true;
1174
1175 if ( mValuesInitialized )
1176 updateJoinedFields( *eww );
1177
1178 break;
1179 }
1181 {
1182 if ( !mIsSettingMultiEditFeatures )
1183 {
1184 mUnsavedMultiEditChanges = true;
1185
1186 QLabel *msgLabel = new QLabel( tr( "Unsaved multiedit changes: <a href=\"#apply\">apply changes</a> or <a href=\"#reset\">reset changes</a>." ), mMessageBar );
1187 msgLabel->setAlignment( Qt::AlignLeft | Qt::AlignVCenter );
1188 msgLabel->setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed );
1189 connect( msgLabel, &QLabel::linkActivated, this, &QgsAttributeForm::multiEditMessageClicked );
1190 clearMultiEditMessages();
1191
1192 mMultiEditUnsavedMessageBarItem = new QgsMessageBarItem( msgLabel, Qgis::MessageLevel::Warning );
1193 if ( !mButtonBox->isVisible() )
1194 mMessageBar->pushItem( mMultiEditUnsavedMessageBarItem );
1195
1196 emit widgetValueChanged( eww->field().name(), value, false );
1197 signalEmitted = true;
1198 }
1199 break;
1200 }
1203 //nothing to do
1204 break;
1205 }
1206
1207 updateConstraints( eww );
1208
1209 // Update dependent fields (only if form is not initializing)
1210 if ( mValuesInitialized && !mIsSettingMultiEditFeatures )
1211 {
1212 //append field index here, so it's not updated recursive
1213 mAlreadyUpdatedFields.append( eww->fieldIdx() );
1214 updateValuesDependencies( eww->fieldIdx() );
1215 mAlreadyUpdatedFields.removeAll( eww->fieldIdx() );
1216 }
1217
1218 // Updates expression controlled labels and editable state
1219 updateLabels();
1220 updateEditableState();
1221
1222 if ( !signalEmitted )
1223 {
1225 emit attributeChanged( eww->field().name(), value );
1227 bool attributeHasChanged = !mIsSettingFeature;
1229 attributeHasChanged &= !mIsSettingMultiEditFeatures;
1230
1231 emit widgetValueChanged( eww->field().name(), value, attributeHasChanged );
1232 }
1233}
1234
1235void QgsAttributeForm::updateAllConstraints()
1236{
1237 const auto constMWidgets = mWidgets;
1238 for ( QgsWidgetWrapper *ww : constMWidgets )
1239 {
1240 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1241 if ( eww )
1242 updateConstraints( eww );
1243 }
1244}
1245
1246void QgsAttributeForm::updateConstraints( QgsEditorWidgetWrapper *eww )
1247{
1248 // get the current feature set in the form
1249 QgsFeature ft;
1250 if ( currentFormValuesFeature( ft ) )
1251 {
1252 // if the layer is NOT being edited then we only check layer based constraints, and not
1253 // any constraints enforced by the provider. Because:
1254 // 1. we want to keep browsing features nice and responsive. It's nice to give feedback as to whether
1255 // the value checks out, but not if it's too slow to do so. Some constraints (e.g., unique) can be
1256 // expensive to test. A user can freely remove a layer-based constraint if it proves to be too slow
1257 // to test, but they are unlikely to have any control over provider-side constraints
1258 // 2. the provider has already accepted the value, so presumably it doesn't violate the constraint
1259 // and there's no point rechecking!
1260
1261 // update eww constraint
1262 updateConstraint( ft, eww );
1263
1264 // update eww dependencies constraint
1265 const QList<QgsEditorWidgetWrapper *> deps = constraintDependencies( eww );
1266
1267 for ( QgsEditorWidgetWrapper *depsEww : deps )
1268 updateConstraint( ft, depsEww );
1269
1270 // sync OK button status
1271 synchronizeState();
1272
1273 QgsExpressionContext context = createExpressionContext( ft );
1274
1275 // Recheck visibility/collapsed state for all containers which are controlled by this value
1276 const QVector<ContainerInformation *> infos = mContainerInformationDependency.value( eww->field().name() );
1277 for ( ContainerInformation *info : infos )
1278 {
1279 info->apply( &context );
1280 }
1281 }
1282}
1283
1284void QgsAttributeForm::updateContainersVisibility()
1285{
1286 QgsExpressionContext context = createExpressionContext( mFeature );
1287
1288 const QVector<ContainerInformation *> infos = mContainerVisibilityCollapsedInformation;
1289
1290 for ( ContainerInformation *info : infos )
1291 {
1292 info->apply( &context );
1293 }
1294
1295 // Update the constraints if not in multi edit, because
1296 // when mode changes to multi edit, constraints have been already
1297 // updated and a further update will use current form feature values,
1298 // possibly empty for mixed values, leading to false positive
1299 // constraints violations.
1301 {
1302 updateAllConstraints();
1303 }
1304}
1305
1306void QgsAttributeForm::updateConstraint( const QgsFeature &ft, QgsEditorWidgetWrapper *eww )
1307{
1309
1310 if ( eww->layer()->fields().fieldOrigin( eww->fieldIdx() ) == Qgis::FieldOrigin::Join )
1311 {
1312 int srcFieldIdx;
1313 const QgsVectorLayerJoinInfo *info = eww->layer()->joinBuffer()->joinForFieldIndex( eww->fieldIdx(), eww->layer()->fields(), srcFieldIdx );
1314
1315 if ( info && info->joinLayer() && info->isDynamicFormEnabled() )
1316 {
1317 if ( mJoinedFeatures.contains( info ) )
1318 {
1319 eww->updateConstraint( info->joinLayer(), srcFieldIdx, mJoinedFeatures[info], constraintOrigin );
1320 return;
1321 }
1322 else // if we are here, it means there's not joined field for this feature
1323 {
1324 eww->updateConstraint( QgsFeature() );
1325 return;
1326 }
1327 }
1328 }
1329 // default constraint update
1330 eww->updateConstraint( ft, constraintOrigin );
1331}
1332
1333void QgsAttributeForm::updateLabels()
1334{
1335 if ( !mLabelDataDefinedProperties.isEmpty() )
1336 {
1337 QgsFeature currentFeature;
1338 if ( currentFormValuesFeature( currentFeature ) )
1339 {
1340 QgsExpressionContext context = createExpressionContext( currentFeature );
1341
1342 for ( auto it = mLabelDataDefinedProperties.constBegin(); it != mLabelDataDefinedProperties.constEnd(); ++it )
1343 {
1344 QLabel *label { it.key() };
1345 bool ok;
1346 const QString value { it->valueAsString( context, QString(), &ok ) };
1347 if ( ok && !value.isEmpty() )
1348 {
1349 label->setText( value );
1350 }
1351 }
1352 }
1353 }
1354 if ( !mCustomCommentDataDefinedProperties.isEmpty() )
1355 {
1356 QgsFeature currentFeature;
1357 if ( currentFormValuesFeature( currentFeature ) )
1358 {
1359 QgsExpressionContext context = createExpressionContext( currentFeature );
1360
1361 for ( auto it = mCustomCommentDataDefinedProperties.constBegin(); it != mCustomCommentDataDefinedProperties.constEnd(); ++it )
1362 {
1363 QWidget *labelWidget { it.key() };
1364 bool ok;
1365 const QString value { it->valueAsString( context, QString(), &ok ) };
1366 if ( ok && !value.isEmpty() )
1367 {
1368 const QString fieldName = labelWidget->objectName();
1369 const QgsFields fields = mLayer->fields();
1370 int idx = fields.lookupField( fieldName );
1371
1372 if ( idx >= 0 )
1373 {
1374 labelWidget->setToolTip( QgsFieldModel::fieldToolTipExtended( fields.at( idx ), mLayer, value ) );
1375 }
1376 }
1377 }
1378 }
1379 }
1380}
1381
1382void QgsAttributeForm::updateEditableState()
1383{
1384 if ( !mEditableDataDefinedProperties.isEmpty() )
1385 {
1386 QgsFeature currentFeature;
1387 if ( currentFormValuesFeature( currentFeature ) )
1388 {
1389 QgsExpressionContext context = createExpressionContext( currentFeature );
1390
1391 for ( auto it = mEditableDataDefinedProperties.constBegin(); it != mEditableDataDefinedProperties.constEnd(); ++it )
1392 {
1393 QWidget *w { it.key() };
1394 bool ok;
1395 const bool isEditable { it->valueAsBool( context, true, &ok ) && mLayer && mLayer->isEditable() }; // *NOPAD*
1396 if ( ok )
1397 {
1398 QgsAttributeFormEditorWidget *editorWidget { qobject_cast<QgsAttributeFormEditorWidget *>( w ) };
1399 if ( editorWidget )
1400 {
1401 editorWidget->editorWidget()->setEnabled( isEditable );
1402 }
1403 else
1404 {
1405 w->setEnabled( isEditable );
1406 }
1407 }
1408 }
1409 }
1410 }
1411}
1412
1413bool QgsAttributeForm::currentFormValuesFeature( QgsFeature &feature )
1414{
1415 bool rc = true;
1416 feature = QgsFeature( mFeature );
1417 QgsAttributes dst = feature.attributes();
1418
1419 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1420 {
1421 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1422
1423 if ( !eww )
1424 continue;
1425
1426 if ( dst.count() > eww->fieldIdx() )
1427 {
1428 QVariantList dstVars = QVariantList() << dst.at( eww->fieldIdx() );
1429 QVariantList srcVars = QVariantList() << eww->value();
1430 QList<int> fieldIndexes = QList<int>() << eww->fieldIdx();
1431
1432 // append additional fields
1433 const QStringList additionalFields = eww->additionalFields();
1434 for ( const QString &fieldName : additionalFields )
1435 {
1436 int idx = eww->layer()->fields().lookupField( fieldName );
1437 fieldIndexes << idx;
1438 dstVars << dst.at( idx );
1439 }
1440 srcVars.append( eww->additionalFieldValues() );
1441
1442 Q_ASSERT( dstVars.count() == srcVars.count() );
1443
1444 for ( int i = 0; i < dstVars.count(); i++ )
1445 {
1446 // need to check dstVar.isNull() != srcVar.isNull()
1447 // otherwise if dstVar=NULL and scrVar=0, then dstVar = srcVar
1448 if ( ( !qgsVariantEqual( dstVars[i], srcVars[i] ) || QgsVariantUtils::isNull( dstVars[i] ) != QgsVariantUtils::isNull( srcVars[i] ) ) && srcVars[i].isValid() )
1449 {
1450 dst[fieldIndexes[i]] = srcVars[i];
1451 }
1452 }
1453 }
1454 else
1455 {
1456 rc = false;
1457 break;
1458 }
1459 }
1460
1461 feature.setAttributes( dst );
1462
1463 return rc;
1464}
1465
1466
1467void QgsAttributeForm::registerContainerInformation( QgsAttributeForm::ContainerInformation *info )
1468{
1469 mContainerVisibilityCollapsedInformation.append( info );
1470
1471 const QSet<QString> referencedColumns = info->expression.referencedColumns().unite( info->collapsedExpression.referencedColumns() );
1472
1473 for ( const QString &col : referencedColumns )
1474 {
1475 mContainerInformationDependency[col].append( info );
1476 }
1477}
1478
1479bool QgsAttributeForm::currentFormValidConstraints( QStringList &invalidFields, QStringList &descriptions ) const
1480{
1481 bool valid { true };
1482
1483 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1484 {
1485 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1486 if ( eww )
1487 {
1488 if ( !eww->isValidConstraint() )
1489 {
1490 invalidFields.append( eww->field().displayName() );
1491
1492 descriptions.append( eww->constraintFailureReason() );
1493
1494 if ( eww->isBlockingCommit() )
1495 valid = false; // continue to get all invalid fields
1496 }
1497 }
1498 }
1499
1500 return valid;
1501}
1502
1503bool QgsAttributeForm::currentFormValidHardConstraints( QStringList &invalidFields, QStringList &descriptions ) const
1504{
1505 bool valid { true };
1506
1507 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1508 {
1509 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1510 if ( eww )
1511 {
1512 if ( eww->isBlockingCommit() )
1513 {
1514 invalidFields.append( eww->field().displayName() );
1515 descriptions.append( eww->constraintFailureReason() );
1516 valid = false; // continue to get all invalid fields
1517 }
1518 }
1519 }
1520
1521 return valid;
1522}
1523
1524void QgsAttributeForm::onAttributeAdded( int idx )
1525{
1526 mPreventFeatureRefresh = false;
1527 if ( mFeature.isValid() )
1528 {
1529 QgsAttributes attrs = mFeature.attributes();
1530 attrs.insert( idx, QgsVariantUtils::createNullVariant( layer()->fields().at( idx ).type() ) );
1531 mFeature.setFields( layer()->fields() );
1532 mFeature.setAttributes( attrs );
1533 }
1534 init();
1535 setFeature( mFeature );
1536}
1537
1538void QgsAttributeForm::onAttributeDeleted( int idx )
1539{
1540 mPreventFeatureRefresh = false;
1541 if ( mFeature.isValid() )
1542 {
1543 QgsAttributes attrs = mFeature.attributes();
1544 attrs.remove( idx );
1545 mFeature.setFields( layer()->fields() );
1546 mFeature.setAttributes( attrs );
1547 }
1548 init();
1549 setFeature( mFeature );
1550}
1551
1552void QgsAttributeForm::onRelatedFeaturesChanged()
1553{
1554 updateRelatedLayerFields();
1555}
1556
1557void QgsAttributeForm::onUpdatedFields()
1558{
1559 mPreventFeatureRefresh = false;
1560 if ( mFeature.isValid() )
1561 {
1562 QgsAttributes attrs( layer()->fields().size() );
1563 for ( int i = 0; i < layer()->fields().size(); i++ )
1564 {
1565 int idx = mFeature.fields().indexFromName( layer()->fields().at( i ).name() );
1566 if ( idx != -1 )
1567 {
1568 attrs[i] = mFeature.attributes().at( idx );
1569 if ( mFeature.attributes().at( idx ).userType() != layer()->fields().at( i ).type() )
1570 {
1571 attrs[i].convert( layer()->fields().at( i ).type() );
1572 }
1573 }
1574 else
1575 {
1576 attrs[i] = QgsVariantUtils::createNullVariant( layer()->fields().at( i ).type() );
1577 }
1578 }
1579 mFeature.setFields( layer()->fields() );
1580 mFeature.setAttributes( attrs );
1581 }
1582 init();
1583 setFeature( mFeature );
1584}
1585
1586void QgsAttributeForm::onConstraintStatusChanged( const QString &constraint, const QString &description, const QString &err, QgsEditorWidgetWrapper::ConstraintResult result )
1587{
1588 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( sender() );
1589 Q_ASSERT( eww );
1590
1591 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( eww->fieldIdx() );
1592
1593 for ( QgsAttributeFormEditorWidget *formEditorWidget : formEditorWidgets )
1594 {
1595 formEditorWidget->setConstraintStatus( constraint, description, err, result );
1596 if ( formEditorWidget->editorWidget() != eww )
1597 {
1598 formEditorWidget->editorWidget()->updateConstraint( result, err );
1599 }
1600 }
1601}
1602
1603QList<QgsEditorWidgetWrapper *> QgsAttributeForm::constraintDependencies( QgsEditorWidgetWrapper *w )
1604{
1605 QList<QgsEditorWidgetWrapper *> wDeps;
1606 QString name = w->field().name();
1607
1608 // for each widget in the current form
1609 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1610 {
1611 // get the wrapper
1612 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1613 if ( eww )
1614 {
1615 // compare name to not compare w to itself
1616 QString ewwName = eww->field().name();
1617 if ( name != ewwName )
1618 {
1619 // get expression and referencedColumns
1620 QgsExpression expr = eww->layer()->fields().at( eww->fieldIdx() ).constraints().constraintExpression();
1621
1622 const auto referencedColumns = expr.referencedColumns();
1623
1624 for ( const QString &colName : referencedColumns )
1625 {
1626 if ( name.compare( colName, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
1627 {
1628 wDeps.append( eww );
1629 break;
1630 }
1631 }
1632 }
1633 }
1634 }
1635
1636 return wDeps;
1637}
1638
1639QgsRelationWidgetWrapper *QgsAttributeForm::setupRelationWidgetWrapper( const QgsRelation &rel, const QgsAttributeEditorContext &context )
1640{
1641 return setupRelationWidgetWrapper( QString(), rel, context );
1642}
1643
1644QgsRelationWidgetWrapper *QgsAttributeForm::setupRelationWidgetWrapper( const QString &relationWidgetTypeId, const QgsRelation &rel, const QgsAttributeEditorContext &context )
1645{
1646 QgsRelationWidgetWrapper *rww = new QgsRelationWidgetWrapper( relationWidgetTypeId, mLayer, rel, nullptr, this );
1647 const QVariantMap config = mLayer->editFormConfig().widgetConfig( rel.id() );
1648 rww->setConfig( config );
1649 rww->setContext( context );
1650
1651 return rww;
1652}
1653
1654QToolButton *QgsAttributeForm::createCommentInfoButton( QWidget *labelWidget )
1655{
1656 QToolButton *infoButton = new QToolButton( labelWidget );
1657 infoButton->setIcon( QgsApplication::getThemeIcon( u"/mIndicatorFieldComment.svg"_s, QgsApplication::palette().color( QPalette::WindowText ) ) );
1658 infoButton->setFocusPolicy( Qt::NoFocus );
1659 // looks like an icon, but on click the tooltip of the label appears
1660 infoButton->setAutoRaise( true );
1661 infoButton->setStyleSheet(
1662 "QToolButton { "
1663 " border: none; "
1664 " background-color: transparent; "
1665 " padding: 0px; "
1666 "}"
1667 );
1668 // connect button to label (for the label's tooltip)
1669 connect( infoButton, &QToolButton::clicked, labelWidget, [labelWidget]() { QToolTip::showText( QCursor::pos(), labelWidget->toolTip(), labelWidget ); } );
1670 // invisible per default
1671 infoButton->setVisible( false );
1672 return infoButton;
1673}
1674
1675void QgsAttributeForm::preventFeatureRefresh()
1676{
1677 mPreventFeatureRefresh = true;
1678}
1679
1681{
1682 if ( mPreventFeatureRefresh || mLayer->isEditable() || !mFeature.isValid() )
1683 return;
1684
1685 // reload feature if layer changed although not editable
1686 // (datasource probably changed bypassing QgsVectorLayer)
1687 if ( !mLayer->getFeatures( QgsFeatureRequest().setFilterFid( mFeature.id() ) ).nextFeature( mFeature ) )
1688 return;
1689
1690 init();
1691 setFeature( mFeature );
1692}
1693
1694void QgsAttributeForm::parentFormValueChanged( const QString &attribute, const QVariant &newValue )
1695{
1696 if ( mContext.parentFormFeature().isValid() )
1697 {
1698 QgsFeature parentFormFeature = mContext.parentFormFeature();
1699 parentFormFeature.setAttribute( attribute, newValue );
1700 mContext.setParentFormFeature( parentFormFeature );
1701 }
1702
1703 updateValuesDependenciesParent();
1704
1705 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1706 {
1707 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1708 if ( eww )
1709 {
1710 eww->parentFormValueChanged( attribute, newValue );
1711 }
1712 }
1713}
1714
1716{
1717 return mNeedsGeometry;
1718}
1719
1720void QgsAttributeForm::synchronizeState()
1721{
1722 bool isEditable = editable();
1723
1724 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1725 {
1726 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1727 if ( eww )
1728 {
1729 const QList<QgsAttributeFormEditorWidget *> formWidgets = mFormEditorWidgets.values( eww->fieldIdx() );
1730
1731 for ( QgsAttributeFormEditorWidget *formWidget : formWidgets )
1732 {
1733 formWidget->setConstraintResultVisible( isEditable );
1734 }
1735
1736 eww->setConstraintResultVisible( isEditable );
1737
1738 bool enabled = isEditable && fieldIsEditable( eww->fieldIdx() );
1739 ww->setEnabled( enabled );
1740
1741 updateIcon( eww );
1742 }
1743 else // handle QgsWidgetWrapper different than QgsEditorWidgetWrapper
1744 {
1745 ww->setEnabled( isEditable );
1746 }
1747 }
1748
1749
1751 {
1752 if ( mMode == QgsAttributeEditorContext::Mode::MultiEditMode && mLayer->selectedFeatureCount() == 0 )
1753 {
1754 isEditable = false;
1755 if ( mConstraintsFailMessageBarItem )
1756 {
1757 mMessageBar->popWidget( mConstraintsFailMessageBarItem );
1758 }
1759 mConstraintsFailMessageBarItem = new QgsMessageBarItem( tr( "Multi edit mode requires at least one selected feature." ), Qgis::MessageLevel::Info, -1 );
1760 mMessageBar->pushItem( mConstraintsFailMessageBarItem );
1761 }
1762 else
1763 {
1764 QStringList invalidFields, descriptions;
1765 mValidConstraints = currentFormValidHardConstraints( invalidFields, descriptions );
1766
1767 if ( isEditable && mContext.formMode() == QgsAttributeEditorContext::Embed )
1768 {
1769 if ( !mValidConstraints && !mConstraintsFailMessageBarItem )
1770 {
1771 mConstraintsFailMessageBarItem
1772 = new QgsMessageBarItem( tr( "Changes to this form will not be saved. %n field(s) don't meet their constraints.", "invalid fields", invalidFields.size() ), Qgis::MessageLevel::Warning, -1 );
1773 mMessageBar->pushItem( mConstraintsFailMessageBarItem );
1774 }
1775 else if ( mValidConstraints && mConstraintsFailMessageBarItem )
1776 {
1777 mMessageBar->popWidget( mConstraintsFailMessageBarItem );
1778 mConstraintsFailMessageBarItem = nullptr;
1779 }
1780 }
1781 else if ( mConstraintsFailMessageBarItem )
1782 {
1783 mMessageBar->popWidget( mConstraintsFailMessageBarItem );
1784 mConstraintsFailMessageBarItem = nullptr;
1785 }
1786
1787 isEditable = isEditable & mValidConstraints;
1788 }
1789 }
1790
1791 // change OK button status
1792 QPushButton *okButton = mButtonBox->button( QDialogButtonBox::Ok );
1793 if ( okButton )
1794 {
1795 okButton->setEnabled( isEditable );
1796 }
1797
1798 emit editableChanged();
1799}
1800
1801void QgsAttributeForm::init()
1802{
1803 QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
1804
1805 // Cleanup of any previously shown widget, we start from scratch
1806 QWidget *formWidget = nullptr;
1807 mNeedsGeometry = false;
1808
1809 bool buttonBoxVisible = true;
1810 // Cleanup button box but preserve visibility
1811 if ( mButtonBox )
1812 {
1813 buttonBoxVisible = mButtonBox->isVisible();
1814 delete mButtonBox;
1815 mButtonBox = nullptr;
1816 }
1817
1818 if ( mSearchButtonBox )
1819 {
1820 delete mSearchButtonBox;
1821 mSearchButtonBox = nullptr;
1822 }
1823
1824 qDeleteAll( mWidgets );
1825 mWidgets.clear();
1826
1827 while ( QWidget *w = this->findChild<QWidget *>() )
1828 {
1829 delete w;
1830 }
1831 delete layout();
1832
1833 QVBoxLayout *vl = new QVBoxLayout();
1834 vl->setContentsMargins( 0, 0, 0, 0 );
1835 mMessageBar = new QgsMessageBar( this );
1836 mMessageBar->setSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::Fixed );
1837 vl->addWidget( mMessageBar );
1838
1839 setLayout( vl );
1840
1841 // Get a layout
1842 QGridLayout *layout = new QGridLayout();
1843 QWidget *container = new QWidget();
1844 container->setLayout( layout );
1845 vl->addWidget( container );
1846
1847 mFormEditorWidgets.clear();
1848 mFormWidgets.clear();
1849
1850 // a bar to warn the user with non-blocking messages
1851 setContentsMargins( 0, 0, 0, 0 );
1852
1853 // Try to load Ui-File for layout
1854 if ( mContext.allowCustomUi() && mLayer->editFormConfig().layout() == Qgis::AttributeFormLayout::UiFile && !mLayer->editFormConfig().uiForm().isEmpty() )
1855 {
1856 QgsDebugMsgLevel( u"loading form: %1"_s.arg( mLayer->editFormConfig().uiForm() ), 2 );
1857 const QString path = mLayer->editFormConfig().uiForm();
1859 if ( file && file->open( QFile::ReadOnly ) )
1860 {
1861 QUiLoader loader;
1862
1863 QFileInfo fi( file->fileName() );
1864 loader.setWorkingDirectory( fi.dir() );
1865 formWidget = loader.load( file, this );
1866 if ( formWidget )
1867 {
1868 formWidget->setWindowFlags( Qt::Widget );
1869 layout->addWidget( formWidget );
1870 formWidget->show();
1871 file->close();
1872 mButtonBox = findChild<QDialogButtonBox *>();
1873 createWrappers();
1874
1875 formWidget->installEventFilter( this );
1876 }
1877 }
1878 }
1879
1880 QgsTabWidget *tabWidget = nullptr;
1881
1882 // Tab layout
1883 if ( !formWidget && mLayer->editFormConfig().layout() == Qgis::AttributeFormLayout::DragAndDrop )
1884 {
1885 int row = 0;
1886 int column = 0;
1887 int columnCount = 1;
1888 bool hasRootFields = false;
1889 bool addSpacer = true;
1890
1891 const QList<QgsAttributeEditorElement *> tabs = mLayer->editFormConfig().tabs();
1892
1893 for ( QgsAttributeEditorElement *widgDef : tabs )
1894 {
1895 if ( widgDef->type() == Qgis::AttributeEditorType::Container )
1896 {
1897 QgsAttributeEditorContainer *containerDef = dynamic_cast<QgsAttributeEditorContainer *>( widgDef );
1898 if ( !containerDef )
1899 continue;
1900
1901 switch ( containerDef->type() )
1902 {
1904 {
1905 tabWidget = nullptr;
1906 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, formWidget, mLayer, mContext );
1907 if ( widgetInfo.labelStyle.overrideColor )
1908 {
1909 if ( widgetInfo.labelStyle.color.isValid() )
1910 {
1911 widgetInfo.widget->setStyleSheet( u"QGroupBox::title { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
1912 }
1913 }
1914 if ( widgetInfo.labelStyle.overrideFont )
1915 {
1916 widgetInfo.widget->setFont( widgetInfo.labelStyle.font );
1917 }
1918
1919 layout->addWidget( widgetInfo.widget, row, column, 1, 2 );
1920 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
1921 {
1922 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
1923 }
1924 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
1925 {
1926 layout->setRowStretch( row, widgDef->verticalStretch() );
1927 addSpacer = false;
1928 }
1929 else
1930 {
1931 if ( widgetInfo.expandingNeeded )
1932 {
1933 addSpacer = false;
1934 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
1935 }
1936 else
1937 {
1938 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum );
1939 }
1940 }
1941
1942 if ( containerDef->visibilityExpression().enabled() || containerDef->collapsedExpression().enabled() )
1943 {
1944 registerContainerInformation( new ContainerInformation(
1945 widgetInfo.widget,
1946 containerDef->visibilityExpression().enabled() ? containerDef->visibilityExpression().data() : QgsExpression(),
1947 containerDef->collapsed(),
1948 containerDef->collapsedExpression().enabled() ? containerDef->collapsedExpression().data() : QgsExpression()
1949 ) );
1950 }
1951 column += 2;
1952 break;
1953 }
1954
1956 {
1957 tabWidget = nullptr;
1958 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, formWidget, mLayer, mContext );
1959 layout->addWidget( widgetInfo.widget, row, column, 1, 2 );
1960 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
1961 {
1962 layout->setRowStretch( row, widgDef->verticalStretch() );
1963 addSpacer = false;
1964 }
1965 else
1966 {
1967 if ( widgetInfo.expandingNeeded )
1968 {
1969 addSpacer = false;
1970 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
1971 }
1972 else
1973 {
1974 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum );
1975 }
1976 }
1977 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
1978 {
1979 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
1980 }
1981
1982 if ( containerDef->visibilityExpression().enabled() || containerDef->collapsedExpression().enabled() )
1983 {
1984 registerContainerInformation( new ContainerInformation(
1985 widgetInfo.widget,
1986 containerDef->visibilityExpression().enabled() ? containerDef->visibilityExpression().data() : QgsExpression(),
1987 containerDef->collapsed(),
1988 containerDef->collapsedExpression().enabled() ? containerDef->collapsedExpression().data() : QgsExpression()
1989 ) );
1990 }
1991 column += 2;
1992 break;
1993 }
1994
1996 {
1997 if ( !tabWidget )
1998 {
1999 tabWidget = new QgsTabWidget();
2000 layout->addWidget( tabWidget, row, column, 1, 2 );
2001 column += 2;
2002 }
2003
2004 QWidget *tabPage = new QWidget( tabWidget );
2005 tabWidget->addTab( tabPage, widgDef->name() );
2006 tabWidget->setTabStyle( tabWidget->tabBar()->count() - 1, widgDef->labelStyle() );
2007
2008 if ( containerDef->visibilityExpression().enabled() )
2009 {
2010 registerContainerInformation( new ContainerInformation( tabWidget, tabPage, containerDef->visibilityExpression().data() ) );
2011 }
2012 QGridLayout *tabPageLayout = new QGridLayout();
2013 tabPage->setLayout( tabPageLayout );
2014
2015 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, tabPage, mLayer, mContext );
2016 if ( widgetInfo.expandingNeeded )
2017 {
2018 addSpacer = false;
2019 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
2020 }
2021 tabPageLayout->addWidget( widgetInfo.widget );
2022 break;
2023 }
2024 }
2025 }
2026 else if ( widgDef->type() == Qgis::AttributeEditorType::Relation )
2027 {
2028 hasRootFields = true;
2029 tabWidget = nullptr;
2030 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, container, mLayer, mContext );
2031 QgsCollapsibleGroupBox *collapsibleGroupBox = new QgsCollapsibleGroupBox();
2032
2033 if ( widgetInfo.showLabel )
2034 {
2035 if ( widgetInfo.labelStyle.overrideColor && widgetInfo.labelStyle.color.isValid() )
2036 {
2037 collapsibleGroupBox->setStyleSheet( u"QGroupBox::title { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2038 }
2039
2040 if ( widgetInfo.labelStyle.overrideFont )
2041 {
2042 collapsibleGroupBox->setFont( widgetInfo.labelStyle.font );
2043 }
2044
2045 collapsibleGroupBox->setTitle( widgetInfo.labelText );
2046 }
2047
2048 QVBoxLayout *collapsibleGroupBoxLayout = new QVBoxLayout();
2049 collapsibleGroupBoxLayout->addWidget( widgetInfo.widget );
2050 collapsibleGroupBox->setLayout( collapsibleGroupBoxLayout );
2051
2052 QVBoxLayout *c = new QVBoxLayout();
2053 c->addWidget( collapsibleGroupBox );
2054 layout->addLayout( c, row, column, 1, 2 );
2055
2056 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
2057 layout->setRowStretch( row, widgDef->verticalStretch() );
2058 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
2059 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
2060
2061 column += 2;
2062
2063 // we consider all relation editors should be expanding
2064 addSpacer = false;
2065 }
2066 else
2067 {
2068 hasRootFields = true;
2069 tabWidget = nullptr;
2070 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, container, mLayer, mContext );
2071 QWidget *labelWidget = new QWidget(); //to group label and comment icon in one widget
2072 QLabel *label = new QLabel( widgetInfo.labelText, labelWidget );
2073
2074 if ( widgetInfo.labelStyle.overrideColor )
2075 {
2076 if ( widgetInfo.labelStyle.color.isValid() )
2077 {
2078 label->setStyleSheet( u"QLabel { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2079 }
2080 }
2081
2082 if ( widgetInfo.labelStyle.overrideFont )
2083 {
2084 label->setFont( widgetInfo.labelStyle.font );
2085 }
2086
2087 labelWidget->setToolTip( widgetInfo.toolTip );
2088 if ( columnCount > 1 && !widgetInfo.labelOnTop )
2089 {
2090 label->setAlignment( Qt::AlignRight | Qt::AlignVCenter );
2091 }
2092
2093 label->setBuddy( widgetInfo.widget );
2094
2095 // Indicator button when a comment is available for the field
2096 QToolButton *commentInfoButton = createCommentInfoButton( labelWidget );
2097 // Only visible when there is a comment available
2098 if ( !widgetInfo.hint.isEmpty() )
2099 commentInfoButton->setVisible( true );
2100
2101 // If at least one expanding widget is present do not add a spacer
2102 if ( widgetInfo.widget
2103 && widgetInfo.widget->sizePolicy().verticalPolicy() != QSizePolicy::Fixed
2104 && widgetInfo.widget->sizePolicy().verticalPolicy() != QSizePolicy::Maximum
2105 && widgetInfo.widget->sizePolicy().verticalPolicy() != QSizePolicy::Preferred )
2106 addSpacer = false;
2107
2108 QHBoxLayout *labelLayout = new QHBoxLayout( labelWidget );
2109 labelLayout->addWidget( label );
2110 labelLayout->addWidget( commentInfoButton );
2111 labelLayout->setContentsMargins( 0, 0, 0, 0 );
2112
2113 if ( !widgetInfo.showLabel )
2114 {
2115 QVBoxLayout *c = new QVBoxLayout();
2116 label->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );
2117 c->addWidget( widgetInfo.widget );
2118 layout->addLayout( c, row, column, 1, 2 );
2119
2120 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
2121 {
2122 layout->setRowStretch( row, widgDef->verticalStretch() );
2123 addSpacer = false;
2124 }
2125 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
2126 {
2127 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
2128 }
2129
2130 column += 2;
2131 }
2132 else if ( widgetInfo.labelOnTop )
2133 {
2134 QVBoxLayout *c = new QVBoxLayout();
2135 label->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );
2136 c->addWidget( labelWidget );
2137 c->addWidget( widgetInfo.widget );
2138 layout->addLayout( c, row, column, 1, 2 );
2139
2140 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
2141 {
2142 layout->setRowStretch( row, widgDef->verticalStretch() );
2143 addSpacer = false;
2144 }
2145 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
2146 {
2147 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
2148 }
2149
2150 column += 2;
2151 }
2152 else
2153 {
2154 const int widgetColumn = column + 1;
2155 layout->addWidget( labelWidget, row, column++ );
2156 layout->addWidget( widgetInfo.widget, row, column++ );
2157
2158 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
2159 {
2160 layout->setRowStretch( row, widgDef->verticalStretch() );
2161 addSpacer = false;
2162 }
2163 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( widgetColumn ) )
2164 {
2165 layout->setColumnStretch( widgetColumn, widgDef->horizontalStretch() );
2166 }
2167 }
2168
2169 // Alias DD overrides
2170 if ( widgDef->type() == Qgis::AttributeEditorType::Field )
2171 {
2172 const QgsAttributeEditorField *fieldElement { static_cast<QgsAttributeEditorField *>( widgDef ) };
2173 const int fieldIdx = fieldElement->idx();
2174 if ( fieldIdx >= 0 && fieldIdx < mLayer->fields().count() )
2175 {
2176 const QString fieldName { mLayer->fields().at( fieldIdx ).name() };
2177 label->setObjectName( fieldName );
2178
2179 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::Alias ) )
2180 {
2181 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::Alias ) };
2182 if ( property.isActive() )
2183 {
2184 mLabelDataDefinedProperties[label] = property;
2185 }
2186 }
2187 labelWidget->setObjectName( fieldName );
2188 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::CustomComment ) )
2189 {
2190 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::CustomComment ) };
2191 if ( property.isActive() )
2192 {
2193 mCustomCommentDataDefinedProperties[labelWidget] = property;
2194 commentInfoButton->setVisible( true );
2195 }
2196 }
2197 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::Editable ) )
2198 {
2199 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::Editable ) };
2200 if ( property.isActive() )
2201 {
2202 mEditableDataDefinedProperties[widgetInfo.widget] = property;
2203 }
2204 }
2205 }
2206 }
2207 }
2208
2209 if ( column >= columnCount * 2 )
2210 {
2211 column = 0;
2212 row += 1;
2213 }
2214 }
2215
2216 if ( hasRootFields && addSpacer )
2217 {
2218 QSpacerItem *spacerItem = new QSpacerItem( 20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding );
2219 layout->addItem( spacerItem, row, 0 );
2220 layout->setRowStretch( row, 1 );
2221 }
2222
2223 formWidget = container;
2224 }
2225
2226 // Autogenerate Layout
2227 // If there is still no layout loaded (defined as autogenerate or other methods failed)
2228 mIconMap.clear();
2229
2230 if ( !formWidget )
2231 {
2232 formWidget = new QWidget( this );
2233 QGridLayout *gridLayout = new QGridLayout( formWidget );
2234 formWidget->setLayout( gridLayout );
2235
2236 if ( mContext.formMode() != QgsAttributeEditorContext::Embed )
2237 {
2238 // put the form into a scroll area to nicely handle cases with lots of attributes
2239 QgsScrollArea *scrollArea = new QgsScrollArea( this );
2240 scrollArea->setWidget( formWidget );
2241 scrollArea->setWidgetResizable( true );
2242 scrollArea->setFrameShape( QFrame::NoFrame );
2243 scrollArea->setFrameShadow( QFrame::Plain );
2244 scrollArea->setFocusProxy( this );
2245 layout->addWidget( scrollArea );
2246 }
2247 else
2248 {
2249 layout->addWidget( formWidget );
2250 }
2251
2252 int row = 0;
2253
2254 const QgsFields fields = mLayer->fields();
2255
2256 // Collect non-first fields of composite foreign keys — these should be
2257 // hidden since the RelationReference widget on the first field manages
2258 // all composite key values internally
2259 QSet<int> compositeHiddenFields;
2260 const QList<QgsRelation> referencingRelations = QgsProject::instance()->relationManager()->referencingRelations( mLayer );
2261 for ( const QgsRelation &rel : referencingRelations )
2262 {
2263 if ( rel.type() != Qgis::RelationshipType::Normal )
2264 continue;
2265
2266 const QList<QgsRelation::FieldPair> fieldPairs = rel.fieldPairs();
2267 if ( fieldPairs.size() > 1 )
2268 {
2269 for ( int i = 1; i < fieldPairs.size(); i++ )
2270 {
2271 const int idx = fields.lookupField( fieldPairs.at( i ).referencingField() );
2272 if ( idx >= 0 )
2273 compositeHiddenFields.insert( idx );
2274 }
2275 }
2276 }
2277
2278 for ( const QgsField &field : fields )
2279 {
2280 const QString fieldName = field.name();
2281 int idx = fields.lookupField( fieldName );
2282 if ( idx < 0 )
2283 continue;
2284
2285 if ( compositeHiddenFields.contains( idx ) )
2286 continue;
2287
2288 //show attribute alias if available
2289 QString labelText = mLayer->attributeDisplayName( idx );
2290 labelText.replace( '&', "&&"_L1 ); // need to escape '&' or they'll be replace by _ in the label text
2291
2292 const QgsEditorWidgetSetup widgetSetup = QgsGui::editorWidgetRegistry()->findBest( mLayer, field.name() );
2293
2294 if ( widgetSetup.type() == "Hidden"_L1 )
2295 continue;
2296
2297 bool labelOnTop = mLayer->editFormConfig().labelOnTop( idx );
2298
2299 // This will also create the widget
2300 QWidget *labelWidget = new QWidget(); //to group label and comment icon in one widget
2301 QLabel *label = new QLabel( labelText, labelWidget );
2302 label->setObjectName( fieldName );
2303
2304 labelWidget->setToolTip( QgsFieldModel::fieldToolTipExtended( field, mLayer ) );
2305
2306 // Indicator button when a comment is available for the field
2307 QToolButton *commentInfoButton = createCommentInfoButton( labelWidget );
2308 // Only visible when there is a comment available (not visible when custom comment is an empty string)
2309 if ( !field.customComment().isEmpty() || ( field.customComment().isNull() && !field.comment().isEmpty() ) )
2310 commentInfoButton->setVisible( true );
2311
2312 QSvgWidget *i = new QSvgWidget();
2313 i->setFixedSize( 18, 18 );
2314
2315 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::Alias ) )
2316 {
2317 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::Alias ) };
2318 if ( property.isActive() )
2319 {
2320 mLabelDataDefinedProperties[label] = property;
2321 }
2322 }
2323 labelWidget->setObjectName( fieldName );
2324 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::CustomComment ) )
2325 {
2326 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::CustomComment ) };
2327 if ( property.isActive() )
2328 {
2329 mCustomCommentDataDefinedProperties[labelWidget] = property;
2330 commentInfoButton->setVisible( true );
2331 }
2332 }
2333
2334 QgsEditorWidgetWrapper *eww = QgsGui::editorWidgetRegistry()->create( widgetSetup.type(), mLayer, idx, widgetSetup.config(), nullptr, this, mContext );
2335
2336 QWidget *w = nullptr;
2337 if ( eww )
2338 {
2339 QgsAttributeFormEditorWidget *formWidget = new QgsAttributeFormEditorWidget( eww, widgetSetup.type(), this );
2340 w = formWidget;
2341 mFormEditorWidgets.insert( idx, formWidget );
2342 mFormWidgets.append( formWidget );
2343
2344 const Qgis::AttributeFormReuseLastValuePolicy reusePolicy = mLayer->editFormConfig().reuseLastValuePolicy( idx );
2346 {
2347 bool remember = reusePolicy == Qgis::AttributeFormReuseLastValuePolicy::AllowedDefaultOn;
2348 const QVariant rememberLastUsedValuesVariant = mLayer->property( "AttributeFormRememberLastUsedValues" );
2349 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
2350 if ( rememberLastUsedValues.contains( idx ) )
2351 {
2352 remember = rememberLastUsedValues[idx];
2353 }
2354
2355 formWidget->setRememberLastValue( remember );
2356 connect( formWidget, &QgsAttributeFormEditorWidget::rememberLastValueChanged, this, [this]( int idx, bool remember ) {
2357 const QVariant rememberLastUsedValuesVariant = mLayer->property( "AttributeFormRememberLastUsedValues" );
2358 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
2359 rememberLastUsedValues[idx] = remember;
2360 mLayer->setProperty( "AttributeFormRememberLastUsedValues", QVariant::fromValue<QMap<int, bool>>( rememberLastUsedValues ) );
2361 } );
2362 }
2363
2364 formWidget->createSearchWidgetWrappers( mContext );
2365
2366 label->setBuddy( eww->widget() );
2367
2368 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::Editable ) )
2369 {
2370 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::Editable ) };
2371 if ( property.isActive() )
2372 {
2373 mEditableDataDefinedProperties[formWidget] = property;
2374 }
2375 }
2376 }
2377 else
2378 {
2379 w = new QLabel( u"<p style=\"color: red; font-style: italic;\">%1</p>"_s.arg( tr( "Failed to create widget with type '%1'" ).arg( widgetSetup.type() ) ) );
2380 }
2381
2382
2383 if ( w )
2384 w->setObjectName( field.name() );
2385
2386 if ( eww )
2387 {
2388 mWidgets.append( eww );
2389 mIconMap[eww->widget()] = i;
2390 }
2391
2392 QHBoxLayout *labelLayout = new QHBoxLayout( labelWidget );
2393 labelLayout->addWidget( label );
2394 labelLayout->addWidget( commentInfoButton );
2395 labelLayout->setContentsMargins( 0, 0, 0, 0 );
2396
2397 if ( labelOnTop )
2398 {
2399 gridLayout->addWidget( labelWidget, row++, 0, 1, 2 );
2400 gridLayout->addWidget( w, row++, 0, 1, 2 );
2401 gridLayout->addWidget( i, row++, 0, 1, 2 );
2402 }
2403 else
2404 {
2405 int widgetColumn = 0;
2406 gridLayout->addWidget( labelWidget, row, widgetColumn++ );
2407 gridLayout->addWidget( w, row, widgetColumn++ );
2408 gridLayout->addWidget( i, row++, widgetColumn++ );
2409 }
2410 }
2411
2412 const QList<QgsRelation> relations = QgsProject::instance()->relationManager()->referencedRelations( mLayer );
2413 for ( const QgsRelation &rel : relations )
2414 {
2415 QgsRelationWidgetWrapper *rww = setupRelationWidgetWrapper( u"relation_editor"_s, rel, mContext );
2416
2417 QgsAttributeFormRelationEditorWidget *formWidget = new QgsAttributeFormRelationEditorWidget( rww, this );
2418 formWidget->createSearchWidgetWrappers( mContext );
2419
2420 QgsCollapsibleGroupBox *collapsibleGroupBox = new QgsCollapsibleGroupBox( rel.name() );
2421 QVBoxLayout *collapsibleGroupBoxLayout = new QVBoxLayout();
2422 collapsibleGroupBoxLayout->addWidget( formWidget );
2423 collapsibleGroupBox->setLayout( collapsibleGroupBoxLayout );
2424
2425 gridLayout->addWidget( collapsibleGroupBox, row++, 0, 1, 2 );
2426
2427 mWidgets.append( rww );
2428 mFormWidgets.append( formWidget );
2429 }
2430
2431 if ( QgsProject::instance()->relationManager()->referencedRelations( mLayer ).isEmpty() )
2432 {
2433 QSpacerItem *spacerItem = new QSpacerItem( 20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding );
2434 gridLayout->addItem( spacerItem, row, 0 );
2435 gridLayout->setRowStretch( row, 1 );
2436 row++;
2437 }
2438 }
2439
2440 // Prepare value dependencies
2441 updateFieldDependencies();
2442
2443 if ( !mButtonBox )
2444 {
2445 mButtonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel );
2446 mButtonBox->setObjectName( u"buttonBox"_s );
2447 layout->addWidget( mButtonBox, layout->rowCount(), 0, 1, layout->columnCount() );
2448 }
2449 mButtonBox->setVisible( buttonBoxVisible );
2450
2451 if ( !mSearchButtonBox )
2452 {
2453 mSearchButtonBox = new QWidget();
2454 QHBoxLayout *boxLayout = new QHBoxLayout();
2455 boxLayout->setContentsMargins( 0, 0, 0, 0 );
2456 mSearchButtonBox->setLayout( boxLayout );
2457 mSearchButtonBox->setObjectName( u"searchButtonBox"_s );
2458
2459 QPushButton *clearButton = new QPushButton( tr( "&Reset Form" ), mSearchButtonBox );
2460 connect( clearButton, &QPushButton::clicked, this, &QgsAttributeForm::resetSearch );
2461 boxLayout->addWidget( clearButton );
2462 boxLayout->addStretch( 1 );
2463
2464 QPushButton *flashButton = new QPushButton();
2465 flashButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
2466 flashButton->setText( tr( "&Flash Features" ) );
2467 connect( flashButton, &QToolButton::clicked, this, &QgsAttributeForm::searchFlash );
2468 boxLayout->addWidget( flashButton );
2469
2470 QPushButton *openAttributeTableButton = new QPushButton();
2471 openAttributeTableButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
2472 openAttributeTableButton->setText( tr( "Show in &Table" ) );
2473 openAttributeTableButton->setToolTip( tr( "Open the attribute table editor with the filtered features" ) );
2474 connect( openAttributeTableButton, &QToolButton::clicked, this, [this] { emit openFilteredFeaturesAttributeTable( createFilterExpression() ); } );
2475 boxLayout->addWidget( openAttributeTableButton );
2476
2477 QPushButton *zoomButton = new QPushButton();
2478 zoomButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
2479 zoomButton->setText( tr( "&Zoom to Features" ) );
2480 connect( zoomButton, &QToolButton::clicked, this, &QgsAttributeForm::searchZoomTo );
2481 boxLayout->addWidget( zoomButton );
2482
2483 QToolButton *selectButton = new QToolButton();
2484 selectButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
2485 selectButton->setText( tr( "&Select Features" ) );
2486 selectButton->setIcon( QgsApplication::getThemeIcon( u"/mIconFormSelect.svg"_s ) );
2487 selectButton->setPopupMode( QToolButton::MenuButtonPopup );
2488 selectButton->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
2489 connect( selectButton, &QToolButton::clicked, this, &QgsAttributeForm::searchSetSelection );
2490 QMenu *selectMenu = new QMenu( selectButton );
2491 QAction *selectAction = new QAction( tr( "Select Features" ), selectMenu );
2492 selectAction->setIcon( QgsApplication::getThemeIcon( u"/mIconFormSelect.svg"_s ) );
2493 connect( selectAction, &QAction::triggered, this, &QgsAttributeForm::searchSetSelection );
2494 selectMenu->addAction( selectAction );
2495 QAction *addSelectAction = new QAction( tr( "Add to Current Selection" ), selectMenu );
2496 addSelectAction->setIcon( QgsApplication::getThemeIcon( u"/mIconSelectAdd.svg"_s ) );
2497 connect( addSelectAction, &QAction::triggered, this, &QgsAttributeForm::searchAddToSelection );
2498 selectMenu->addAction( addSelectAction );
2499 QAction *deselectAction = new QAction( tr( "Remove from Current Selection" ), selectMenu );
2500 deselectAction->setIcon( QgsApplication::getThemeIcon( u"/mIconSelectRemove.svg"_s ) );
2501 connect( deselectAction, &QAction::triggered, this, &QgsAttributeForm::searchRemoveFromSelection );
2502 selectMenu->addAction( deselectAction );
2503 QAction *filterSelectAction = new QAction( tr( "Filter Current Selection" ), selectMenu );
2504 filterSelectAction->setIcon( QgsApplication::getThemeIcon( u"/mIconSelectIntersect.svg"_s ) );
2505 connect( filterSelectAction, &QAction::triggered, this, &QgsAttributeForm::searchIntersectSelection );
2506 selectMenu->addAction( filterSelectAction );
2507 selectButton->setMenu( selectMenu );
2508 boxLayout->addWidget( selectButton );
2509
2510 if ( mContext.formMode() == QgsAttributeEditorContext::Embed )
2511 {
2512 QToolButton *filterButton = new QToolButton();
2513 filterButton->setText( tr( "Filter Features" ) );
2514 filterButton->setPopupMode( QToolButton::MenuButtonPopup );
2515 filterButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
2516 connect( filterButton, &QToolButton::clicked, this, &QgsAttributeForm::filterTriggered );
2517 QMenu *filterMenu = new QMenu( filterButton );
2518 QAction *filterAndAction = new QAction( tr( "Filter Within (\"AND\")" ), filterMenu );
2519 connect( filterAndAction, &QAction::triggered, this, &QgsAttributeForm::filterAndTriggered );
2520 filterMenu->addAction( filterAndAction );
2521 QAction *filterOrAction = new QAction( tr( "Extend Filter (\"OR\")" ), filterMenu );
2522 connect( filterOrAction, &QAction::triggered, this, &QgsAttributeForm::filterOrTriggered );
2523 filterMenu->addAction( filterOrAction );
2524 filterButton->setMenu( filterMenu );
2525 boxLayout->addWidget( filterButton );
2526 }
2527 else
2528 {
2529 QPushButton *closeButton = new QPushButton( tr( "Close" ), mSearchButtonBox );
2530 connect( closeButton, &QPushButton::clicked, this, &QgsAttributeForm::closed );
2531 closeButton->setShortcut( Qt::Key_Escape );
2532 boxLayout->addWidget( closeButton );
2533 }
2534
2535 layout->addWidget( mSearchButtonBox, layout->rowCount(), 0, 1, layout->columnCount() );
2536 }
2537 mSearchButtonBox->setVisible( mMode == QgsAttributeEditorContext::SearchMode );
2538
2539 afterWidgetInit();
2540
2541 connect( mButtonBox, &QDialogButtonBox::accepted, this, &QgsAttributeForm::save );
2542 connect( mButtonBox, &QDialogButtonBox::rejected, this, &QgsAttributeForm::resetValues );
2543
2544 connect( mLayer, &QgsVectorLayer::editingStarted, this, &QgsAttributeForm::synchronizeState );
2545 connect( mLayer, &QgsVectorLayer::editingStopped, this, &QgsAttributeForm::synchronizeState );
2546
2547 // This triggers a refresh of the form widget and gives a chance to re-format the
2548 // value to those widgets that have a different representation when in edit mode
2551
2552
2553 const auto constMInterfaces = mInterfaces;
2554 for ( QgsAttributeFormInterface *iface : constMInterfaces )
2555 {
2556 iface->initForm();
2557 }
2558
2559 if ( mContext.formMode() == QgsAttributeEditorContext::Embed || mMode == QgsAttributeEditorContext::SearchMode )
2560 {
2561 hideButtonBox();
2562 }
2563
2564 QApplication::restoreOverrideCursor();
2565}
2566
2567void QgsAttributeForm::cleanPython()
2568{
2569 if ( !mPyFormVarName.isNull() )
2570 {
2571 QString expr = u"if '%1' in locals(): del %1\n"_s.arg( mPyFormVarName );
2572 QgsPythonRunner::run( expr );
2573 }
2574}
2575
2576void QgsAttributeForm::initPython()
2577{
2578 cleanPython();
2579
2580 // Init Python, if init function is not empty and the combo indicates
2581 // the source for the function code
2582 if ( !mLayer->editFormConfig().initFunction().isEmpty() && mLayer->editFormConfig().initCodeSource() != Qgis::AttributeFormPythonInitCodeSource::NoSource )
2583 {
2585 if ( !allowed )
2586 {
2587 mMessageBar->pushMessage( tr( "Security warning" ), tr( "The attribute form contains an embedded script which has been denied execution." ), Qgis::MessageLevel::Warning );
2588 return;
2589 }
2590
2591 QString initFunction = mLayer->editFormConfig().initFunction();
2592 QString initFilePath = mLayer->editFormConfig().initFilePath();
2593 QString initCode;
2594
2595 switch ( mLayer->editFormConfig().initCodeSource() )
2596 {
2598 if ( !initFilePath.isEmpty() )
2599 {
2600 QFile *inputFile = QgsApplication::networkContentFetcherRegistry()->localFile( initFilePath );
2601
2602 if ( inputFile && inputFile->open( QFile::ReadOnly ) )
2603 {
2604 // Read it into a string
2605 QTextStream inf( inputFile );
2606 initCode = inf.readAll();
2607 inputFile->close();
2608 }
2609 else // The file couldn't be opened
2610 {
2611 QgsLogger::warning( u"The external python file path %1 could not be opened!"_s.arg( initFilePath ) );
2612 }
2613 }
2614 else
2615 {
2616 QgsLogger::warning( u"The external python file path is empty!"_s );
2617 }
2618 break;
2619
2621 initCode = mLayer->editFormConfig().initCode();
2622 if ( initCode.isEmpty() )
2623 {
2624 QgsLogger::warning( u"The python code provided in the dialog is empty!"_s );
2625 }
2626 break;
2627
2630 // Nothing to do: the function code should be already in the environment
2631 break;
2632 }
2633
2634 // If we have a function code, run it
2635 if ( !initCode.isEmpty() )
2636 {
2638 {
2639 QgsPythonRunner::run( initCode );
2640 }
2641 else
2642 {
2643 mMessageBar->pushMessage( QString(), tr( "Python macro could not be run due to missing permissions." ), Qgis::MessageLevel::Warning );
2644 }
2645 }
2646
2647 QgsPythonRunner::run( u"import inspect"_s );
2648 QString numArgs;
2649
2650 // Check for eval result
2651 if ( QgsPythonRunner::eval( u"len(inspect.getfullargspec(%1)[0])"_s.arg( initFunction ), numArgs ) )
2652 {
2653 static int sFormId = 0;
2654 mPyFormVarName = u"_qgis_featureform_%1_%2"_s.arg( mFormNr ).arg( sFormId++ );
2655
2656 QString form = u"%1 = sip.wrapinstance( %2, qgis.gui.QgsAttributeForm )"_s.arg( mPyFormVarName ).arg( ( quint64 ) this );
2657
2658 QgsPythonRunner::run( form );
2659
2660 QgsDebugMsgLevel( u"running featureForm init: %1"_s.arg( mPyFormVarName ), 2 );
2661
2662 // Legacy
2663 if ( numArgs == "3"_L1 )
2664 {
2665 addInterface( new QgsAttributeFormLegacyInterface( initFunction, mPyFormVarName, this ) );
2666 }
2667 else
2668 {
2669 // If we get here, it means that the function doesn't accept three arguments
2670 QMessageBox msgBox;
2671 msgBox.setText(
2672 tr( "The python init function (<code>%1</code>) does not accept three arguments as expected!<br>Please check the function name in the <b>Fields</b> tab of the layer properties." ).arg( initFunction )
2673 );
2674 msgBox.exec();
2675#if 0
2676 QString expr = QString( "%1(%2)" )
2677 .arg( mLayer->editFormInit() )
2678 .arg( mPyFormVarName );
2679 QgsAttributeFormInterface *iface = QgsPythonRunner::evalToSipObject<QgsAttributeFormInterface *>( expr, "QgsAttributeFormInterface" );
2680 if ( iface )
2681 addInterface( iface );
2682#endif
2683 }
2684 }
2685 else
2686 {
2687 // If we get here, it means that inspect couldn't find the function
2688 QMessageBox msgBox;
2689 msgBox.setText( tr( "The python init function (<code>%1</code>) could not be found!<br>Please check the function name in the <b>Fields</b> tab of the layer properties." ).arg( initFunction ) );
2690 msgBox.exec();
2691 }
2692 }
2693}
2694
2695QgsAttributeForm::WidgetInfo QgsAttributeForm::createWidgetFromDef( const QgsAttributeEditorElement *widgetDef, QWidget *parent, QgsVectorLayer *vl, QgsAttributeEditorContext &context )
2696{
2697 WidgetInfo newWidgetInfo;
2698
2699 newWidgetInfo.labelStyle = widgetDef->labelStyle();
2700
2701 switch ( widgetDef->type() )
2702 {
2704 {
2705 const QgsAttributeEditorAction *elementDef = dynamic_cast<const QgsAttributeEditorAction *>( widgetDef );
2706 if ( !elementDef )
2707 break;
2708
2709 QgsActionWidgetWrapper *actionWrapper = new QgsActionWidgetWrapper( mLayer, nullptr, this, mMessageBar );
2710 actionWrapper->setAction( elementDef->action( vl ) );
2711 context.setAttributeFormMode( mMode );
2712 actionWrapper->setContext( context );
2713 mWidgets.append( actionWrapper );
2714 newWidgetInfo.widget = actionWrapper->widget();
2715 newWidgetInfo.showLabel = false;
2716
2717 break;
2718 }
2719
2721 {
2722 const QgsAttributeEditorField *fieldDef = dynamic_cast<const QgsAttributeEditorField *>( widgetDef );
2723 if ( !fieldDef )
2724 break;
2725
2726 const QgsFields fields = vl->fields();
2727 int fldIdx = fields.lookupField( fieldDef->name() );
2728 if ( fldIdx < fields.count() && fldIdx >= 0 )
2729 {
2730 const QgsEditorWidgetSetup widgetSetup = QgsGui::editorWidgetRegistry()->findBest( mLayer, fieldDef->name() );
2731
2732 QgsEditorWidgetWrapper *eww = QgsGui::editorWidgetRegistry()->create( widgetSetup.type(), mLayer, fldIdx, widgetSetup.config(), nullptr, this, mContext );
2733 QgsAttributeFormEditorWidget *formWidget = new QgsAttributeFormEditorWidget( eww, widgetSetup.type(), this );
2734 mFormEditorWidgets.insert( fldIdx, formWidget );
2735 mFormWidgets.append( formWidget );
2736
2737 const Qgis::AttributeFormReuseLastValuePolicy reusePolicy = mLayer->editFormConfig().reuseLastValuePolicy( fldIdx );
2739 {
2740 bool remember = reusePolicy == Qgis::AttributeFormReuseLastValuePolicy::AllowedDefaultOn;
2741 const QVariant rememberLastUsedValuesVariant = mLayer->property( "AttributeFormRememberLastUsedValues" );
2742 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
2743 if ( rememberLastUsedValues.contains( fldIdx ) )
2744 {
2745 remember = rememberLastUsedValues[fldIdx];
2746 }
2747 formWidget->setRememberLastValue( remember );
2748 connect( formWidget, &QgsAttributeFormEditorWidget::rememberLastValueChanged, this, [this]( int idx, bool remember ) {
2749 const QVariant rememberLastUsedValuesVariant = mLayer->property( "AttributeFormRememberLastUsedValues" );
2750 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
2751 rememberLastUsedValues[idx] = remember;
2752 mLayer->setProperty( "AttributeFormRememberLastUsedValues", QVariant::fromValue<QMap<int, bool>>( rememberLastUsedValues ) );
2753 } );
2754 }
2755
2756 formWidget->createSearchWidgetWrappers( mContext );
2757
2758 newWidgetInfo.widget = formWidget;
2759 mWidgets.append( eww );
2760
2761 newWidgetInfo.widget->setObjectName( fields.at( fldIdx ).name() );
2762 const QString customComment = fields.at( fldIdx ).customComment();
2763 newWidgetInfo.hint = customComment.isNull() ? fields.at( fldIdx ).comment() : customComment;
2764
2765 newWidgetInfo.labelOnTop = mLayer->editFormConfig().labelOnTop( fldIdx );
2766 newWidgetInfo.labelText = mLayer->attributeDisplayName( fldIdx );
2767 newWidgetInfo.labelText.replace( '&', "&&"_L1 ); // need to escape '&' or they'll be replace by _ in the label text
2768
2769 newWidgetInfo.toolTip = ( QgsFieldModel::fieldToolTipExtended( fields.at( fldIdx ), mLayer ) );
2770 }
2771 else
2772 {
2773 QgsDebugError( u"Attribute form references unknown field '%1' on layer '%2' - skipping widget"_s.arg( fieldDef->name(), mLayer ? mLayer->name() : QString() ) );
2774 newWidgetInfo.labelOnTop = false;
2775 newWidgetInfo.labelText = fieldDef->name();
2776 newWidgetInfo.labelText.replace( '&', "&&"_L1 );
2777 newWidgetInfo.toolTip.clear();
2778 }
2779
2780 newWidgetInfo.showLabel = widgetDef->showLabel();
2781
2782 break;
2783 }
2784
2786 {
2787 const QgsAttributeEditorRelation *relDef = static_cast<const QgsAttributeEditorRelation *>( widgetDef );
2788
2789 QgsRelationWidgetWrapper *rww = setupRelationWidgetWrapper( relDef->relationWidgetTypeId(), relDef->relation(), context );
2790
2791 QgsAttributeFormRelationEditorWidget *formWidget = new QgsAttributeFormRelationEditorWidget( rww, this );
2792 formWidget->createSearchWidgetWrappers( mContext );
2793
2794 // This needs to be after QgsAttributeFormRelationEditorWidget creation, because the widget
2795 // does not exists yet until QgsAttributeFormRelationEditorWidget is created and the setters
2796 // below directly alter the widget and check for it.
2798 rww->setNmRelationId( relDef->nmRelationId() );
2800
2801 mWidgets.append( rww );
2802 mFormWidgets.append( formWidget );
2803
2804 newWidgetInfo.widget = formWidget;
2805 newWidgetInfo.showLabel = relDef->showLabel();
2806 newWidgetInfo.labelText = relDef->label();
2807 if ( newWidgetInfo.labelText.isEmpty() )
2808 newWidgetInfo.labelText = rww->relation().name();
2809 newWidgetInfo.labelOnTop = true;
2810 break;
2811 }
2812
2814 {
2815 const QgsAttributeEditorContainer *container = dynamic_cast<const QgsAttributeEditorContainer *>( widgetDef );
2816 if ( !container )
2817 break;
2818
2819 int columnCount = container->columnCount();
2820
2821 if ( columnCount <= 0 )
2822 columnCount = 1;
2823
2824 QString widgetName;
2825 QWidget *myContainer = nullptr;
2826 bool removeLayoutMargin = false;
2827 switch ( container->type() )
2828 {
2830 {
2831 QgsCollapsibleGroupBoxBasic *groupBox = new QgsCollapsibleGroupBoxBasic();
2832 widgetName = u"QGroupBox"_s;
2833 if ( container->showLabel() )
2834 {
2835 groupBox->setTitle( container->name() );
2836 if ( newWidgetInfo.labelStyle.overrideColor )
2837 {
2838 if ( newWidgetInfo.labelStyle.color.isValid() )
2839 {
2840 groupBox->setStyleSheet( u"QGroupBox::title { color: %1; }"_s.arg( newWidgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2841 }
2842 }
2843 if ( newWidgetInfo.labelStyle.overrideFont )
2844 {
2845 groupBox->setFont( newWidgetInfo.labelStyle.font );
2846 }
2847 }
2848 myContainer = groupBox;
2849 newWidgetInfo.widget = myContainer;
2850 groupBox->setCollapsed( container->collapsed() );
2851 break;
2852 }
2853
2855 {
2856 QWidget *rowWidget = new QWidget();
2857 widgetName = u"Row"_s;
2858 myContainer = rowWidget;
2859 newWidgetInfo.widget = myContainer;
2860 removeLayoutMargin = true;
2861 columnCount = container->children().size();
2862 break;
2863 }
2864
2866 {
2867 myContainer = new QWidget();
2868
2869 QgsScrollArea *scrollArea = new QgsScrollArea( parent );
2870
2871 scrollArea->setWidget( myContainer );
2872 scrollArea->setWidgetResizable( true );
2873 scrollArea->setFrameShape( QFrame::NoFrame );
2874 widgetName = u"QScrollArea QWidget"_s;
2875
2876 newWidgetInfo.widget = scrollArea;
2877 break;
2878 }
2879 }
2880
2881 if ( container->backgroundColor().isValid() )
2882 {
2883 QString style { u"background-color: %1;"_s.arg( container->backgroundColor().name() ) };
2884 newWidgetInfo.widget->setStyleSheet( style );
2885 }
2886
2887 QGridLayout *gbLayout = new QGridLayout();
2888 if ( removeLayoutMargin )
2889 gbLayout->setContentsMargins( 0, 0, 0, 0 );
2890 myContainer->setLayout( gbLayout );
2891
2892 int row = 0;
2893 int column = 0;
2894 bool addSpacer = true;
2895
2896 const QList<QgsAttributeEditorElement *> children = container->children();
2897
2898 for ( QgsAttributeEditorElement *childDef : children )
2899 {
2900 WidgetInfo widgetInfo = createWidgetFromDef( childDef, myContainer, vl, context );
2901
2902 if ( childDef->type() == Qgis::AttributeEditorType::Container )
2903 {
2904 QgsAttributeEditorContainer *containerDef = static_cast<QgsAttributeEditorContainer *>( childDef );
2905 if ( containerDef->visibilityExpression().enabled() || containerDef->collapsedExpression().enabled() )
2906 {
2907 registerContainerInformation( new ContainerInformation(
2908 widgetInfo.widget,
2909 containerDef->visibilityExpression().enabled() ? containerDef->visibilityExpression().data() : QgsExpression(),
2910 containerDef->collapsed(),
2911 containerDef->collapsedExpression().enabled() ? containerDef->collapsedExpression().data() : QgsExpression()
2912 ) );
2913 }
2914 if ( childDef->verticalStretch() == 0 )
2915 {
2916 if ( widgetInfo.expandingNeeded )
2917 {
2918 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
2919 }
2920 else
2921 {
2922 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum );
2923 }
2924 }
2925 }
2926
2927 // column containing the actual widget, not the label
2928 int widgetColumn = column;
2929
2930 if ( widgetInfo.labelText.isNull() || !widgetInfo.showLabel )
2931 {
2932 gbLayout->addWidget( widgetInfo.widget, row, column, 1, 2 );
2933 widgetColumn = column + 1;
2934 column += 2;
2935 }
2936 else
2937 {
2938 QWidget *labelWidget = new QWidget(); //to group label and comment icon in one widget
2939 QLabel *mypLabel = new QLabel( widgetInfo.labelText, labelWidget );
2940
2941 if ( widgetInfo.labelStyle.overrideColor )
2942 {
2943 if ( widgetInfo.labelStyle.color.isValid() )
2944 {
2945 mypLabel->setStyleSheet( u"QLabel { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2946 }
2947 }
2948
2949 if ( widgetInfo.labelStyle.overrideFont )
2950 {
2951 mypLabel->setFont( widgetInfo.labelStyle.font );
2952 }
2953
2954 // Indicator button when a comment is available for the field
2955 QToolButton *commentInfoButton = createCommentInfoButton( labelWidget );
2956 // Only visible when there is a comment available
2957 if ( !widgetInfo.hint.isEmpty() )
2958 commentInfoButton->setVisible( true );
2959
2960 // Alias DD overrides
2961 if ( childDef->type() == Qgis::AttributeEditorType::Field )
2962 {
2963 const QgsAttributeEditorField *fieldDef { static_cast<QgsAttributeEditorField *>( childDef ) };
2964 const QgsFields fields = vl->fields();
2965 const int fldIdx = fieldDef->idx();
2966 if ( fldIdx < fields.count() && fldIdx >= 0 )
2967 {
2968 const QString fieldName { fields.at( fldIdx ).name() };
2969 mypLabel->setObjectName( fieldName );
2970
2971 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::Alias ) )
2972 {
2973 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::Alias ) };
2974 if ( property.isActive() )
2975 {
2976 mLabelDataDefinedProperties[mypLabel] = property;
2977 }
2978 }
2979 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::Editable ) )
2980 {
2981 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::Editable ) };
2982 if ( property.isActive() )
2983 {
2984 mEditableDataDefinedProperties[widgetInfo.widget] = property;
2985 }
2986 }
2987 labelWidget->setObjectName( fieldName );
2988 if ( mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).hasProperty( QgsEditFormConfig::DataDefinedProperty::CustomComment ) )
2989 {
2990 const QgsProperty property { mLayer->editFormConfig().dataDefinedFieldProperties( fieldName ).property( QgsEditFormConfig::DataDefinedProperty::CustomComment ) };
2991 if ( property.isActive() )
2992 {
2993 mCustomCommentDataDefinedProperties[labelWidget] = property;
2994 }
2995 }
2996 }
2997 }
2998
2999 labelWidget->setToolTip( widgetInfo.toolTip );
3000 if ( columnCount > 1 && !widgetInfo.labelOnTop )
3001 {
3002 mypLabel->setAlignment( Qt::AlignRight | Qt::AlignVCenter );
3003 }
3004
3005 mypLabel->setBuddy( widgetInfo.widget );
3006
3007 QHBoxLayout *labelLayout = new QHBoxLayout( labelWidget );
3008 labelLayout->addWidget( mypLabel );
3009 labelLayout->addWidget( commentInfoButton );
3010 labelLayout->setContentsMargins( 0, 0, 0, 0 );
3011
3012 if ( widgetInfo.labelOnTop )
3013 {
3014 widgetColumn = column + 1;
3015 QVBoxLayout *c = new QVBoxLayout();
3016 mypLabel->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );
3017 c->addWidget( labelWidget );
3018 c->layout()->addWidget( widgetInfo.widget );
3019 gbLayout->addLayout( c, row, column, 1, 2 );
3020 column += 2;
3021 }
3022 else
3023 {
3024 widgetColumn = column + 1;
3025 gbLayout->addWidget( labelWidget, row, column++ );
3026 gbLayout->addWidget( widgetInfo.widget, row, column++ );
3027 }
3028 }
3029
3030 const int childHorizontalStretch = childDef->horizontalStretch();
3031 const int existingColumnStretch = gbLayout->columnStretch( widgetColumn );
3032 if ( childHorizontalStretch > 0 && childHorizontalStretch > existingColumnStretch )
3033 {
3034 gbLayout->setColumnStretch( widgetColumn, childHorizontalStretch );
3035 }
3036
3037 if ( childDef->verticalStretch() > 0 && childDef->verticalStretch() > gbLayout->rowStretch( row ) )
3038 {
3039 gbLayout->setRowStretch( row, childDef->verticalStretch() );
3040 }
3041
3042 if ( column >= columnCount * 2 )
3043 {
3044 column = 0;
3045 row += 1;
3046 }
3047
3048 if ( widgetInfo.widget
3049 && widgetInfo.widget->sizePolicy().verticalPolicy() != QSizePolicy::Fixed
3050 && widgetInfo.widget->sizePolicy().verticalPolicy() != QSizePolicy::Maximum
3051 && widgetInfo.widget->sizePolicy().verticalPolicy() != QSizePolicy::Preferred )
3052 addSpacer = false;
3053
3054 // we consider all relation editors should be expanding
3055 if ( qobject_cast<QgsAttributeFormRelationEditorWidget *>( widgetInfo.widget ) )
3056 addSpacer = false;
3057 }
3058
3059 if ( addSpacer )
3060 {
3061 QWidget *spacer = new QWidget();
3062 spacer->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Preferred );
3063 gbLayout->addWidget( spacer, ++row, 0 );
3064 gbLayout->setRowStretch( row, 1 );
3065 }
3066
3067 newWidgetInfo.labelText = QString();
3068 newWidgetInfo.labelOnTop = true;
3069 newWidgetInfo.showLabel = widgetDef->showLabel();
3070 newWidgetInfo.expandingNeeded |= !addSpacer;
3071 break;
3072 }
3073
3075 {
3076 const QgsAttributeEditorQmlElement *elementDef = static_cast<const QgsAttributeEditorQmlElement *>( widgetDef );
3077 QgsQmlWidgetWrapper *qmlWrapper = new QgsQmlWidgetWrapper( mLayer, nullptr, this );
3078 qmlWrapper->setQmlCode( elementDef->qmlCode() );
3079 context.setAttributeFormMode( mMode );
3080 qmlWrapper->setContext( context );
3081
3082 mWidgets.append( qmlWrapper );
3083
3084 newWidgetInfo.widget = qmlWrapper->widget();
3085 newWidgetInfo.labelText = elementDef->name();
3086 newWidgetInfo.labelOnTop = true;
3087 newWidgetInfo.showLabel = widgetDef->showLabel();
3088 break;
3089 }
3090
3092 {
3093 const QgsAttributeEditorHtmlElement *elementDef = static_cast<const QgsAttributeEditorHtmlElement *>( widgetDef );
3094
3095 QgsHtmlWidgetWrapper *htmlWrapper = new QgsHtmlWidgetWrapper( mLayer, nullptr, this );
3096 context.setAttributeFormMode( mMode );
3097 htmlWrapper->setHtmlCode( elementDef->htmlCode() );
3098 htmlWrapper->reinitWidget();
3099 mWidgets.append( htmlWrapper );
3100
3101 newWidgetInfo.widget = htmlWrapper->widget();
3102 newWidgetInfo.labelText = elementDef->name();
3103 newWidgetInfo.labelOnTop = true;
3104 newWidgetInfo.showLabel = widgetDef->showLabel();
3105 mNeedsGeometry |= htmlWrapper->needsGeometry();
3106 break;
3107 }
3108
3110 {
3111 const QgsAttributeEditorTextElement *elementDef = static_cast<const QgsAttributeEditorTextElement *>( widgetDef );
3112
3113 QgsTextWidgetWrapper *textWrapper = new QgsTextWidgetWrapper( mLayer, nullptr, this );
3114 context.setAttributeFormMode( mMode );
3115 textWrapper->setText( elementDef->text() );
3116 textWrapper->reinitWidget();
3117 mWidgets.append( textWrapper );
3118
3119 newWidgetInfo.widget = textWrapper->widget();
3120 newWidgetInfo.labelText = elementDef->name();
3121 newWidgetInfo.labelOnTop = false;
3122 newWidgetInfo.showLabel = widgetDef->showLabel();
3123 mNeedsGeometry |= textWrapper->needsGeometry();
3124 break;
3125 }
3126
3128 {
3129 const QgsAttributeEditorSpacerElement *elementDef = static_cast<const QgsAttributeEditorSpacerElement *>( widgetDef );
3130 QgsSpacerWidgetWrapper *spacerWrapper = new QgsSpacerWidgetWrapper( mLayer, nullptr, this );
3131 spacerWrapper->setDrawLine( elementDef->drawLine() );
3132 context.setAttributeFormMode( mMode );
3133 mWidgets.append( spacerWrapper );
3134
3135 newWidgetInfo.widget = spacerWrapper->widget();
3136 newWidgetInfo.labelOnTop = false;
3137 newWidgetInfo.showLabel = false;
3138 break;
3139 }
3140
3141 default:
3142 QgsDebugError( u"Unknown attribute editor widget type encountered..."_s );
3143 break;
3144 }
3145
3146 return newWidgetInfo;
3147}
3148
3149void QgsAttributeForm::createWrappers()
3150{
3151 QList<QWidget *> myWidgets = findChildren<QWidget *>();
3152 const QList<QgsField> fields = mLayer->fields().toList();
3153
3154 const auto constMyWidgets = myWidgets;
3155 for ( QWidget *myWidget : constMyWidgets )
3156 {
3157 // Check the widget's properties for a relation definition
3158 QVariant vRel = myWidget->property( "qgisRelation" );
3159 if ( vRel.isValid() )
3160 {
3161 QgsRelationManager *relMgr = QgsProject::instance()->relationManager();
3162 QgsRelation relation = relMgr->relation( vRel.toString() );
3163 if ( relation.isValid() )
3164 {
3165 QgsRelationWidgetWrapper *rww = new QgsRelationWidgetWrapper( mLayer, relation, myWidget, this );
3166 rww->setConfig( mLayer->editFormConfig().widgetConfig( relation.id() ) );
3167 rww->setContext( mContext );
3168 rww->widget(); // Will initialize the widget
3169 mWidgets.append( rww );
3170 }
3171 }
3172 else
3173 {
3174 const auto constFields = fields;
3175 for ( const QgsField &field : constFields )
3176 {
3177 if ( field.name() == myWidget->objectName() )
3178 {
3179 int idx = mLayer->fields().lookupField( field.name() );
3180
3181 QgsEditorWidgetWrapper *eww = QgsGui::editorWidgetRegistry()->create( mLayer, idx, myWidget, this, mContext );
3182 mWidgets.append( eww );
3183 }
3184 }
3185 }
3186 }
3187}
3188
3189void QgsAttributeForm::afterWidgetInit()
3190{
3191 bool isFirstEww = true;
3192
3193 const auto constMWidgets = mWidgets;
3194 for ( QgsWidgetWrapper *ww : constMWidgets )
3195 {
3196 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
3197
3198 if ( eww )
3199 {
3200 if ( isFirstEww )
3201 {
3202 setFocusProxy( eww->widget() );
3203 isFirstEww = false;
3204 }
3205
3206 connect( eww, &QgsEditorWidgetWrapper::valuesChanged, this, &QgsAttributeForm::onAttributeChanged, Qt::UniqueConnection );
3207 connect( eww, &QgsEditorWidgetWrapper::constraintStatusChanged, this, &QgsAttributeForm::onConstraintStatusChanged, Qt::UniqueConnection );
3208 }
3209 else
3210 {
3211 QgsRelationWidgetWrapper *relationWidgetWrapper = qobject_cast<QgsRelationWidgetWrapper *>( ww );
3212 if ( relationWidgetWrapper )
3213 {
3214 connect( relationWidgetWrapper, &QgsRelationWidgetWrapper::relatedFeaturesChanged, this, &QgsAttributeForm::onRelatedFeaturesChanged, static_cast<Qt::ConnectionType>( Qt::UniqueConnection | Qt::QueuedConnection ) );
3215 }
3216 }
3217 }
3218}
3219
3220
3221bool QgsAttributeForm::eventFilter( QObject *object, QEvent *e )
3222{
3223 Q_UNUSED( object )
3224
3225 if ( e->type() == QEvent::KeyPress )
3226 {
3227 QKeyEvent *keyEvent = dynamic_cast<QKeyEvent *>( e );
3228 if ( keyEvent && keyEvent->key() == Qt::Key_Escape )
3229 {
3230 // Re-emit to this form so it will be forwarded to parent
3231 event( e );
3232 return true;
3233 }
3234 }
3235
3236 return false;
3237}
3238
3239void QgsAttributeForm::scanForEqualAttributes( QgsFeatureIterator &fit, QSet<int> &mixedValueFields, QHash<int, QVariant> &fieldSharedValues ) const
3240{
3241 mixedValueFields.clear();
3242 fieldSharedValues.clear();
3243
3244 QgsFeature f;
3245 bool first = true;
3246 while ( fit.nextFeature( f ) )
3247 {
3248 for ( int i = 0; i < mLayer->fields().count(); ++i )
3249 {
3250 if ( mixedValueFields.contains( i ) )
3251 continue;
3252
3253 if ( first )
3254 {
3255 fieldSharedValues[i] = f.attribute( i );
3256 }
3257 else
3258 {
3259 if ( fieldSharedValues.value( i ) != f.attribute( i ) )
3260 {
3261 fieldSharedValues.remove( i );
3262 mixedValueFields.insert( i );
3263 }
3264 }
3265 }
3266 first = false;
3267
3268 if ( mixedValueFields.count() == mLayer->fields().count() )
3269 {
3270 // all attributes are mixed, no need to keep scanning
3271 break;
3272 }
3273 }
3274}
3275
3276
3277void QgsAttributeForm::layerSelectionChanged()
3278{
3279 switch ( mMode )
3280 {
3288 break;
3289
3291 resetMultiEdit( true );
3292 break;
3293 }
3294}
3295
3297{
3298 mIsSettingMultiEditFeatures = true;
3299 mMultiEditFeatureIds = fids;
3300
3301 if ( fids.isEmpty() )
3302 {
3303 // no selected features
3304 QMultiMap<int, QgsAttributeFormEditorWidget *>::const_iterator wIt = mFormEditorWidgets.constBegin();
3305 for ( ; wIt != mFormEditorWidgets.constEnd(); ++wIt )
3306 {
3307 wIt.value()->initialize( QVariant() );
3308 }
3309 mIsSettingMultiEditFeatures = false;
3310 return;
3311 }
3312
3313 QgsFeatureIterator fit = mLayer->getFeatures( QgsFeatureRequest().setFilterFids( fids ) );
3314
3315 // Scan through all features to determine which attributes are initially the same
3316 QSet<int> mixedValueFields;
3317 QHash<int, QVariant> fieldSharedValues;
3318 scanForEqualAttributes( fit, mixedValueFields, fieldSharedValues );
3319
3320 // also fetch just first feature
3321 fit = mLayer->getFeatures( QgsFeatureRequest().setFilterFid( *fids.constBegin() ) );
3322 QgsFeature firstFeature;
3323 fit.nextFeature( firstFeature );
3324
3325 // Make this feature the current form feature or the constraints will be evaluated
3326 // on a possibly wrong previously selected/current feature
3327 if ( mCurrentFormFeature.id() != firstFeature.id() )
3328 {
3329 setFeature( firstFeature );
3330 }
3331
3332 const auto constMixedValueFields = mixedValueFields;
3333 for ( int fieldIndex : std::as_const( mixedValueFields ) )
3334 {
3335 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( fieldIndex );
3336 if ( formEditorWidgets.isEmpty() )
3337 continue;
3338
3339 const QStringList additionalFields = formEditorWidgets.first()->editorWidget()->additionalFields();
3340 QVariantList additionalFieldValues;
3341 for ( const QString &additionalField : additionalFields )
3342 additionalFieldValues << firstFeature.attribute( additionalField );
3343
3344 for ( QgsAttributeFormEditorWidget *w : formEditorWidgets )
3345 w->initialize( firstFeature.attribute( fieldIndex ), true, additionalFieldValues );
3346 }
3347 QHash<int, QVariant>::const_iterator sharedValueIt = fieldSharedValues.constBegin();
3348 for ( ; sharedValueIt != fieldSharedValues.constEnd(); ++sharedValueIt )
3349 {
3350 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( sharedValueIt.key() );
3351 if ( formEditorWidgets.isEmpty() )
3352 continue;
3353
3354 bool mixed = false;
3355 const QStringList additionalFields = formEditorWidgets.first()->editorWidget()->additionalFields();
3356 for ( const QString &additionalField : additionalFields )
3357 {
3358 int index = mLayer->fields().indexFromName( additionalField );
3359 if ( constMixedValueFields.contains( index ) )
3360 {
3361 // if additional field are mixed, it is considered as mixed
3362 mixed = true;
3363 break;
3364 }
3365 }
3366 QVariantList additionalFieldValues;
3367 if ( mixed )
3368 {
3369 for ( const QString &additionalField : additionalFields )
3370 additionalFieldValues << firstFeature.attribute( additionalField );
3371 for ( QgsAttributeFormEditorWidget *w : formEditorWidgets )
3372 w->initialize( firstFeature.attribute( sharedValueIt.key() ), true, additionalFieldValues );
3373 }
3374 else
3375 {
3376 for ( const QString &additionalField : additionalFields )
3377 {
3378 int index = mLayer->fields().indexFromName( additionalField );
3379 Q_ASSERT( fieldSharedValues.contains( index ) );
3380 additionalFieldValues << fieldSharedValues.value( index );
3381 }
3382 for ( QgsAttributeFormEditorWidget *w : formEditorWidgets )
3383 w->initialize( sharedValueIt.value(), false, additionalFieldValues );
3384 }
3385 }
3386
3387 setMultiEditFeatureIdsRelations( fids );
3388
3389 mIsSettingMultiEditFeatures = false;
3390}
3391
3393{
3394 if ( mOwnsMessageBar )
3395 delete mMessageBar;
3396 mOwnsMessageBar = false;
3397 mMessageBar = messageBar;
3398}
3399
3401{
3403 {
3404 Q_ASSERT( false );
3405 }
3406
3407 QStringList filters;
3408 for ( QgsAttributeFormWidget *widget : mFormWidgets )
3409 {
3410 QString filter = widget->currentFilterExpression();
3411 if ( !filter.isNull() )
3412 filters << '(' + filter + ')';
3413 }
3414
3415 return filters.join( " AND "_L1 );
3416}
3417
3419{
3420 mExtraContextScope.reset( extraScope );
3421}
3422
3423void QgsAttributeForm::ContainerInformation::apply( QgsExpressionContext *expressionContext )
3424{
3425 const bool newVisibility = expression.evaluate( expressionContext ).toBool();
3426
3427 if ( expression.isValid() && !expression.hasEvalError() && newVisibility != isVisible )
3428 {
3429 if ( tabWidget )
3430 {
3431 tabWidget->setTabVisible( widget, newVisibility );
3432 }
3433 else
3434 {
3435 widget->setVisible( newVisibility );
3436 }
3437
3438 isVisible = newVisibility;
3439 }
3440
3441 const bool newCollapsedState = collapsedExpression.evaluate( expressionContext ).toBool();
3442
3443 if ( collapsedExpression.isValid() && !collapsedExpression.hasEvalError() && newCollapsedState != isCollapsed )
3444 {
3445 if ( QgsCollapsibleGroupBoxBasic * collapsibleGroupBox { qobject_cast<QgsCollapsibleGroupBoxBasic *>( widget ) } )
3446 {
3447 collapsibleGroupBox->setCollapsed( newCollapsedState );
3448 isCollapsed = newCollapsedState;
3449 }
3450 }
3451}
3452
3453void QgsAttributeForm::updateJoinedFields( const QgsEditorWidgetWrapper &eww )
3454{
3455 if ( !eww.layer()->fields().exists( eww.fieldIdx() ) )
3456 return;
3457
3458 QgsFeature formFeature;
3459 QgsField field = eww.layer()->fields().field( eww.fieldIdx() );
3460 QList<const QgsVectorLayerJoinInfo *> infos = eww.layer()->joinBuffer()->joinsWhereFieldIsId( field );
3461
3462 if ( infos.count() == 0 || !currentFormValuesFeature( formFeature ) )
3463 return;
3464
3465 const QString hint = tr( "No feature joined" );
3466 const auto constInfos = infos;
3467 for ( const QgsVectorLayerJoinInfo *info : constInfos )
3468 {
3469 if ( !info->isDynamicFormEnabled() )
3470 continue;
3471
3472 QgsFeature joinFeature = mLayer->joinBuffer()->joinedFeatureOf( info, formFeature );
3473
3474 mJoinedFeatures[info] = joinFeature;
3475
3476 if ( info->hasSubset() )
3477 {
3478 const QStringList subsetNames = QgsVectorLayerJoinInfo::joinFieldNamesSubset( *info );
3479
3480 const auto constSubsetNames = subsetNames;
3481 for ( const QString &field : constSubsetNames )
3482 {
3483 QString prefixedName = info->prefixedFieldName( field );
3484 QVariant val;
3485 QString hintText = hint;
3486
3487 if ( joinFeature.isValid() )
3488 {
3489 val = joinFeature.attribute( field );
3490 hintText.clear();
3491 }
3492
3493 changeAttribute( prefixedName, val, hintText );
3494 }
3495 }
3496 else
3497 {
3498 const QgsFields joinFields = joinFeature.fields();
3499 for ( const QgsField &field : joinFields )
3500 {
3501 QString prefixedName = info->prefixedFieldName( field );
3502 QVariant val;
3503 QString hintText = hint;
3504
3505 if ( joinFeature.isValid() )
3506 {
3507 val = joinFeature.attribute( field.name() );
3508 hintText.clear();
3509 }
3510
3511 changeAttribute( prefixedName, val, hintText );
3512 }
3513 }
3514 }
3515}
3516
3517bool QgsAttributeForm::fieldIsEditable( int fieldIndex ) const
3518{
3521}
3522
3523void QgsAttributeForm::updateFieldDependencies()
3524{
3525 mDefaultValueDependencies.clear();
3526 mVirtualFieldsDependencies.clear();
3527 mRelatedLayerFieldsDependencies.clear();
3528 mParentDependencies.clear();
3529
3530 //create defaultValueDependencies
3531 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
3532 {
3533 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
3534 if ( !eww )
3535 continue;
3536
3537 updateFieldDependenciesParent( eww );
3538 updateFieldDependenciesDefaultValue( eww );
3539 updateFieldDependenciesVirtualFields( eww );
3540 updateRelatedLayerFieldsDependencies( eww );
3541 }
3542}
3543
3544void QgsAttributeForm::updateFieldDependenciesDefaultValue( QgsEditorWidgetWrapper *eww )
3545{
3546 QgsExpression exp( eww->field().defaultValueDefinition().expression() );
3547
3548 if ( exp.needsGeometry() )
3549 mNeedsGeometry = true;
3550
3551 //if a function requires all attributes, it should have the dependency of every field change
3552 if ( exp.referencedColumns().contains( QgsFeatureRequest::ALL_ATTRIBUTES ) )
3553 {
3554 const QList<int> allAttributeIds( mLayer->fields().allAttributesList() );
3555
3556 for ( const int id : allAttributeIds )
3557 {
3558 mDefaultValueDependencies.insertMulti( id, eww );
3559 }
3560 }
3561 else
3562 {
3563 //otherwise just enter for the field depending on
3564 const QSet<QString> referencedColumns = exp.referencedColumns();
3565 for ( const QString &referencedColumn : referencedColumns )
3566 {
3567 mDefaultValueDependencies.insertMulti( mLayer->fields().lookupField( referencedColumn ), eww );
3568 }
3569 }
3570}
3571
3572void QgsAttributeForm::updateFieldDependenciesVirtualFields( QgsEditorWidgetWrapper *eww )
3573{
3574 QString expressionField = eww->layer()->expressionField( eww->fieldIdx() );
3575 if ( expressionField.isEmpty() )
3576 return;
3577
3578 QgsExpression exp( expressionField );
3579
3580 if ( exp.needsGeometry() )
3581 mNeedsGeometry = true;
3582
3583 //if a function requires all attributes, it should have the dependency of every field change
3584 if ( exp.referencedColumns().contains( QgsFeatureRequest::ALL_ATTRIBUTES ) )
3585 {
3586 const QList<int> allAttributeIds( mLayer->fields().allAttributesList() );
3587
3588 for ( const int id : allAttributeIds )
3589 {
3590 mVirtualFieldsDependencies.insertMulti( id, eww );
3591 }
3592 }
3593 else
3594 {
3595 //otherwise just enter for the field depending on
3596 const QSet<QString> referencedColumns = exp.referencedColumns();
3597 for ( const QString &referencedColumn : referencedColumns )
3598 {
3599 mVirtualFieldsDependencies.insertMulti( mLayer->fields().lookupField( referencedColumn ), eww );
3600 }
3601 }
3602}
3603
3604void QgsAttributeForm::updateRelatedLayerFieldsDependencies( QgsEditorWidgetWrapper *eww )
3605{
3606 if ( eww )
3607 {
3608 QString expressionField = eww->layer()->expressionField( eww->fieldIdx() );
3609 if ( expressionField.contains( u"relation_aggregate"_s ) || expressionField.contains( u"get_features"_s ) )
3610 mRelatedLayerFieldsDependencies.insert( eww );
3611 }
3612 else
3613 {
3614 mRelatedLayerFieldsDependencies.clear();
3615 //create defaultValueDependencies
3616 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
3617 {
3618 QgsEditorWidgetWrapper *editorWidgetWrapper = qobject_cast<QgsEditorWidgetWrapper *>( ww );
3619 if ( !editorWidgetWrapper )
3620 continue;
3621
3622 updateRelatedLayerFieldsDependencies( editorWidgetWrapper );
3623 }
3624 }
3625}
3626
3627void QgsAttributeForm::updateFieldDependenciesParent( QgsEditorWidgetWrapper *eww )
3628{
3629 if ( eww && !eww->field().defaultValueDefinition().expression().isEmpty() )
3630 {
3631 const QgsExpression expression( eww->field().defaultValueDefinition().expression() );
3632 const QSet<QString> referencedVariablesAndFunctions = expression.referencedVariables() + expression.referencedFunctions();
3633 for ( const QString &referenced : referencedVariablesAndFunctions )
3634 {
3635 if ( referenced.startsWith( "current_parent"_L1 ) )
3636 {
3637 mParentDependencies.insert( eww );
3638 break;
3639 }
3640 }
3641 }
3642}
3643
3644void QgsAttributeForm::setMultiEditFeatureIdsRelations( const QgsFeatureIds &fids )
3645{
3646 for ( QgsAttributeFormWidget *formWidget : mFormWidgets )
3647 {
3648 QgsAttributeFormRelationEditorWidget *relationEditorWidget = dynamic_cast<QgsAttributeFormRelationEditorWidget *>( formWidget );
3649 if ( !relationEditorWidget )
3650 continue;
3651
3652 relationEditorWidget->setMultiEditFeatureIds( fids );
3653 }
3654}
3655
3656void QgsAttributeForm::updateIcon( QgsEditorWidgetWrapper *eww )
3657{
3658 if ( !eww->widget() || !mIconMap[eww->widget()] )
3659 return;
3660
3661 // no icon by default
3662 mIconMap[eww->widget()]->hide();
3663
3664 if ( !eww->widget()->isEnabled() && mLayer->isEditable() )
3665 {
3666 if ( mLayer->fields().fieldOrigin( eww->fieldIdx() ) == Qgis::FieldOrigin::Join )
3667 {
3668 int srcFieldIndex;
3669 const QgsVectorLayerJoinInfo *info = mLayer->joinBuffer()->joinForFieldIndex( eww->fieldIdx(), mLayer->fields(), srcFieldIndex );
3670
3671 if ( !info )
3672 return;
3673
3674 if ( !info->isEditable() )
3675 {
3676 const QString file = u"/mIconJoinNotEditable.svg"_s;
3677 const QString tooltip = tr( "Join settings do not allow editing" );
3678 reloadIcon( file, tooltip, mIconMap[eww->widget()] );
3679 }
3680 else if ( mMode == QgsAttributeEditorContext::AddFeatureMode && !info->hasUpsertOnEdit() )
3681 {
3682 const QString file = u"mIconJoinHasNotUpsertOnEdit.svg"_s;
3683 const QString tooltip = tr( "Join settings do not allow upsert on edit" );
3684 reloadIcon( file, tooltip, mIconMap[eww->widget()] );
3685 }
3686 else if ( !info->joinLayer()->isEditable() )
3687 {
3688 const QString file = u"/mIconJoinedLayerNotEditable.svg"_s;
3689 const QString tooltip = tr( "Joined layer is not toggled editable" );
3690 reloadIcon( file, tooltip, mIconMap[eww->widget()] );
3691 }
3692 }
3693 }
3694}
3695
3696void QgsAttributeForm::reloadIcon( const QString &file, const QString &tooltip, QSvgWidget *sw )
3697{
3698 sw->load( QgsApplication::iconPath( file ) );
3699 sw->setToolTip( tooltip );
3700 sw->show();
3701}
3702
3704{
3705 const bool reuseAllLastValues = QgsSettingsRegistryCore::settingsDigitizingReuseLastValues->value();
3706 QgsDebugMsgLevel( u"reuseAllLastValues: %1"_s.arg( reuseAllLastValues ), 2 );
3707
3708 const QgsFields fields = layer->fields();
3709 QgsAttributeMap initialAttributeValues;
3710 for ( int idx = 0; idx < fields.count(); ++idx )
3711 {
3712 if ( attributes.contains( idx ) )
3713 {
3714 initialAttributeValues.insert( idx, attributes.value( idx ) );
3715 }
3716 else if ( reuseAllLastValues || layer->editFormConfig().reuseLastValuePolicy( idx ) != Qgis::AttributeFormReuseLastValuePolicy::NotAllowed )
3717 {
3718 const QVariant lastUsedValuesVariant = layer->property( "AttributeFormLastUsedValues" );
3719 const QgsAttributeMap lastUsedValues = lastUsedValuesVariant.isValid() ? lastUsedValuesVariant.value<QgsAttributeMap>() : QgsAttributeMap();
3720 if ( lastUsedValues.contains( idx ) && layer->dataProvider() && layer->dataProvider()->defaultValueClause( idx ) != lastUsedValues[idx] )
3721 {
3722 initialAttributeValues.insert( idx, lastUsedValues[idx] );
3723 }
3724 }
3725 }
3726
3727 return QgsVectorLayerUtils::createFeature( layer, geometry, initialAttributeValues, &context );
3728}
@ Trusted
The project has been determined by the user as trusted.
Definition qgis.h:498
@ Row
A row of editors (horizontal layout).
Definition qgis.h:6306
AttributeFormReuseLastValuePolicy
Attribute form policy for reusing last entered values.
Definition qgis.h:6362
@ AllowedDefaultOn
Reuse of last values allowed and enabled by default.
Definition qgis.h:6364
@ NotAllowed
Reuse of last values not allowed.
Definition qgis.h:6363
@ File
Load the Python code from an external file.
Definition qgis.h:6350
@ Environment
Use the Python code available in the Python environment.
Definition qgis.h:6352
@ NoSource
Do not use Python code at all.
Definition qgis.h:6349
@ Dialog
Use the Python code provided in the dialog.
Definition qgis.h:6351
@ DragAndDrop
"Drag and drop" layout. Needs to be configured.
Definition qgis.h:6320
@ UiFile
Load a .ui file for the layout. Needs to be configured.
Definition qgis.h:6321
@ Warning
Warning message.
Definition qgis.h:162
@ Info
Information message.
Definition qgis.h:161
@ Success
Used for reporting a successful operation.
Definition qgis.h:164
@ Normal
A normal relation.
Definition qgis.h:4904
@ Join
Field originates from a joined layer.
Definition qgis.h:1877
@ Action
A layer action element.
Definition qgis.h:6290
@ Container
A container.
Definition qgis.h:6285
@ QmlElement
A QML element.
Definition qgis.h:6288
@ Relation
A relation.
Definition qgis.h:6287
@ HtmlElement
A HTML element.
Definition qgis.h:6289
@ TextElement
A text element.
Definition qgis.h:6291
@ SpacerElement
A spacer element.
Definition qgis.h:6292
SelectBehavior
Specifies how a selection should be applied.
Definition qgis.h:1941
@ SetSelection
Set selection, removing any existing selection.
Definition qgis.h:1942
@ AddToSelection
Add selection to current selection.
Definition qgis.h:1943
@ IntersectSelection
Modify current selection to include only select features which match.
Definition qgis.h:1944
@ RemoveFromSelection
Remove from current selection.
Definition qgis.h:1945
void setAction(const QgsAction &action)
Sets the action.
static QgsNetworkContentFetcherRegistry * networkContentFetcherRegistry()
Returns the application's network content registry used for fetching temporary files during QGIS sess...
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
const QgsAction & action(const QgsVectorLayer *layer) const
Returns the (possibly lazy loaded) action for the given layer.
QgsOptionalExpression visibilityExpression() const
The visibility expression is used in the attribute form to show or hide this container based on an ex...
QgsOptionalExpression collapsedExpression() const
The collapsed expression is used in the attribute form to set the collapsed status of the group box c...
bool collapsed() const
For group box containers returns true if this group box is collapsed.
Qgis::AttributeEditorContainerType type() const
Returns the container type.
QList< QgsAttributeEditorElement * > children() const
Gets a list of the children elements of this container.
QColor backgroundColor() const
Returns the background color of the container.
int columnCount() const
Gets the number of columns in this group.
Contains context information for attribute editor widgets.
FormMode formMode() const
Returns the form mode.
@ Embed
A form was embedded as a widget on another form.
@ SearchMode
Form values are used for searching/filtering the layer.
@ FixAttributeMode
Fix feature mode, for modifying the feature attributes without saving. The updated feature is availab...
@ IdentifyMode
Identify the feature.
@ SingleEditMode
Single edit mode, for editing a single feature.
@ AggregateSearchMode
Form is in aggregate search mode, show each widget in this mode.
@ MultiEditMode
Multi edit mode, for editing fields of multiple features at once.
@ PreviewMode
Preview mode, for previewing attribute configurations.
void setAttributeFormMode(const Mode &attributeFormMode)
Set attributeFormMode for the edited form.
An abstract base class for any elements of a drag and drop form.
LabelStyle labelStyle() const
Returns the label style.
Qgis::AttributeEditorType type() const
The type of this element.
bool showLabel() const
Controls if this element should be labeled with a title (field, relation or groupname).
QString name() const
Returns the name of this element.
int idx() const
Returns the index of the field.
QString htmlCode() const
The Html code that will be represented within this widget.
QString qmlCode() const
The QML code that will be represented within this widget.
const QgsRelation & relation() const
Gets the id of the relation which shall be embedded.
QVariantMap relationEditorConfiguration() const
Returns the relation editor widget configuration.
QVariant nmRelationId() const
Determines the relation id of the second relation involved in an N:M relation.
bool forceSuppressFormPopup() const
Determines the force suppress form popup status.
QString relationWidgetTypeId() const
Returns the current relation widget type id.
QString label() const
Determines the label of this element.
bool drawLine() const
Returns true if the spacer element will contain an horizontal line.
QString text() const
The Text that will be represented within this widget.
A widget consisting of both an editor widget and additional widgets for controlling the behavior of t...
void setRememberLastValue(bool remember)
Sets whether the widget value will be remembered for potential reuse when creating new features.
void rememberLastValueChanged(int index, bool remember)
Emitted when the widget's remember last value toggle changes.
QgsEditorWidgetWrapper * editorWidget() const
Returns the editor widget wrapper.
void createSearchWidgetWrappers(const QgsAttributeEditorContext &context=QgsAttributeEditorContext()) override
Creates the search widget wrappers for the widget used when the form is in search mode.
Interface class for custom attribute forms.
Widget to show for child relations on an attribute form.
void setMultiEditFeatureIds(const QgsFeatureIds &fids)
Set multiple feature to edit simultaneously.
void createSearchWidgetWrappers(const QgsAttributeEditorContext &context=QgsAttributeEditorContext()) override
Creates the search widget wrappers for the widget used when the form is in search mode.
Base class for all widgets shown on a QgsAttributeForm.
@ SearchMode
Layer search/filter mode.
@ MultiEditMode
Multi edit mode, both the editor widget and a QgsMultiEditToolButton is shown.
@ DefaultMode
Default mode, only the editor widget is shown.
@ AggregateSearchMode
Embedded in a search form, show additional aggregate function toolbutton.
void showButtonBox()
Shows the button box (OK/Cancel) and disables auto-commit.
void parentFormValueChanged(const QString &attribute, const QVariant &newValue)
Is called in embedded forms when an attribute value in the parent form has changed to newValue.
QgsVectorLayer * layer()
Returns the layer for which this form is shown.
void setFeature(const QgsFeature &feature)
Update all editors to correspond to a different feature.
void setMultiEditFeatureIds(const QgsFeatureIds &fids)
Sets all feature IDs which are to be edited if the form is in multiedit mode.
void refreshFeature()
reload current feature
void beforeSave(bool &ok)
Will be emitted before the feature is saved.
void changeGeometry(const QgsGeometry &geometry)
Changes the geometry of the feature attached to the form.
bool eventFilter(QObject *object, QEvent *event) override
Intercepts keypress on custom form (escape should not close it).
bool saveWithDetails(QString *error=nullptr)
Save all the values from the editors to the layer.
void addInterface(QgsAttributeFormInterface *iface)
Takes ownership.
bool needsGeometry() const
Returns true if any of the form widgets need feature geometry.
void setExtraContextScope(QgsExpressionContextScope *extraScope)
Sets an additional expression context scope to be used for calculations in this form.
void changeAttribute(const QString &field, const QVariant &value, const QString &hintText=QString())
Call this to change the content of a given attribute.
bool save()
Save all the values from the editors to the layer.
void filterExpressionSet(const QString &expression, QgsAttributeForm::FilterType type)
Emitted when a filter expression is set using the form.
void hideButtonBox()
Hides the button box (OK/Cancel) and enables auto-commit.
void closed()
Emitted when the user selects the close option from the form's button bar.
void resetSearch()
Resets the search/filter form values.
void editableChanged()
Emitted when the editable state of the attribute form has changed.
void widgetValueChanged(const QString &attribute, const QVariant &value, bool attributeChanged)
Notifies about changes of attributes.
void openFilteredFeaturesAttributeTable(const QString &filter)
Emitted when the user chooses to open the attribute table dialog with a filtered set of features.
QString aggregateFilter() const
The aggregate filter is only useful if the form is in AggregateFilter mode.
void flashFeatures(const QString &filter)
Emitted when the user chooses to flash a filtered set of features.
void resetValues()
Sets all values to the values of the current feature.
QgsAttributeForm(QgsVectorLayer *vl, const QgsFeature &feature=QgsFeature(), const QgsAttributeEditorContext &context=QgsAttributeEditorContext(), QWidget *parent=nullptr)
void disconnectButtonBox()
Disconnects the button box (OK/Cancel) from the accept/resetValues slots If this method is called,...
bool editable()
Returns if the form is currently in editable mode.
void setMessageBar(QgsMessageBar *messageBar)
Sets the message bar to display feedback from the form in.
void modeChanged(QgsAttributeEditorContext::Mode mode)
Emitted when the form changes mode.
static QgsFeature createFeature(QgsVectorLayer *layer, const QgsGeometry &geometry, const QgsAttributeMap &attributes, QgsExpressionContext &context)
Creates a new feature for a given layer taking into account attribute form-specific context such as t...
const QgsFeature & feature() const
Returns feature of attribute form.
void featureSaved(const QgsFeature &feature)
Emitted when a feature is changed or added.
void displayWarning(const QString &message)
Displays a warning message in the form message bar.
void zoomToFeatures(const QString &filter)
Emitted when the user chooses to zoom to a filtered set of features.
Q_DECL_DEPRECATED void attributeChanged(const QString &attribute, const QVariant &value)
Notifies about changes of attributes, this signal is not emitted when the value is set back to the or...
void setMode(QgsAttributeEditorContext::Mode mode)
Sets the current mode of the form.
@ ReplaceFilter
Filter should replace any existing filter.
@ FilterOr
Filter should be combined using "OR".
@ FilterAnd
Filter should be combined using "AND".
QgsAttributeEditorContext::Mode mode() const
Returns the current mode of the form.
void setStyleSheet(const QString &style)
Overridden to prepare base call and avoid crash due to specific QT versions.
void setCollapsed(bool collapse)
Collapse or uncollapse this groupbox.
QgsEditorWidgetSetup findBest(const QgsVectorLayer *vl, const QString &fieldName) const
Find the best editor widget and its configuration for a given field.
QgsEditorWidgetWrapper * create(const QString &widgetId, QgsVectorLayer *vl, int fieldIdx, const QVariantMap &config, QWidget *editor, QWidget *parent, const QgsAttributeEditorContext &context=QgsAttributeEditorContext())
Create an attribute editor widget wrapper of a given type for a given field.
QString type() const
Returns the widget type to use.
QVariantMap config() const
Returns the widget configuration.
Manages an editor widget.
virtual QVariant value() const =0
Will be used to access the widget's value.
virtual QVariantList additionalFieldValues() const
Will be used to access the widget's values for potential additional fields handled by the widget.
int fieldIdx() const
Access the field index.
virtual void parentFormValueChanged(const QString &attribute, const QVariant &value)
Is called in embedded form widgets when an attribute value in the parent form has changed.
virtual QStringList additionalFields() const
Returns the list of additional fields which the editor handles.
QString constraintFailureReason() const
Returns the reason why a constraint check has failed (or an empty string if constraint check was succ...
void setEnabled(bool enabled) override
Is used to enable or disable the edit functionality of the managed widget.
void valuesChanged(const QVariant &value, const QVariantList &additionalFieldValues=QVariantList())
Emit this signal, whenever the value changed.
bool isValidConstraint() const
Gets the current constraint status.
void updateConstraint(const QgsFeature &featureContext, QgsFieldConstraints::ConstraintOrigin constraintOrigin=QgsFieldConstraints::ConstraintOriginNotSet)
Update constraint.
void setValues(const QVariant &value, const QVariantList &additionalValues)
Is called when the value of the widget or additional field values needs to be changed.
virtual void setHint(const QString &hintText)
Add a hint text on the widget.
QgsField field() const
Access the field.
ConstraintResult
Result of constraint checks.
void constraintStatusChanged(const QString &constraint, const QString &desc, const QString &err, QgsEditorWidgetWrapper::ConstraintResult status)
Emit this signal when the constraint status changed.
virtual void setValue(const QVariant &value)
Is called when the value of the widget needs to be changed.
bool isBlockingCommit() const
Returns true if the widget is preventing the feature from being committed.
void setConstraintResultVisible(bool constraintResultVisible)
Sets whether the constraint result is visible.
Single scope for storing variables and functions for use within a QgsExpressionContext.
static std::vector< std::unique_ptr< QgsExpressionContextScope > > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
static std::unique_ptr< QgsExpressionContextScope > formScope(const QgsFeature &formFeature=QgsFeature(), const QString &formMode=QString())
Creates a new scope which contains functions and variables from the current attribute form/table form...
static std::unique_ptr< QgsExpressionContextScope > parentFormScope(const QgsFeature &formFeature=QgsFeature(), const QString &formMode=QString())
Creates a new scope which contains functions and variables from the current parent attribute form/tab...
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
bool hasEvalError() const
Returns true if an error occurred when evaluating last input.
QVariant evaluate()
Evaluate the feature and return the result.
bool isValid() const
Checks if this expression is valid.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
static const QString ALL_ATTRIBUTES
A special attribute that if set matches all attributes.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
Q_INVOKABLE bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
QgsAttributes attributes
Definition qgsfeature.h:64
QgsFields fields
Definition qgsfeature.h:65
QgsFeatureId id
Definition qgsfeature.h:63
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:66
bool isValid() const
Returns the validity of this feature.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
ConstraintOrigin
Origin of constraints.
@ ConstraintOriginNotSet
Constraint is not set.
@ ConstraintOriginLayer
Constraint was set by layer.
QString constraintExpression() const
Returns the constraint expression for the field, if set.
static QString fieldToolTipExtended(const QgsField &field, const QgsVectorLayer *layer, const QString &predefinedComment=QString())
Returns a HTML formatted tooltip string for a field, containing details like the field name,...
QString name
Definition qgsfield.h:65
QString displayName() const
Returns the name to use when displaying this field.
Definition qgsfield.cpp:96
QgsDefaultValue defaultValueDefinition
Definition qgsfield.h:67
QString customComment
Definition qgsfield.h:71
QString comment
Definition qgsfield.h:64
QgsFieldConstraints constraints
Definition qgsfield.h:68
Container of fields for a vector layer.
Definition qgsfields.h:45
int count
Definition qgsfields.h:49
QList< QgsField > toList() const
Utility function to return a list of QgsField instances.
QgsField field(int fieldIdx) const
Returns the field at particular index (must be in range 0..N-1).
Qgis::FieldOrigin fieldOrigin(int fieldIdx) const
Returns the field's origin (value from an enumeration).
Q_INVOKABLE bool exists(int i) const
Returns if a field index is valid.
int size() const
Returns number of items.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
A geometry is the spatial representation of a feature.
bool isExactlyEqual(const QgsGeometry &geometry, Qgis::GeometryBackend backend=Qgis::GeometryBackend::QGIS) const
Compares the geometry with another geometry using the specified backend.
static QgsEditorWidgetRegistry * editorWidgetRegistry()
Returns the global editor widget registry, used for managing all known edit widget factories.
Definition qgsgui.cpp:110
static bool allowExecutionOfEmbeddedScripts(QgsProject *project, QgsMessageBar *messageBar=nullptr)
Returns true if python embedded in a project is currently allowed to be loaded.
Definition qgsgui.cpp:418
void reinitWidget()
Clears the content and makes new initialization.
void setHtmlCode(const QString &htmlCode)
Sets the HTML code to htmlCode.
bool needsGeometry() const
Returns true if the widget needs feature geometry.
static void warning(const QString &msg)
Goes to qWarning.
void editingStopped()
Emitted when edited changes have been successfully written to the data provider.
void editingStarted()
Emitted when editing on this layer has started.
A bar for displaying non-blocking messages to the user.
bool popWidget(QgsMessageBarItem *item)
Remove the specified item from the bar, and display the next most recent one in the stack.
QFile * localFile(const QString &filePathOrUrl)
Returns a QFile from a local file or to a temporary file previously fetched by the registry.
bool enabled() const
Check if this optional is enabled.
Definition qgsoptional.h:76
T data() const
Access the payload data.
Definition qgsoptional.h:94
static Qgis::ProjectTrustStatus checkUserTrust(QgsProject *project)
Returns the current trust status of the specified project.
QgsRelationManager * relationManager
Definition qgsproject.h:125
static QgsProject * instance()
Returns the QgsProject singleton instance.
static bool run(const QString &command, const QString &messageOnError=QString())
Execute a Python statement.
static bool eval(const QString &command, QString &result)
Eval a Python statement.
void setQmlCode(const QString &qmlCode)
writes the qmlCode into a temporary file
QList< QgsRelation > referencedRelations(const QgsVectorLayer *layer=nullptr) const
Gets all relations where this layer is the referenced part (i.e.
QList< QgsRelation > referencingRelations(const QgsVectorLayer *layer=nullptr, int fieldIdx=-2) const
Gets all relations where the specified layer (and field) is the referencing part (i....
Q_INVOKABLE QgsRelation relation(const QString &id) const
Gets access to a relation by its id.
A widget wrapper for relation widgets.
void relatedFeaturesChanged()
Emit this signal, whenever the related features changed.
QgsRelation relation() const
The relation for which this wrapper is created.
void setWidgetConfig(const QVariantMap &config)
Will set the config of this widget wrapper to the specified config.
void setForceSuppressFormPopup(bool forceSuppressFormPopup)
Sets force suppress form popup status to forceSuppressFormPopup for this widget and for the vectorLay...
void setNmRelationId(const QVariant &nmRelationId=QVariant())
Sets nmRelationId for the relation id of the second relation involved in an N:M relation.
Represents a relationship between two vector layers.
Definition qgsrelation.h:42
QString name
Definition qgsrelation.h:52
Qgis::RelationshipType type() const
Returns the type of the relation.
QString id
Definition qgsrelation.h:45
QList< QgsRelation::FieldPair > fieldPairs() const
Returns the field pairs which form this relation The first element of each pair are the field names o...
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
static const QgsSettingsEntryBool * settingsDigitizingReuseLastValues
Settings entry digitizing reuseLastValues.
void setDrawLine(bool drawLine)
Sets a flag to define if the spacer element will contain an horizontal line.
void setTabVisible(QWidget *tab, bool visible)
Control the visibility for the tab with the given widget.
void setTabStyle(int tabIndex, const QgsAttributeEditorElement::LabelStyle &labelStyle)
Sets the optional custom labelStyle for the tab identified by tabIndex.
bool isInvalidJSON() const
Returns whether the text edit widget contains Invalid JSON.
bool needsGeometry() const
Returns true if the widget needs feature geometry.
void setText(const QString &text)
Sets the text code to htmlCode.
void reinitWidget()
Clears the content and makes new initialization.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
static QVariant createNullVariant(QMetaType::Type metaType)
Helper method to properly create a null QVariant from a metaType Returns the created QVariant.
const QgsVectorLayerJoinInfo * joinForFieldIndex(int index, const QgsFields &fields, int &sourceFieldIndex) const
Finds the vector join for a layer field index.
QList< const QgsVectorLayerJoinInfo * > joinsWhereFieldIsId(const QgsField &field) const
Returns joins where the field of a target layer is considered as an id.
QStringList * joinFieldNamesSubset() const
Returns the subset of fields to be used from joined layer.
bool isDynamicFormEnabled() const
Returns whether the form has to be dynamically updated with joined fields when a feature is being cre...
bool hasUpsertOnEdit() const
Returns whether a feature created on the target layer has to impact the joined layer by creating a ne...
bool isEditable() const
Returns whether joined fields may be edited through the form of the target layer.
QgsVectorLayer * joinLayer() const
Returns joined layer (may be nullptr if the reference was set by layer ID and not resolved yet).
static bool fieldIsEditable(const QgsVectorLayer *layer, int fieldIndex, const QgsFeature &feature, QgsVectorLayerUtils::FieldIsEditableFlags flags=QgsVectorLayerUtils::FieldIsEditableFlags())
Tests whether a field is editable for a particular feature.
static QgsFeature createFeature(const QgsVectorLayer *layer, const QgsGeometry &geometry=QgsGeometry(), const QgsAttributeMap &attributes=QgsAttributeMap(), QgsExpressionContext *context=nullptr)
Creates a new feature ready for insertion into a layer.
QFlags< FieldIsEditableFlag > FieldIsEditableFlags
@ IgnoreLayerEditability
Ignores the vector layer's editable state.
Represents a vector layer which manages a vector based dataset.
bool isEditable() const final
Returns true if the provider is in editing mode.
void beforeRemovingExpressionField(int idx)
Will be emitted, when an expression field is going to be deleted from this vector layer.
QString expressionField(int index) const
Returns the expression used for a given expression field.
Q_INVOKABLE void selectByExpression(const QString &expression, Qgis::SelectBehavior behavior=Qgis::SelectBehavior::SetSelection, QgsExpressionContext *context=nullptr)
Selects matching features using an expression.
QgsVectorLayerJoinBuffer * joinBuffer()
Returns the join buffer object.
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
void beforeAddingExpressionField(const QString &fieldName)
Will be emitted, when an expression field is going to be added to this vector layer.
void updatedFields()
Emitted whenever the fields available from this layer have been changed.
void beforeModifiedCheck() const
Emitted when the layer is checked for modifications. Use for last-minute additions.
Manages an editor widget.
QWidget * widget()
Access the widget managed by this wrapper.
void setConfig(const QVariantMap &config)
Will set the config of this wrapper to the specified config.
QgsVectorLayer * layer() const
Returns the vector layer associated with the widget.
void setContext(const QgsAttributeEditorContext &context)
Set the context in which this widget is shown.
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 c
bool qgsVariantEqual(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether they are equal, two NULL values are always treated a...
Definition qgis.cpp:657
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:8447
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:8446
QMap< int, QVariant > QgsAttributeMap
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71