80#include "moc_qgsattributeform.cpp"
82using namespace Qt::StringLiterals;
84int QgsAttributeForm::sFormCounter = 0;
90 , mFormNr( sFormCounter++ )
91 , mEditCommandMessage( tr(
"Attributes changed" ) )
103 updateContainersVisibility();
105 updateEditableState();
111 qDeleteAll( mInterfaces );
138 mInterfaces.append( iface );
143 bool isEditable =
false;
152 isEditable = mFeature.isValid() && mLayer->isEditable();
156 isEditable = mLayer->isEditable();
175 if ( mUnsavedMultiEditChanges )
178 int res = QMessageBox::question(
this, tr(
"Multiedit Attributes" ), tr(
"Apply changes to edited features?" ), QMessageBox::Yes | QMessageBox::No );
179 if ( res == QMessageBox::Yes )
184 clearMultiEditMessages();
186 mUnsavedMultiEditChanges =
false;
242 w->setContext( newContext );
245 auto setRelationWidgetsVisible = [
this](
bool relationWidgetsVisible ) {
248 w->setVisible( relationWidgetsVisible );
255 setRelationWidgetsVisible(
true );
257 mSearchButtonBox->setVisible(
false );
261 setRelationWidgetsVisible(
true );
263 mSearchButtonBox->setVisible(
false );
267 setRelationWidgetsVisible(
true );
269 mSearchButtonBox->setVisible(
false );
273 setRelationWidgetsVisible(
true );
274 resetMultiEdit(
false );
276 mSearchButtonBox->setVisible(
false );
280 setRelationWidgetsVisible(
true );
281 mSearchButtonBox->setVisible(
true );
287 setRelationWidgetsVisible(
false );
288 mSearchButtonBox->setVisible(
false );
294 setRelationWidgetsVisible(
true );
297 mSearchButtonBox->setVisible(
false );
301 setRelationWidgetsVisible(
false );
303 mSearchButtonBox->setVisible(
false );
312 const auto constMWidgets = mWidgets;
327 QVariant mainValue = eww->
value();
329 additionalFieldValues[index] = value;
330 eww->
setValues( mainValue, additionalFieldValues );
339 mCurrentFormFeature.setGeometry( geometry );
344 mIsSettingFeature =
true;
362 mIsSettingFeature =
false;
363 const auto constMInterfaces = mInterfaces;
366 iface->featureChanged();
382 mIsSettingFeature =
false;
385bool QgsAttributeForm::saveEdits( QString *error )
388 bool changedLayer =
false;
392 if ( updatedFeatureChangedGeometry )
399 bool doUpdate =
false;
408 QgsAttributes src = mFeature.attributes();
409 QgsAttributes dst = mFeature.attributes();
411 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
413 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
417 QgsTextEditWrapper *textEdit = qobject_cast<QgsTextEditWrapper *>( eww );
421 *error = tr(
"JSON value for %1 is invalid and has not been saved" ).arg( eww->
field().
name() );
424 QVariantList dstVars = QVariantList() << dst.at( eww->
fieldIdx() );
425 QVariantList srcVars = QVariantList() << eww->
value();
426 QList<int> fieldIndexes = QList<int>() << eww->
fieldIdx();
430 for (
const QString &fieldName : additionalFields )
434 dstVars << dst.at( idx );
438 Q_ASSERT( dstVars.count() == srcVars.count() );
440 for (
int i = 0; i < dstVars.count(); i++ )
442 if ( !
qgsVariantEqual( dstVars[i], srcVars[i] ) && srcVars[i].isValid() )
444 dst[fieldIndexes[i]] = srcVars[i];
454 const auto constMInterfaces = mInterfaces;
455 for ( QgsAttributeFormInterface *iface : constMInterfaces )
457 if ( !iface->acceptChanges( updatedFeature ) )
467 mFeature = updatedFeature;
471 mFeature.setValid(
true );
472 mLayer->beginEditCommand( mEditCommandMessage );
473 bool res = mLayer->addFeature( updatedFeature );
476 mFeature.setAttributes( updatedFeature.
attributes() );
477 mLayer->endEditCommand();
479 const QgsFields fields = mLayer->fields();
480 const QgsAttributes newValues = updatedFeature.
attributes();
481 const QVariant lastUsedValuesVariant = mLayer->property(
"AttributeFormLastUsedValues" );
484 for (
int idx = 0; idx < fields.
count(); ++idx )
489 const QVariant rememberLastUsedValuesVariant = mLayer->property(
"AttributeFormRememberLastUsedValues" );
490 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
491 if ( !rememberLastUsedValues.contains( idx ) )
494 rememberLastUsedValues[idx] = remember;
495 mLayer->setProperty(
"AttributeFormRememberLastUsedValues", QVariant::fromValue<QMap<int, bool>>( rememberLastUsedValues ) );
498 const QVariant newValue = rememberLastUsedValues[idx] ? newValues.at( idx ) : QVariant();
499 if ( !lastUsedValues.contains( idx ) || lastUsedValues[idx] != newValue )
501 lastUsedValues[idx] = newValue;
502 QgsDebugMsgLevel( u
"Saving %1 for %2"_s.arg( ( newValue.toString() ).arg( idx ) ), 2 );
506 mLayer->setProperty(
"AttributeFormLastUsedValues", QVariant::fromValue<QgsAttributeMap>( lastUsedValues ) );
512 mLayer->destroyEditCommand();
516 mLayer->beginEditCommand( mEditCommandMessage );
522 for (
int i = 0; i < dst.count(); ++i )
525 || !dst.at( i ).isValid()
526 || !fieldIsEditable( i ) )
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 );
535 newValues[i] = dst.at( i );
536 oldValues[i] = src.at( i );
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;
547 mFeature.setAttributes( dst );
550 if ( updatedFeatureChangedGeometry && ( success || editedCount == 0 ) )
552 QgsGeometry geometry = updatedFeature.
geometry();
553 success = success || mLayer->changeGeometry( mFeature.id(), geometry,
false );
556 mFeature.setGeometry( geometry );
562 mLayer->endEditCommand();
567 mLayer->destroyEditCommand();
581 mLayer->triggerRepaint();
586QgsFeature QgsAttributeForm::getUpdatedFeature()
const
589 QgsFeature updatedFeature = QgsFeature( mFeature );
591 QgsAttributes featureAttributes = mFeature.attributes();
592 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
594 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
598 QVariantList dstVars = QVariantList() << featureAttributes.at( eww->
fieldIdx() );
599 QVariantList srcVars = QVariantList() << eww->
value();
600 QList<int> fieldIndexes = QList<int>() << eww->
fieldIdx();
604 for (
const QString &fieldName : additionalFields )
608 dstVars << featureAttributes.at( idx );
612 Q_ASSERT( dstVars.count() == srcVars.count() );
614 for (
int i = 0; i < dstVars.count(); i++ )
616 if ( !
qgsVariantEqual( dstVars[i], srcVars[i] ) && srcVars[i].isValid() )
617 featureAttributes[fieldIndexes[i]] = srcVars[i];
622 return updatedFeature;
625void QgsAttributeForm::updateValuesDependencies(
const int originIdx )
627 updateValuesDependenciesDefaultValues( originIdx );
628 updateValuesDependenciesVirtualFields( originIdx );
631void QgsAttributeForm::updateValuesDependenciesDefaultValues(
const int originIdx )
633 if ( !mDefaultValueDependencies.contains( originIdx ) )
636 if ( !mFeature.isValid() )
655 QgsFeature updatedFeature = getUpdatedFeature();
658 QList<QgsWidgetWrapper *> relevantWidgets = mDefaultValueDependencies.values( originIdx );
659 for ( QgsWidgetWrapper *ww : std::as_const( relevantWidgets ) )
661 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
675 if ( mAlreadyUpdatedFields.contains( eww->
fieldIdx() ) )
678 QgsExpressionContext context = createExpressionContext( updatedFeature );
680 const QVariant value = mLayer->defaultValue( eww->
fieldIdx(), updatedFeature, &context );
682 mCurrentFormFeature.setAttribute( eww->
field().
name(), value );
687void QgsAttributeForm::updateValuesDependenciesVirtualFields(
const int originIdx )
689 if ( !mVirtualFieldsDependencies.contains( originIdx ) )
692 if ( !mFeature.isValid() )
696 QgsFeature updatedFeature = getUpdatedFeature();
699 const QList<QgsWidgetWrapper *> relevantWidgets = mVirtualFieldsDependencies.values( originIdx );
700 for ( QgsWidgetWrapper *ww : relevantWidgets )
702 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
707 if ( mAlreadyUpdatedFields.contains( eww->
fieldIdx() ) )
711 QgsExpressionContext context = createExpressionContext( updatedFeature );
712 QgsExpression exp( mLayer->expressionField( eww->
fieldIdx() ) );
713 const QVariant value = exp.evaluate( &context );
719void QgsAttributeForm::updateValuesDependenciesParent()
722 QgsFeature updatedFeature = getUpdatedFeature();
723 QList<int> updatedFields;
726 const QSet<QgsEditorWidgetWrapper *> relevantWidgets = mParentDependencies;
727 for ( QgsEditorWidgetWrapper *eww : relevantWidgets )
730 if ( updatedFields.contains( eww->
fieldIdx() ) )
735 QgsExpressionContext context = createExpressionContext( updatedFeature );
736 const QVariant value = mLayer->defaultValue( eww->
fieldIdx(), updatedFeature, &context );
741void QgsAttributeForm::updateRelatedLayerFields()
744 updateRelatedLayerFieldsDependencies();
746 if ( mRelatedLayerFieldsDependencies.isEmpty() )
749 if ( !mFeature.isValid() )
753 QgsFeature updatedFeature = getUpdatedFeature();
756 const QSet<QgsEditorWidgetWrapper *> relevantWidgets = mRelatedLayerFieldsDependencies;
757 for ( QgsEditorWidgetWrapper *eww : relevantWidgets )
760 if ( mAlreadyUpdatedFields.contains( eww->
fieldIdx() ) )
764 QgsExpressionContext context = createExpressionContext( updatedFeature );
765 QgsExpression exp( mLayer->expressionField( eww->
fieldIdx() ) );
766 QVariant value = exp.evaluate( &context );
771void QgsAttributeForm::resetMultiEdit(
bool promptToSave )
776 mUnsavedMultiEditChanges =
false;
780void QgsAttributeForm::multiEditMessageClicked(
const QString &link )
782 clearMultiEditMessages();
783 resetMultiEdit( link ==
"#apply"_L1 );
786void QgsAttributeForm::filterTriggered()
788 QString filter = createFilterExpression();
794void QgsAttributeForm::searchZoomTo()
796 QString filter = createFilterExpression();
797 if ( filter.isEmpty() )
803void QgsAttributeForm::searchFlash()
805 QString filter = createFilterExpression();
806 if ( filter.isEmpty() )
812void QgsAttributeForm::filterAndTriggered()
814 QString filter = createFilterExpression();
815 if ( filter.isEmpty() )
823void QgsAttributeForm::filterOrTriggered()
825 QString filter = createFilterExpression();
826 if ( filter.isEmpty() )
834void QgsAttributeForm::pushSelectedFeaturesMessage()
836 int count = mLayer->selectedFeatureCount();
839 mMessageBar->pushMessage( QString(), tr(
"%n matching feature(s) selected",
"matching features", count ),
Qgis::MessageLevel::Info );
854 QString filter = createFilterExpression();
855 if ( filter.isEmpty() )
859 pushSelectedFeaturesMessage();
864void QgsAttributeForm::searchSetSelection()
869void QgsAttributeForm::searchAddToSelection()
874void QgsAttributeForm::searchRemoveFromSelection()
879void QgsAttributeForm::searchIntersectSelection()
884bool QgsAttributeForm::saveMultiEdits()
888 const QList<int> fieldIndexes = mFormEditorWidgets.uniqueKeys();
889 for (
int fieldIndex : fieldIndexes )
891 const QList<QgsAttributeFormEditorWidget *> widgets = mFormEditorWidgets.values( fieldIndex );
892 if ( !widgets.first()->hasChanged() )
895 if ( !widgets.first()->currentValue().isValid()
896 || !fieldIsEditable( fieldIndex ) )
902 for ( QgsAttributeFormEditorWidget *widget : widgets )
903 widget->changesCommitted();
905 newAttributeValues.insert( fieldIndex, widgets.first()->currentValue() );
908 if ( newAttributeValues.isEmpty() )
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 )
925 mLayer->beginEditCommand( tr(
"Updated multiple feature attributes" ) );
929 const auto constMultiEditFeatureIds = mMultiEditFeatureIds;
932 QgsAttributeMap::const_iterator aIt = newAttributeValues.constBegin();
933 for ( ; aIt != newAttributeValues.constEnd(); ++aIt )
935 success &= mLayer->changeAttributeValue( fid, aIt.key(), aIt.value() );
939 clearMultiEditMessages();
942 mLayer->endEditCommand();
943 mLayer->triggerRepaint();
944 mMultiEditMessageBarItem =
new QgsMessageBarItem( tr(
"Attribute changes for multiple features applied." ),
Qgis::MessageLevel::Success, -1 );
948 mLayer->destroyEditCommand();
952 if ( !mButtonBox->isVisible() )
953 mMessageBar->pushItem( mMultiEditMessageBarItem );
979 wrapper->notifyAboutToSave();
1006 bool success =
true;
1022 success = saveEdits( error );
1026 success = saveMultiEdits();
1034 mUnsavedMultiEditChanges =
false;
1043 mValuesInitialized =
false;
1044 const auto constMWidgets = mWidgets;
1047 ww->setFeature( mFeature );
1058 mAlreadyUpdatedFields.append( eww->
fieldIdx() );
1059 updateValuesDependenciesVirtualFields( eww->
fieldIdx() );
1060 mAlreadyUpdatedFields.removeAll( eww->
fieldIdx() );
1063 mValuesInitialized =
true;
1069 const auto widgets { findChildren<QgsAttributeFormEditorWidget *>() };
1076void QgsAttributeForm::clearMultiEditMessages()
1078 if ( mMultiEditUnsavedMessageBarItem )
1080 if ( !mButtonBox->isVisible() )
1081 mMessageBar->
popWidget( mMultiEditUnsavedMessageBarItem );
1082 mMultiEditUnsavedMessageBarItem =
nullptr;
1084 if ( mMultiEditMessageBarItem )
1086 if ( !mButtonBox->isVisible() )
1087 mMessageBar->popWidget( mMultiEditMessageBarItem );
1088 mMultiEditMessageBarItem =
nullptr;
1092QString QgsAttributeForm::createFilterExpression()
const
1094 QStringList filters;
1095 for ( QgsAttributeFormWidget *w : std::as_const( mFormWidgets ) )
1097 QString filter = w->currentFilterExpression();
1098 if ( !filter.isEmpty() )
1102 if ( filters.isEmpty() )
1105 QString filter = filters.join(
") AND ("_L1 ).prepend(
'(' ).append(
')' );
1111 QgsExpressionContext context;
1114 if ( mExtraContextScope )
1116 context.
appendScope(
new QgsExpressionContextScope( *mExtraContextScope.get() ) );
1118 if ( mContext.parentFormFeature().isValid() )
1127void QgsAttributeForm::onAttributeChanged(
const QVariant &value,
const QVariantList &additionalFieldValues )
1129 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( sender() );
1132 bool signalEmitted =
false;
1134 if ( mValuesInitialized )
1137 mCurrentFormFeature.setAttribute( eww->
field().
name(), value );
1141 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( eww->
fieldIdx() );
1142 for ( QgsAttributeFormEditorWidget *formEditorWidget : std::as_const( formEditorWidgets ) )
1144 if ( formEditorWidget->editorWidget() == eww )
1148 formEditorWidget->editorWidget()->setValue( value );
1166 for (
int i = 0; i < additionalFields.count(); i++ )
1168 const QString fieldName = additionalFields.at( i );
1169 const QVariant value = additionalFieldValues.at( i );
1173 signalEmitted =
true;
1175 if ( mValuesInitialized )
1176 updateJoinedFields( *eww );
1182 if ( !mIsSettingMultiEditFeatures )
1184 mUnsavedMultiEditChanges =
true;
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();
1193 if ( !mButtonBox->isVisible() )
1194 mMessageBar->pushItem( mMultiEditUnsavedMessageBarItem );
1197 signalEmitted =
true;
1207 updateConstraints( eww );
1210 if ( mValuesInitialized && !mIsSettingMultiEditFeatures )
1213 mAlreadyUpdatedFields.append( eww->
fieldIdx() );
1214 updateValuesDependencies( eww->
fieldIdx() );
1215 mAlreadyUpdatedFields.removeAll( eww->
fieldIdx() );
1220 updateEditableState();
1222 if ( !signalEmitted )
1227 bool attributeHasChanged = !mIsSettingFeature;
1229 attributeHasChanged &= !mIsSettingMultiEditFeatures;
1235void QgsAttributeForm::updateAllConstraints()
1237 const auto constMWidgets = mWidgets;
1238 for ( QgsWidgetWrapper *ww : constMWidgets )
1240 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1242 updateConstraints( eww );
1250 if ( currentFormValuesFeature( ft ) )
1262 updateConstraint( ft, eww );
1265 const QList<QgsEditorWidgetWrapper *> deps = constraintDependencies( eww );
1267 for ( QgsEditorWidgetWrapper *depsEww : deps )
1268 updateConstraint( ft, depsEww );
1273 QgsExpressionContext context = createExpressionContext( ft );
1276 const QVector<ContainerInformation *> infos = mContainerInformationDependency.value( eww->
field().
name() );
1277 for ( ContainerInformation *info : infos )
1279 info->apply( &context );
1284void QgsAttributeForm::updateContainersVisibility()
1286 QgsExpressionContext context = createExpressionContext( mFeature );
1288 const QVector<ContainerInformation *> infos = mContainerVisibilityCollapsedInformation;
1290 for ( ContainerInformation *info : infos )
1292 info->apply( &context );
1302 updateAllConstraints();
1317 if ( mJoinedFeatures.contains( info ) )
1333void QgsAttributeForm::updateLabels()
1335 if ( !mLabelDataDefinedProperties.isEmpty() )
1337 QgsFeature currentFeature;
1338 if ( currentFormValuesFeature( currentFeature ) )
1340 QgsExpressionContext context = createExpressionContext( currentFeature );
1342 for (
auto it = mLabelDataDefinedProperties.constBegin(); it != mLabelDataDefinedProperties.constEnd(); ++it )
1344 QLabel *label { it.key() };
1346 const QString value { it->valueAsString( context, QString(), &ok ) };
1347 if ( ok && !value.isEmpty() )
1349 label->setText( value );
1354 if ( !mCustomCommentDataDefinedProperties.isEmpty() )
1356 QgsFeature currentFeature;
1357 if ( currentFormValuesFeature( currentFeature ) )
1359 QgsExpressionContext context = createExpressionContext( currentFeature );
1361 for (
auto it = mCustomCommentDataDefinedProperties.constBegin(); it != mCustomCommentDataDefinedProperties.constEnd(); ++it )
1363 QWidget *labelWidget { it.key() };
1365 const QString value { it->valueAsString( context, QString(), &ok ) };
1366 if ( ok && !value.isEmpty() )
1368 const QString fieldName = labelWidget->objectName();
1369 const QgsFields fields = mLayer->fields();
1382void QgsAttributeForm::updateEditableState()
1384 if ( !mEditableDataDefinedProperties.isEmpty() )
1386 QgsFeature currentFeature;
1387 if ( currentFormValuesFeature( currentFeature ) )
1389 QgsExpressionContext context = createExpressionContext( currentFeature );
1391 for (
auto it = mEditableDataDefinedProperties.constBegin(); it != mEditableDataDefinedProperties.constEnd(); ++it )
1393 QWidget *w { it.key() };
1395 const bool isEditable { it->valueAsBool( context,
true, &ok ) && mLayer && mLayer->isEditable() };
1398 QgsAttributeFormEditorWidget *editorWidget { qobject_cast<QgsAttributeFormEditorWidget *>( w ) };
1405 w->setEnabled( isEditable );
1413bool QgsAttributeForm::currentFormValuesFeature(
QgsFeature &feature )
1416 feature = QgsFeature( mFeature );
1417 QgsAttributes dst =
feature.attributes();
1419 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1421 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1426 if ( dst.count() > eww->
fieldIdx() )
1428 QVariantList dstVars = QVariantList() << dst.at( eww->
fieldIdx() );
1429 QVariantList srcVars = QVariantList() << eww->
value();
1430 QList<int> fieldIndexes = QList<int>() << eww->
fieldIdx();
1434 for (
const QString &fieldName : additionalFields )
1437 fieldIndexes << idx;
1438 dstVars << dst.at( idx );
1442 Q_ASSERT( dstVars.count() == srcVars.count() );
1444 for (
int i = 0; i < dstVars.count(); i++ )
1450 dst[fieldIndexes[i]] = srcVars[i];
1467void QgsAttributeForm::registerContainerInformation( QgsAttributeForm::ContainerInformation *info )
1469 mContainerVisibilityCollapsedInformation.append( info );
1473 for (
const QString &col : referencedColumns )
1475 mContainerInformationDependency[col].append( info );
1479bool QgsAttributeForm::currentFormValidConstraints( QStringList &invalidFields, QStringList &descriptions )
const
1481 bool valid {
true };
1483 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1485 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1503bool QgsAttributeForm::currentFormValidHardConstraints( QStringList &invalidFields, QStringList &descriptions )
const
1505 bool valid {
true };
1507 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1509 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1524void QgsAttributeForm::onAttributeAdded(
int idx )
1526 mPreventFeatureRefresh =
false;
1527 if ( mFeature.isValid() )
1529 QgsAttributes attrs = mFeature.attributes();
1531 mFeature.setFields(
layer()->fields() );
1532 mFeature.setAttributes( attrs );
1538void QgsAttributeForm::onAttributeDeleted(
int idx )
1540 mPreventFeatureRefresh =
false;
1541 if ( mFeature.isValid() )
1543 QgsAttributes attrs = mFeature.attributes();
1544 attrs.remove( idx );
1545 mFeature.setFields(
layer()->fields() );
1546 mFeature.setAttributes( attrs );
1552void QgsAttributeForm::onRelatedFeaturesChanged()
1554 updateRelatedLayerFields();
1557void QgsAttributeForm::onUpdatedFields()
1559 mPreventFeatureRefresh =
false;
1560 if ( mFeature.isValid() )
1562 QgsAttributes attrs(
layer()->fields().size() );
1565 int idx = mFeature.fields().indexFromName(
layer()->fields().at( i ).name() );
1568 attrs[i] = mFeature.attributes().at( idx );
1569 if ( mFeature.attributes().at( idx ).userType() !=
layer()->fields().at( i ).type() )
1571 attrs[i].convert(
layer()->fields().at( i ).type() );
1579 mFeature.setFields(
layer()->fields() );
1580 mFeature.setAttributes( attrs );
1588 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( sender() );
1591 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( eww->
fieldIdx() );
1593 for ( QgsAttributeFormEditorWidget *formEditorWidget : formEditorWidgets )
1595 formEditorWidget->setConstraintStatus( constraint, description, err, result );
1596 if ( formEditorWidget->editorWidget() != eww )
1598 formEditorWidget->editorWidget()->updateConstraint( result, err );
1605 QList<QgsEditorWidgetWrapper *> wDeps;
1609 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
1612 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
1617 if ( name != ewwName )
1624 for (
const QString &colName : referencedColumns )
1626 if ( name.compare( colName, Qt::CaseSensitivity::CaseInsensitive ) == 0 )
1628 wDeps.append( eww );
1641 return setupRelationWidgetWrapper( QString(), rel, context );
1646 QgsRelationWidgetWrapper *rww =
new QgsRelationWidgetWrapper( relationWidgetTypeId, mLayer, rel,
nullptr,
this );
1647 const QVariantMap config = mLayer->editFormConfig().widgetConfig( rel.
id() );
1654QToolButton *QgsAttributeForm::createCommentInfoButton( QWidget *labelWidget )
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 );
1660 infoButton->setAutoRaise(
true );
1661 infoButton->setStyleSheet(
1664 " background-color: transparent; "
1669 connect( infoButton, &QToolButton::clicked, labelWidget, [labelWidget]() { QToolTip::showText( QCursor::pos(), labelWidget->toolTip(), labelWidget ); } );
1671 infoButton->setVisible(
false );
1675void QgsAttributeForm::preventFeatureRefresh()
1677 mPreventFeatureRefresh =
true;
1682 if ( mPreventFeatureRefresh || mLayer->isEditable() || !mFeature.isValid() )
1687 if ( !mLayer->getFeatures(
QgsFeatureRequest().setFilterFid( mFeature.id() ) ).nextFeature( mFeature ) )
1696 if ( mContext.parentFormFeature().isValid() )
1698 QgsFeature parentFormFeature = mContext.parentFormFeature();
1700 mContext.setParentFormFeature( parentFormFeature );
1703 updateValuesDependenciesParent();
1717 return mNeedsGeometry;
1720void QgsAttributeForm::synchronizeState()
1729 const QList<QgsAttributeFormEditorWidget *> formWidgets = mFormEditorWidgets.values( eww->
fieldIdx() );
1733 formWidget->setConstraintResultVisible( isEditable );
1738 bool enabled = isEditable && fieldIsEditable( eww->
fieldIdx() );
1739 ww->setEnabled( enabled );
1745 ww->setEnabled( isEditable );
1755 if ( mConstraintsFailMessageBarItem )
1757 mMessageBar->popWidget( mConstraintsFailMessageBarItem );
1759 mConstraintsFailMessageBarItem =
new QgsMessageBarItem( tr(
"Multi edit mode requires at least one selected feature." ),
Qgis::MessageLevel::Info, -1 );
1760 mMessageBar->pushItem( mConstraintsFailMessageBarItem );
1764 QStringList invalidFields, descriptions;
1765 mValidConstraints = currentFormValidHardConstraints( invalidFields, descriptions );
1769 if ( !mValidConstraints && !mConstraintsFailMessageBarItem )
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 );
1775 else if ( mValidConstraints && mConstraintsFailMessageBarItem )
1777 mMessageBar->popWidget( mConstraintsFailMessageBarItem );
1778 mConstraintsFailMessageBarItem =
nullptr;
1781 else if ( mConstraintsFailMessageBarItem )
1783 mMessageBar->popWidget( mConstraintsFailMessageBarItem );
1784 mConstraintsFailMessageBarItem =
nullptr;
1787 isEditable = isEditable & mValidConstraints;
1792 QPushButton *okButton = mButtonBox->button( QDialogButtonBox::Ok );
1795 okButton->setEnabled( isEditable );
1801void QgsAttributeForm::init()
1803 QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
1806 QWidget *formWidget =
nullptr;
1807 mNeedsGeometry =
false;
1809 bool buttonBoxVisible =
true;
1813 buttonBoxVisible = mButtonBox->isVisible();
1815 mButtonBox =
nullptr;
1818 if ( mSearchButtonBox )
1820 delete mSearchButtonBox;
1821 mSearchButtonBox =
nullptr;
1824 qDeleteAll( mWidgets );
1827 while ( QWidget *w = this->findChild<QWidget *>() )
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 );
1842 QGridLayout *layout =
new QGridLayout();
1843 QWidget *container =
new QWidget();
1844 container->setLayout( layout );
1845 vl->addWidget( container );
1847 mFormEditorWidgets.clear();
1848 mFormWidgets.clear();
1851 setContentsMargins( 0, 0, 0, 0 );
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 ) )
1863 QFileInfo fi( file->fileName() );
1864 loader.setWorkingDirectory( fi.dir() );
1865 formWidget = loader.load( file,
this );
1868 formWidget->setWindowFlags( Qt::Widget );
1869 layout->addWidget( formWidget );
1872 mButtonBox = findChild<QDialogButtonBox *>();
1875 formWidget->installEventFilter(
this );
1880 QgsTabWidget *tabWidget =
nullptr;
1887 int columnCount = 1;
1888 bool hasRootFields =
false;
1889 bool addSpacer =
true;
1891 const QList<QgsAttributeEditorElement *> tabs = mLayer->editFormConfig().tabs();
1893 for ( QgsAttributeEditorElement *widgDef : tabs )
1897 QgsAttributeEditorContainer *containerDef =
dynamic_cast<QgsAttributeEditorContainer *
>( widgDef );
1898 if ( !containerDef )
1901 switch ( containerDef->
type() )
1905 tabWidget =
nullptr;
1906 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, formWidget, mLayer, mContext );
1907 if ( widgetInfo.labelStyle.overrideColor )
1909 if ( widgetInfo.labelStyle.color.isValid() )
1911 widgetInfo.widget->setStyleSheet( u
"QGroupBox::title { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
1914 if ( widgetInfo.labelStyle.overrideFont )
1916 widgetInfo.widget->setFont( widgetInfo.labelStyle.font );
1919 layout->addWidget( widgetInfo.widget, row, column, 1, 2 );
1920 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
1922 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
1924 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
1926 layout->setRowStretch( row, widgDef->verticalStretch() );
1931 if ( widgetInfo.expandingNeeded )
1934 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
1938 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum );
1944 registerContainerInformation(
new ContainerInformation(
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 ) )
1962 layout->setRowStretch( row, widgDef->verticalStretch() );
1967 if ( widgetInfo.expandingNeeded )
1970 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
1974 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum );
1977 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
1979 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
1984 registerContainerInformation(
new ContainerInformation(
1999 tabWidget =
new QgsTabWidget();
2000 layout->addWidget( tabWidget, row, column, 1, 2 );
2004 QWidget *tabPage =
new QWidget( tabWidget );
2005 tabWidget->addTab( tabPage, widgDef->name() );
2006 tabWidget->
setTabStyle( tabWidget->tabBar()->count() - 1, widgDef->labelStyle() );
2010 registerContainerInformation(
new ContainerInformation( tabWidget, tabPage, containerDef->
visibilityExpression().
data() ) );
2012 QGridLayout *tabPageLayout =
new QGridLayout();
2013 tabPage->setLayout( tabPageLayout );
2015 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, tabPage, mLayer, mContext );
2016 if ( widgetInfo.expandingNeeded )
2019 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
2021 tabPageLayout->addWidget( widgetInfo.widget );
2028 hasRootFields =
true;
2029 tabWidget =
nullptr;
2030 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, container, mLayer, mContext );
2031 QgsCollapsibleGroupBox *collapsibleGroupBox =
new QgsCollapsibleGroupBox();
2033 if ( widgetInfo.showLabel )
2035 if ( widgetInfo.labelStyle.overrideColor && widgetInfo.labelStyle.color.isValid() )
2037 collapsibleGroupBox->
setStyleSheet( u
"QGroupBox::title { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2040 if ( widgetInfo.labelStyle.overrideFont )
2042 collapsibleGroupBox->setFont( widgetInfo.labelStyle.font );
2045 collapsibleGroupBox->setTitle( widgetInfo.labelText );
2048 QVBoxLayout *collapsibleGroupBoxLayout =
new QVBoxLayout();
2049 collapsibleGroupBoxLayout->addWidget( widgetInfo.widget );
2050 collapsibleGroupBox->setLayout( collapsibleGroupBoxLayout );
2052 QVBoxLayout *
c =
new QVBoxLayout();
2053 c->addWidget( collapsibleGroupBox );
2054 layout->addLayout(
c, row, column, 1, 2 );
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() );
2068 hasRootFields =
true;
2069 tabWidget =
nullptr;
2070 WidgetInfo widgetInfo = createWidgetFromDef( widgDef, container, mLayer, mContext );
2071 QWidget *labelWidget =
new QWidget();
2072 QLabel *label =
new QLabel( widgetInfo.labelText, labelWidget );
2074 if ( widgetInfo.labelStyle.overrideColor )
2076 if ( widgetInfo.labelStyle.color.isValid() )
2078 label->setStyleSheet( u
"QLabel { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2082 if ( widgetInfo.labelStyle.overrideFont )
2084 label->setFont( widgetInfo.labelStyle.font );
2087 labelWidget->setToolTip( widgetInfo.toolTip );
2088 if ( columnCount > 1 && !widgetInfo.labelOnTop )
2090 label->setAlignment( Qt::AlignRight | Qt::AlignVCenter );
2093 label->setBuddy( widgetInfo.widget );
2096 QToolButton *commentInfoButton = createCommentInfoButton( labelWidget );
2098 if ( !widgetInfo.hint.isEmpty() )
2099 commentInfoButton->setVisible(
true );
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 )
2108 QHBoxLayout *labelLayout =
new QHBoxLayout( labelWidget );
2109 labelLayout->addWidget( label );
2110 labelLayout->addWidget( commentInfoButton );
2111 labelLayout->setContentsMargins( 0, 0, 0, 0 );
2113 if ( !widgetInfo.showLabel )
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 );
2120 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
2122 layout->setRowStretch( row, widgDef->verticalStretch() );
2125 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
2127 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
2132 else if ( widgetInfo.labelOnTop )
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 );
2140 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
2142 layout->setRowStretch( row, widgDef->verticalStretch() );
2145 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( column + 1 ) )
2147 layout->setColumnStretch( column + 1, widgDef->horizontalStretch() );
2154 const int widgetColumn = column + 1;
2155 layout->addWidget( labelWidget, row, column++ );
2156 layout->addWidget( widgetInfo.widget, row, column++ );
2158 if ( widgDef->verticalStretch() > 0 && widgDef->verticalStretch() > layout->rowStretch( row ) )
2160 layout->setRowStretch( row, widgDef->verticalStretch() );
2163 if ( widgDef->horizontalStretch() > 0 && widgDef->horizontalStretch() > layout->columnStretch( widgetColumn ) )
2165 layout->setColumnStretch( widgetColumn, widgDef->horizontalStretch() );
2172 const QgsAttributeEditorField *fieldElement {
static_cast<QgsAttributeEditorField *
>( widgDef ) };
2173 const int fieldIdx = fieldElement->
idx();
2174 if ( fieldIdx >= 0 && fieldIdx < mLayer->fields().count() )
2176 const QString fieldName { mLayer->fields().at( fieldIdx ).name() };
2177 label->setObjectName( fieldName );
2182 if ( property.isActive() )
2184 mLabelDataDefinedProperties[label] = property;
2187 labelWidget->setObjectName( fieldName );
2191 if ( property.isActive() )
2193 mCustomCommentDataDefinedProperties[labelWidget] = property;
2194 commentInfoButton->setVisible(
true );
2200 if ( property.isActive() )
2202 mEditableDataDefinedProperties[widgetInfo.widget] = property;
2209 if ( column >= columnCount * 2 )
2216 if ( hasRootFields && addSpacer )
2218 QSpacerItem *spacerItem =
new QSpacerItem( 20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding );
2219 layout->addItem( spacerItem, row, 0 );
2220 layout->setRowStretch( row, 1 );
2223 formWidget = container;
2232 formWidget =
new QWidget(
this );
2233 QGridLayout *gridLayout =
new QGridLayout( formWidget );
2234 formWidget->setLayout( gridLayout );
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 );
2249 layout->addWidget( formWidget );
2254 const QgsFields fields = mLayer->fields();
2259 QSet<int> compositeHiddenFields;
2261 for (
const QgsRelation &rel : referencingRelations )
2266 const QList<QgsRelation::FieldPair> fieldPairs = rel.
fieldPairs();
2267 if ( fieldPairs.size() > 1 )
2269 for (
int i = 1; i < fieldPairs.size(); i++ )
2271 const int idx = fields.
lookupField( fieldPairs.at( i ).referencingField() );
2273 compositeHiddenFields.insert( idx );
2278 for (
const QgsField &field : fields )
2280 const QString fieldName = field.name();
2281 int idx = fields.lookupField( fieldName );
2285 if ( compositeHiddenFields.contains( idx ) )
2289 QString labelText = mLayer->attributeDisplayName( idx );
2290 labelText.replace(
'&',
"&&"_L1 );
2294 if ( widgetSetup.
type() ==
"Hidden"_L1 )
2297 bool labelOnTop = mLayer->editFormConfig().labelOnTop( idx );
2300 QWidget *labelWidget =
new QWidget();
2301 QLabel *label =
new QLabel( labelText, labelWidget );
2302 label->setObjectName( fieldName );
2307 QToolButton *commentInfoButton = createCommentInfoButton( labelWidget );
2309 if ( !field.customComment().isEmpty() || ( field.customComment().isNull() && !field.comment().isEmpty() ) )
2310 commentInfoButton->setVisible(
true );
2312 QSvgWidget *i =
new QSvgWidget();
2313 i->setFixedSize( 18, 18 );
2318 if ( property.isActive() )
2320 mLabelDataDefinedProperties[label] = property;
2323 labelWidget->setObjectName( fieldName );
2327 if ( property.isActive() )
2329 mCustomCommentDataDefinedProperties[labelWidget] = property;
2330 commentInfoButton->setVisible(
true );
2336 QWidget *w =
nullptr;
2339 QgsAttributeFormEditorWidget *formWidget =
new QgsAttributeFormEditorWidget( eww, widgetSetup.
type(),
this );
2341 mFormEditorWidgets.insert( idx, formWidget );
2342 mFormWidgets.append( formWidget );
2348 const QVariant rememberLastUsedValuesVariant = mLayer->property(
"AttributeFormRememberLastUsedValues" );
2349 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
2350 if ( rememberLastUsedValues.contains( idx ) )
2352 remember = rememberLastUsedValues[idx];
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 ) );
2366 label->setBuddy( eww->
widget() );
2371 if ( property.isActive() )
2373 mEditableDataDefinedProperties[formWidget] = property;
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() ) ) );
2384 w->setObjectName( field.name() );
2388 mWidgets.append( eww );
2389 mIconMap[eww->
widget()] = i;
2392 QHBoxLayout *labelLayout =
new QHBoxLayout( labelWidget );
2393 labelLayout->addWidget( label );
2394 labelLayout->addWidget( commentInfoButton );
2395 labelLayout->setContentsMargins( 0, 0, 0, 0 );
2399 gridLayout->addWidget( labelWidget, row++, 0, 1, 2 );
2400 gridLayout->addWidget( w, row++, 0, 1, 2 );
2401 gridLayout->addWidget( i, row++, 0, 1, 2 );
2405 int widgetColumn = 0;
2406 gridLayout->addWidget( labelWidget, row, widgetColumn++ );
2407 gridLayout->addWidget( w, row, widgetColumn++ );
2408 gridLayout->addWidget( i, row++, widgetColumn++ );
2413 for (
const QgsRelation &rel : relations )
2415 QgsRelationWidgetWrapper *rww = setupRelationWidgetWrapper( u
"relation_editor"_s, rel, mContext );
2417 QgsAttributeFormRelationEditorWidget *formWidget =
new QgsAttributeFormRelationEditorWidget( rww,
this );
2420 QgsCollapsibleGroupBox *collapsibleGroupBox =
new QgsCollapsibleGroupBox( rel.
name() );
2421 QVBoxLayout *collapsibleGroupBoxLayout =
new QVBoxLayout();
2422 collapsibleGroupBoxLayout->addWidget( formWidget );
2423 collapsibleGroupBox->setLayout( collapsibleGroupBoxLayout );
2425 gridLayout->addWidget( collapsibleGroupBox, row++, 0, 1, 2 );
2427 mWidgets.append( rww );
2428 mFormWidgets.append( formWidget );
2433 QSpacerItem *spacerItem =
new QSpacerItem( 20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding );
2434 gridLayout->addItem( spacerItem, row, 0 );
2435 gridLayout->setRowStretch( row, 1 );
2441 updateFieldDependencies();
2445 mButtonBox =
new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel );
2446 mButtonBox->setObjectName( u
"buttonBox"_s );
2447 layout->addWidget( mButtonBox, layout->rowCount(), 0, 1, layout->columnCount() );
2449 mButtonBox->setVisible( buttonBoxVisible );
2451 if ( !mSearchButtonBox )
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 );
2459 QPushButton *clearButton =
new QPushButton( tr(
"&Reset Form" ), mSearchButtonBox );
2461 boxLayout->addWidget( clearButton );
2462 boxLayout->addStretch( 1 );
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 );
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" ) );
2475 boxLayout->addWidget( openAttributeTableButton );
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 );
2483 QToolButton *selectButton =
new QToolButton();
2484 selectButton->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Minimum );
2485 selectButton->setText( tr(
"&Select Features" ) );
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 );
2493 connect( selectAction, &QAction::triggered,
this, &QgsAttributeForm::searchSetSelection );
2494 selectMenu->addAction( selectAction );
2495 QAction *addSelectAction =
new QAction( tr(
"Add to Current Selection" ), selectMenu );
2497 connect( addSelectAction, &QAction::triggered,
this, &QgsAttributeForm::searchAddToSelection );
2498 selectMenu->addAction( addSelectAction );
2499 QAction *deselectAction =
new QAction( tr(
"Remove from Current Selection" ), selectMenu );
2501 connect( deselectAction, &QAction::triggered,
this, &QgsAttributeForm::searchRemoveFromSelection );
2502 selectMenu->addAction( deselectAction );
2503 QAction *filterSelectAction =
new QAction( tr(
"Filter Current Selection" ), selectMenu );
2505 connect( filterSelectAction, &QAction::triggered,
this, &QgsAttributeForm::searchIntersectSelection );
2506 selectMenu->addAction( filterSelectAction );
2507 selectButton->setMenu( selectMenu );
2508 boxLayout->addWidget( selectButton );
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 );
2529 QPushButton *closeButton =
new QPushButton( tr(
"Close" ), mSearchButtonBox );
2531 closeButton->setShortcut( Qt::Key_Escape );
2532 boxLayout->addWidget( closeButton );
2535 layout->addWidget( mSearchButtonBox, layout->rowCount(), 0, 1, layout->columnCount() );
2553 const auto constMInterfaces = mInterfaces;
2554 for ( QgsAttributeFormInterface *iface : constMInterfaces )
2564 QApplication::restoreOverrideCursor();
2567void QgsAttributeForm::cleanPython()
2569 if ( !mPyFormVarName.isNull() )
2571 QString expr = u
"if '%1' in locals(): del %1\n"_s.arg( mPyFormVarName );
2576void QgsAttributeForm::initPython()
2587 mMessageBar->pushMessage( tr(
"Security warning" ), tr(
"The attribute form contains an embedded script which has been denied execution." ),
Qgis::MessageLevel::Warning );
2591 QString initFunction = mLayer->editFormConfig().initFunction();
2592 QString initFilePath = mLayer->editFormConfig().initFilePath();
2595 switch ( mLayer->editFormConfig().initCodeSource() )
2598 if ( !initFilePath.isEmpty() )
2602 if ( inputFile && inputFile->open( QFile::ReadOnly ) )
2605 QTextStream inf( inputFile );
2606 initCode = inf.readAll();
2611 QgsLogger::warning( u
"The external python file path %1 could not be opened!"_s.arg( initFilePath ) );
2621 initCode = mLayer->editFormConfig().initCode();
2622 if ( initCode.isEmpty() )
2635 if ( !initCode.isEmpty() )
2643 mMessageBar->pushMessage( QString(), tr(
"Python macro could not be run due to missing permissions." ),
Qgis::MessageLevel::Warning );
2651 if (
QgsPythonRunner::eval( u
"len(inspect.getfullargspec(%1)[0])"_s.arg( initFunction ), numArgs ) )
2653 static int sFormId = 0;
2654 mPyFormVarName = u
"_qgis_featureform_%1_%2"_s.arg( mFormNr ).arg( sFormId++ );
2656 QString form = u
"%1 = sip.wrapinstance( %2, qgis.gui.QgsAttributeForm )"_s.arg( mPyFormVarName ).arg( ( quint64 )
this );
2660 QgsDebugMsgLevel( u
"running featureForm init: %1"_s.arg( mPyFormVarName ), 2 );
2663 if ( numArgs ==
"3"_L1 )
2665 addInterface(
new QgsAttributeFormLegacyInterface( initFunction, mPyFormVarName,
this ) );
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 )
2676 QString expr = QString(
"%1(%2)" )
2677 .arg( mLayer->editFormInit() )
2678 .arg( mPyFormVarName );
2679 QgsAttributeFormInterface *iface = QgsPythonRunner::evalToSipObject<QgsAttributeFormInterface *>( expr,
"QgsAttributeFormInterface" );
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 ) );
2697 WidgetInfo newWidgetInfo;
2699 newWidgetInfo.labelStyle = widgetDef->
labelStyle();
2701 switch ( widgetDef->
type() )
2705 const QgsAttributeEditorAction *elementDef =
dynamic_cast<const QgsAttributeEditorAction *
>( widgetDef );
2709 QgsActionWidgetWrapper *actionWrapper =
new QgsActionWidgetWrapper( mLayer,
nullptr,
this, mMessageBar );
2713 mWidgets.append( actionWrapper );
2714 newWidgetInfo.widget = actionWrapper->
widget();
2715 newWidgetInfo.showLabel =
false;
2722 const QgsAttributeEditorField *fieldDef =
dynamic_cast<const QgsAttributeEditorField *
>( widgetDef );
2726 const QgsFields fields = vl->
fields();
2728 if ( fldIdx < fields.
count() && fldIdx >= 0 )
2733 QgsAttributeFormEditorWidget *formWidget =
new QgsAttributeFormEditorWidget( eww, widgetSetup.
type(),
this );
2734 mFormEditorWidgets.insert( fldIdx, formWidget );
2735 mFormWidgets.append( formWidget );
2741 const QVariant rememberLastUsedValuesVariant = mLayer->property(
"AttributeFormRememberLastUsedValues" );
2742 QMap<int, bool> rememberLastUsedValues = rememberLastUsedValuesVariant.value<QMap<int, bool>>();
2743 if ( rememberLastUsedValues.contains( fldIdx ) )
2745 remember = rememberLastUsedValues[fldIdx];
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 ) );
2758 newWidgetInfo.widget = formWidget;
2759 mWidgets.append( eww );
2761 newWidgetInfo.widget->setObjectName( fields.
at( fldIdx ).
name() );
2763 newWidgetInfo.hint = customComment.isNull() ? fields.
at( fldIdx ).
comment() : customComment;
2765 newWidgetInfo.labelOnTop = mLayer->editFormConfig().labelOnTop( fldIdx );
2766 newWidgetInfo.labelText = mLayer->attributeDisplayName( fldIdx );
2767 newWidgetInfo.labelText.replace(
'&',
"&&"_L1 );
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();
2780 newWidgetInfo.showLabel = widgetDef->
showLabel();
2787 const QgsAttributeEditorRelation *relDef =
static_cast<const QgsAttributeEditorRelation *
>( widgetDef );
2791 QgsAttributeFormRelationEditorWidget *formWidget =
new QgsAttributeFormRelationEditorWidget( rww,
this );
2801 mWidgets.append( rww );
2802 mFormWidgets.append( formWidget );
2804 newWidgetInfo.widget = formWidget;
2805 newWidgetInfo.showLabel = relDef->
showLabel();
2806 newWidgetInfo.labelText = relDef->
label();
2807 if ( newWidgetInfo.labelText.isEmpty() )
2809 newWidgetInfo.labelOnTop =
true;
2815 const QgsAttributeEditorContainer *container =
dynamic_cast<const QgsAttributeEditorContainer *
>( widgetDef );
2821 if ( columnCount <= 0 )
2825 QWidget *myContainer =
nullptr;
2826 bool removeLayoutMargin =
false;
2827 switch ( container->
type() )
2831 QgsCollapsibleGroupBoxBasic *groupBox =
new QgsCollapsibleGroupBoxBasic();
2832 widgetName = u
"QGroupBox"_s;
2835 groupBox->setTitle( container->
name() );
2836 if ( newWidgetInfo.labelStyle.overrideColor )
2838 if ( newWidgetInfo.labelStyle.color.isValid() )
2840 groupBox->
setStyleSheet( u
"QGroupBox::title { color: %1; }"_s.arg( newWidgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2843 if ( newWidgetInfo.labelStyle.overrideFont )
2845 groupBox->setFont( newWidgetInfo.labelStyle.font );
2848 myContainer = groupBox;
2849 newWidgetInfo.widget = myContainer;
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();
2867 myContainer =
new QWidget();
2869 QgsScrollArea *scrollArea =
new QgsScrollArea( parent );
2871 scrollArea->setWidget( myContainer );
2872 scrollArea->setWidgetResizable(
true );
2873 scrollArea->setFrameShape( QFrame::NoFrame );
2874 widgetName = u
"QScrollArea QWidget"_s;
2876 newWidgetInfo.widget = scrollArea;
2883 QString style { u
"background-color: %1;"_s.arg( container->
backgroundColor().name() ) };
2884 newWidgetInfo.widget->setStyleSheet( style );
2887 QGridLayout *gbLayout =
new QGridLayout();
2888 if ( removeLayoutMargin )
2889 gbLayout->setContentsMargins( 0, 0, 0, 0 );
2890 myContainer->setLayout( gbLayout );
2894 bool addSpacer =
true;
2896 const QList<QgsAttributeEditorElement *> children = container->
children();
2898 for ( QgsAttributeEditorElement *childDef : children )
2900 WidgetInfo widgetInfo = createWidgetFromDef( childDef, myContainer, vl, context );
2904 QgsAttributeEditorContainer *containerDef =
static_cast<QgsAttributeEditorContainer *
>( childDef );
2907 registerContainerInformation(
new ContainerInformation(
2914 if ( childDef->verticalStretch() == 0 )
2916 if ( widgetInfo.expandingNeeded )
2918 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Expanding );
2922 widgetInfo.widget->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum );
2928 int widgetColumn = column;
2930 if ( widgetInfo.labelText.isNull() || !widgetInfo.showLabel )
2932 gbLayout->addWidget( widgetInfo.widget, row, column, 1, 2 );
2933 widgetColumn = column + 1;
2938 QWidget *labelWidget =
new QWidget();
2939 QLabel *mypLabel =
new QLabel( widgetInfo.labelText, labelWidget );
2941 if ( widgetInfo.labelStyle.overrideColor )
2943 if ( widgetInfo.labelStyle.color.isValid() )
2945 mypLabel->setStyleSheet( u
"QLabel { color: %1; }"_s.arg( widgetInfo.labelStyle.color.name( QColor::HexArgb ) ) );
2949 if ( widgetInfo.labelStyle.overrideFont )
2951 mypLabel->setFont( widgetInfo.labelStyle.font );
2955 QToolButton *commentInfoButton = createCommentInfoButton( labelWidget );
2957 if ( !widgetInfo.hint.isEmpty() )
2958 commentInfoButton->setVisible(
true );
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 )
2968 const QString fieldName { fields.
at( fldIdx ).
name() };
2969 mypLabel->setObjectName( fieldName );
2974 if ( property.isActive() )
2976 mLabelDataDefinedProperties[mypLabel] = property;
2982 if ( property.isActive() )
2984 mEditableDataDefinedProperties[widgetInfo.widget] = property;
2987 labelWidget->setObjectName( fieldName );
2991 if ( property.isActive() )
2993 mCustomCommentDataDefinedProperties[labelWidget] = property;
2999 labelWidget->setToolTip( widgetInfo.toolTip );
3000 if ( columnCount > 1 && !widgetInfo.labelOnTop )
3002 mypLabel->setAlignment( Qt::AlignRight | Qt::AlignVCenter );
3005 mypLabel->setBuddy( widgetInfo.widget );
3007 QHBoxLayout *labelLayout =
new QHBoxLayout( labelWidget );
3008 labelLayout->addWidget( mypLabel );
3009 labelLayout->addWidget( commentInfoButton );
3010 labelLayout->setContentsMargins( 0, 0, 0, 0 );
3012 if ( widgetInfo.labelOnTop )
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 );
3024 widgetColumn = column + 1;
3025 gbLayout->addWidget( labelWidget, row, column++ );
3026 gbLayout->addWidget( widgetInfo.widget, row, column++ );
3030 const int childHorizontalStretch = childDef->horizontalStretch();
3031 const int existingColumnStretch = gbLayout->columnStretch( widgetColumn );
3032 if ( childHorizontalStretch > 0 && childHorizontalStretch > existingColumnStretch )
3034 gbLayout->setColumnStretch( widgetColumn, childHorizontalStretch );
3037 if ( childDef->verticalStretch() > 0 && childDef->verticalStretch() > gbLayout->rowStretch( row ) )
3039 gbLayout->setRowStretch( row, childDef->verticalStretch() );
3042 if ( column >= columnCount * 2 )
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 )
3055 if ( qobject_cast<QgsAttributeFormRelationEditorWidget *>( widgetInfo.widget ) )
3061 QWidget *spacer =
new QWidget();
3062 spacer->setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Preferred );
3063 gbLayout->addWidget( spacer, ++row, 0 );
3064 gbLayout->setRowStretch( row, 1 );
3067 newWidgetInfo.labelText = QString();
3068 newWidgetInfo.labelOnTop =
true;
3069 newWidgetInfo.showLabel = widgetDef->
showLabel();
3070 newWidgetInfo.expandingNeeded |= !addSpacer;
3076 const QgsAttributeEditorQmlElement *elementDef =
static_cast<const QgsAttributeEditorQmlElement *
>( widgetDef );
3077 QgsQmlWidgetWrapper *qmlWrapper =
new QgsQmlWidgetWrapper( mLayer,
nullptr,
this );
3082 mWidgets.append( qmlWrapper );
3084 newWidgetInfo.widget = qmlWrapper->
widget();
3085 newWidgetInfo.labelText = elementDef->
name();
3086 newWidgetInfo.labelOnTop =
true;
3087 newWidgetInfo.showLabel = widgetDef->
showLabel();
3093 const QgsAttributeEditorHtmlElement *elementDef =
static_cast<const QgsAttributeEditorHtmlElement *
>( widgetDef );
3095 QgsHtmlWidgetWrapper *htmlWrapper =
new QgsHtmlWidgetWrapper( mLayer,
nullptr,
this );
3099 mWidgets.append( htmlWrapper );
3101 newWidgetInfo.widget = htmlWrapper->
widget();
3102 newWidgetInfo.labelText = elementDef->
name();
3103 newWidgetInfo.labelOnTop =
true;
3104 newWidgetInfo.showLabel = widgetDef->
showLabel();
3111 const QgsAttributeEditorTextElement *elementDef =
static_cast<const QgsAttributeEditorTextElement *
>( widgetDef );
3113 QgsTextWidgetWrapper *textWrapper =
new QgsTextWidgetWrapper( mLayer,
nullptr,
this );
3117 mWidgets.append( textWrapper );
3119 newWidgetInfo.widget = textWrapper->
widget();
3120 newWidgetInfo.labelText = elementDef->
name();
3121 newWidgetInfo.labelOnTop =
false;
3122 newWidgetInfo.showLabel = widgetDef->
showLabel();
3129 const QgsAttributeEditorSpacerElement *elementDef =
static_cast<const QgsAttributeEditorSpacerElement *
>( widgetDef );
3130 QgsSpacerWidgetWrapper *spacerWrapper =
new QgsSpacerWidgetWrapper( mLayer,
nullptr,
this );
3133 mWidgets.append( spacerWrapper );
3135 newWidgetInfo.widget = spacerWrapper->
widget();
3136 newWidgetInfo.labelOnTop =
false;
3137 newWidgetInfo.showLabel =
false;
3142 QgsDebugError( u
"Unknown attribute editor widget type encountered..."_s );
3146 return newWidgetInfo;
3149void QgsAttributeForm::createWrappers()
3151 QList<QWidget *> myWidgets = findChildren<QWidget *>();
3152 const QList<QgsField> fields = mLayer->fields().
toList();
3154 const auto constMyWidgets = myWidgets;
3155 for ( QWidget *myWidget : constMyWidgets )
3158 QVariant vRel = myWidget->property(
"qgisRelation" );
3159 if ( vRel.isValid() )
3162 QgsRelation relation = relMgr->
relation( vRel.toString() );
3165 QgsRelationWidgetWrapper *rww =
new QgsRelationWidgetWrapper( mLayer, relation, myWidget,
this );
3166 rww->
setConfig( mLayer->editFormConfig().widgetConfig( relation.
id() ) );
3169 mWidgets.append( rww );
3174 const auto constFields = fields;
3175 for (
const QgsField &field : constFields )
3177 if ( field.name() == myWidget->objectName() )
3179 int idx = mLayer->fields().lookupField( field.name() );
3182 mWidgets.append( eww );
3189void QgsAttributeForm::afterWidgetInit()
3191 bool isFirstEww =
true;
3193 const auto constMWidgets = mWidgets;
3194 for ( QgsWidgetWrapper *ww : constMWidgets )
3196 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
3202 setFocusProxy( eww->
widget() );
3211 QgsRelationWidgetWrapper *relationWidgetWrapper = qobject_cast<QgsRelationWidgetWrapper *>( ww );
3212 if ( relationWidgetWrapper )
3225 if ( e->type() == QEvent::KeyPress )
3227 QKeyEvent *keyEvent =
dynamic_cast<QKeyEvent *
>( e );
3228 if ( keyEvent && keyEvent->key() == Qt::Key_Escape )
3239void QgsAttributeForm::scanForEqualAttributes(
QgsFeatureIterator &fit, QSet<int> &mixedValueFields, QHash<int, QVariant> &fieldSharedValues )
const
3241 mixedValueFields.clear();
3242 fieldSharedValues.clear();
3248 for (
int i = 0; i < mLayer->
fields().count(); ++i )
3250 if ( mixedValueFields.contains( i ) )
3255 fieldSharedValues[i] = f.
attribute( i );
3259 if ( fieldSharedValues.value( i ) != f.
attribute( i ) )
3261 fieldSharedValues.remove( i );
3262 mixedValueFields.insert( i );
3268 if ( mixedValueFields.count() == mLayer->fields().count() )
3277void QgsAttributeForm::layerSelectionChanged()
3291 resetMultiEdit(
true );
3298 mIsSettingMultiEditFeatures =
true;
3299 mMultiEditFeatureIds = fids;
3301 if ( fids.isEmpty() )
3304 QMultiMap<int, QgsAttributeFormEditorWidget *>::const_iterator wIt = mFormEditorWidgets.constBegin();
3305 for ( ; wIt != mFormEditorWidgets.constEnd(); ++wIt )
3307 wIt.value()->initialize( QVariant() );
3309 mIsSettingMultiEditFeatures =
false;
3316 QSet<int> mixedValueFields;
3317 QHash<int, QVariant> fieldSharedValues;
3318 scanForEqualAttributes( fit, mixedValueFields, fieldSharedValues );
3321 fit = mLayer->getFeatures(
QgsFeatureRequest().setFilterFid( *fids.constBegin() ) );
3327 if ( mCurrentFormFeature.id() != firstFeature.
id() )
3332 const auto constMixedValueFields = mixedValueFields;
3333 for (
int fieldIndex : std::as_const( mixedValueFields ) )
3335 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( fieldIndex );
3336 if ( formEditorWidgets.isEmpty() )
3339 const QStringList additionalFields = formEditorWidgets.first()->editorWidget()->additionalFields();
3340 QVariantList additionalFieldValues;
3341 for (
const QString &additionalField : additionalFields )
3342 additionalFieldValues << firstFeature.
attribute( additionalField );
3345 w->initialize( firstFeature.
attribute( fieldIndex ),
true, additionalFieldValues );
3347 QHash<int, QVariant>::const_iterator sharedValueIt = fieldSharedValues.constBegin();
3348 for ( ; sharedValueIt != fieldSharedValues.constEnd(); ++sharedValueIt )
3350 const QList<QgsAttributeFormEditorWidget *> formEditorWidgets = mFormEditorWidgets.values( sharedValueIt.key() );
3351 if ( formEditorWidgets.isEmpty() )
3355 const QStringList additionalFields = formEditorWidgets.first()->editorWidget()->additionalFields();
3356 for (
const QString &additionalField : additionalFields )
3358 int index = mLayer->fields().indexFromName( additionalField );
3359 if ( constMixedValueFields.contains( index ) )
3366 QVariantList additionalFieldValues;
3369 for (
const QString &additionalField : additionalFields )
3370 additionalFieldValues << firstFeature.
attribute( additionalField );
3372 w->initialize( firstFeature.
attribute( sharedValueIt.key() ),
true, additionalFieldValues );
3376 for (
const QString &additionalField : additionalFields )
3378 int index = mLayer->fields().indexFromName( additionalField );
3379 Q_ASSERT( fieldSharedValues.contains( index ) );
3380 additionalFieldValues << fieldSharedValues.value( index );
3383 w->initialize( sharedValueIt.value(),
false, additionalFieldValues );
3387 setMultiEditFeatureIdsRelations( fids );
3389 mIsSettingMultiEditFeatures =
false;
3394 if ( mOwnsMessageBar )
3396 mOwnsMessageBar =
false;
3397 mMessageBar = messageBar;
3407 QStringList filters;
3410 QString filter = widget->currentFilterExpression();
3411 if ( !filter.isNull() )
3412 filters <<
'(' + filter +
')';
3415 return filters.join(
" AND "_L1 );
3420 mExtraContextScope.reset( extraScope );
3425 const bool newVisibility = expression.
evaluate( expressionContext ).toBool();
3435 widget->setVisible( newVisibility );
3438 isVisible = newVisibility;
3441 const bool newCollapsedState = collapsedExpression.evaluate( expressionContext ).toBool();
3443 if ( collapsedExpression.isValid() && !collapsedExpression.hasEvalError() && newCollapsedState != isCollapsed )
3445 if ( QgsCollapsibleGroupBoxBasic * collapsibleGroupBox { qobject_cast<QgsCollapsibleGroupBoxBasic *>( widget ) } )
3447 collapsibleGroupBox->
setCollapsed( newCollapsedState );
3448 isCollapsed = newCollapsedState;
3453void QgsAttributeForm::updateJoinedFields(
const QgsEditorWidgetWrapper &eww )
3458 QgsFeature formFeature;
3462 if ( infos.count() == 0 || !currentFormValuesFeature( formFeature ) )
3465 const QString hint = tr(
"No feature joined" );
3466 const auto constInfos = infos;
3467 for (
const QgsVectorLayerJoinInfo *info : constInfos )
3469 if ( !info->isDynamicFormEnabled() )
3472 QgsFeature joinFeature = mLayer->joinBuffer()->joinedFeatureOf( info, formFeature );
3474 mJoinedFeatures[info] = joinFeature;
3476 if ( info->hasSubset() )
3480 const auto constSubsetNames = subsetNames;
3481 for (
const QString &field : constSubsetNames )
3483 QString prefixedName = info->prefixedFieldName( field );
3485 QString hintText = hint;
3498 const QgsFields joinFields = joinFeature.
fields();
3499 for (
const QgsField &field : joinFields )
3501 QString prefixedName = info->prefixedFieldName( field );
3503 QString hintText = hint;
3517bool QgsAttributeForm::fieldIsEditable(
int fieldIndex )
const
3523void QgsAttributeForm::updateFieldDependencies()
3525 mDefaultValueDependencies.clear();
3526 mVirtualFieldsDependencies.clear();
3527 mRelatedLayerFieldsDependencies.clear();
3528 mParentDependencies.clear();
3531 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
3533 QgsEditorWidgetWrapper *eww = qobject_cast<QgsEditorWidgetWrapper *>( ww );
3537 updateFieldDependenciesParent( eww );
3538 updateFieldDependenciesDefaultValue( eww );
3539 updateFieldDependenciesVirtualFields( eww );
3540 updateRelatedLayerFieldsDependencies( eww );
3544void QgsAttributeForm::updateFieldDependenciesDefaultValue( QgsEditorWidgetWrapper *eww )
3548 if ( exp.needsGeometry() )
3549 mNeedsGeometry =
true;
3554 const QList<int> allAttributeIds( mLayer->fields().allAttributesList() );
3556 for (
const int id : allAttributeIds )
3558 mDefaultValueDependencies.insertMulti(
id, eww );
3564 const QSet<QString> referencedColumns = exp.referencedColumns();
3565 for (
const QString &referencedColumn : referencedColumns )
3567 mDefaultValueDependencies.insertMulti( mLayer->fields().lookupField( referencedColumn ), eww );
3572void QgsAttributeForm::updateFieldDependenciesVirtualFields( QgsEditorWidgetWrapper *eww )
3575 if ( expressionField.isEmpty() )
3578 QgsExpression exp( expressionField );
3580 if ( exp.needsGeometry() )
3581 mNeedsGeometry =
true;
3586 const QList<int> allAttributeIds( mLayer->fields().allAttributesList() );
3588 for (
const int id : allAttributeIds )
3590 mVirtualFieldsDependencies.insertMulti(
id, eww );
3596 const QSet<QString> referencedColumns = exp.referencedColumns();
3597 for (
const QString &referencedColumn : referencedColumns )
3599 mVirtualFieldsDependencies.insertMulti( mLayer->fields().lookupField( referencedColumn ), eww );
3604void QgsAttributeForm::updateRelatedLayerFieldsDependencies( QgsEditorWidgetWrapper *eww )
3609 if ( expressionField.contains( u
"relation_aggregate"_s ) || expressionField.contains( u
"get_features"_s ) )
3610 mRelatedLayerFieldsDependencies.insert( eww );
3614 mRelatedLayerFieldsDependencies.clear();
3616 for ( QgsWidgetWrapper *ww : std::as_const( mWidgets ) )
3618 QgsEditorWidgetWrapper *editorWidgetWrapper = qobject_cast<QgsEditorWidgetWrapper *>( ww );
3619 if ( !editorWidgetWrapper )
3622 updateRelatedLayerFieldsDependencies( editorWidgetWrapper );
3627void QgsAttributeForm::updateFieldDependenciesParent( QgsEditorWidgetWrapper *eww )
3632 const QSet<QString> referencedVariablesAndFunctions = expression.referencedVariables() + expression.referencedFunctions();
3633 for (
const QString &referenced : referencedVariablesAndFunctions )
3635 if ( referenced.startsWith(
"current_parent"_L1 ) )
3637 mParentDependencies.insert( eww );
3644void QgsAttributeForm::setMultiEditFeatureIdsRelations(
const QgsFeatureIds &fids )
3646 for ( QgsAttributeFormWidget *formWidget : mFormWidgets )
3648 QgsAttributeFormRelationEditorWidget *relationEditorWidget =
dynamic_cast<QgsAttributeFormRelationEditorWidget *
>( formWidget );
3649 if ( !relationEditorWidget )
3656void QgsAttributeForm::updateIcon( QgsEditorWidgetWrapper *eww )
3662 mIconMap[eww->
widget()]->hide();
3664 if ( !eww->
widget()->isEnabled() && mLayer->isEditable() )
3669 const QgsVectorLayerJoinInfo *info = mLayer->joinBuffer()->joinForFieldIndex( eww->
fieldIdx(), mLayer->fields(), srcFieldIndex );
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()] );
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()] );
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()] );
3696void QgsAttributeForm::reloadIcon(
const QString &file,
const QString &tooltip, QSvgWidget *sw )
3699 sw->setToolTip( tooltip );
3706 QgsDebugMsgLevel( u
"reuseAllLastValues: %1"_s.arg( reuseAllLastValues ), 2 );
3710 for (
int idx = 0; idx < fields.
count(); ++idx )
3712 if ( attributes.contains( idx ) )
3714 initialAttributeValues.insert( idx, attributes.value( idx ) );
3718 const QVariant lastUsedValuesVariant =
layer->property(
"AttributeFormLastUsedValues" );
3720 if ( lastUsedValues.contains( idx ) &&
layer->dataProvider() &&
layer->dataProvider()->defaultValueClause( idx ) != lastUsedValues[idx] )
3722 initialAttributeValues.insert( idx, lastUsedValues[idx] );
@ Trusted
The project has been determined by the user as trusted.
@ Row
A row of editors (horizontal layout).
AttributeFormReuseLastValuePolicy
Attribute form policy for reusing last entered values.
@ AllowedDefaultOn
Reuse of last values allowed and enabled by default.
@ NotAllowed
Reuse of last values not allowed.
@ File
Load the Python code from an external file.
@ Environment
Use the Python code available in the Python environment.
@ NoSource
Do not use Python code at all.
@ Dialog
Use the Python code provided in the dialog.
@ DragAndDrop
"Drag and drop" layout. Needs to be configured.
@ UiFile
Load a .ui file for the layout. Needs to be configured.
@ Warning
Warning message.
@ Info
Information message.
@ Success
Used for reporting a successful operation.
@ Normal
A normal relation.
@ Join
Field originates from a joined layer.
@ Action
A layer action element.
@ QmlElement
A QML element.
@ HtmlElement
A HTML element.
@ TextElement
A text element.
@ SpacerElement
A spacer element.
SelectBehavior
Specifies how a selection should be applied.
@ SetSelection
Set selection, removing any existing selection.
@ AddToSelection
Add selection to current selection.
@ IntersectSelection
Modify current selection to include only select features which match.
@ RemoveFromSelection
Remove from current selection.
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.
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.
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...
Q_INVOKABLE bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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 displayName() const
Returns the name to use when displaying this field.
QgsDefaultValue defaultValueDefinition
QgsFieldConstraints constraints
Container of fields for a vector layer.
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.
static bool allowExecutionOfEmbeddedScripts(QgsProject *project, QgsMessageBar *messageBar=nullptr)
Returns true if python embedded in a project is currently allowed to be loaded.
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.
T data() const
Access the payload data.
static Qgis::ProjectTrustStatus checkUserTrust(QgsProject *project)
Returns the current trust status of the specified project.
QgsRelationManager * relationManager
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.
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.
Represents a relationship between two vector layers.
Qgis::RelationshipType type() const
Returns the type of the relation.
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.
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.
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...
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
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)
#define QgsDebugError(str)