QGIS API Documentation 3.99.0-Master (d270888f95f)
Loading...
Searching...
No Matches
qgsrelationreferencewidgetwrapper.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsrelationreferencewidgetwrapper.cpp
3 --------------------------------------
4 Date : 20.4.2013
5 Copyright : (C) 2013 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
18
19#include "qgsattributeform.h"
20#include "qgsproject.h"
21#include "qgsrelationmanager.h"
24
25#include <QString>
26
27#include "moc_qgsrelationreferencewidgetwrapper.cpp"
28
29using namespace Qt::StringLiterals;
30
32 : QgsEditorWidgetWrapper( vl, fieldIdx, editor, parent )
33 , mCanvas( canvas )
34 , mMessageBar( messageBar )
35
36{
37}
38
40{
41 QgsAttributeForm *form = qobject_cast<QgsAttributeForm *>( parent );
42 if ( form )
44
46 return w;
47}
48
50{
51 QgsRelationReferenceWidget *w = qobject_cast<QgsRelationReferenceWidget *>( editor );
52 if ( !w )
53 {
54 w = new QgsRelationReferenceWidget( editor );
55 }
56
57 mWidget = w;
58
59 const QgsAttributeEditorContext *ctx = &context();
60
61 mWidget->setEditorContext( *ctx, mCanvas, mMessageBar );
62
63 const bool showForm = config( u"ShowForm"_s, false ).toBool();
64 const bool mapIdent = config( u"MapIdentification"_s, false ).toBool();
65 const bool readOnlyWidget = config( u"ReadOnly"_s, false ).toBool();
66 const bool showOpenFormButton = config( u"ShowOpenFormButton"_s, true ).toBool();
67
68 mWidget->setEmbedForm( showForm );
69 mWidget->setReadOnlySelector( readOnlyWidget );
70 mWidget->setAllowMapIdentification( mapIdent );
71 mWidget->setOpenFormButtonVisible( showOpenFormButton );
72
73 const bool fetchLimitActive = config( u"FetchLimitActive"_s, QgsSettings().value( u"maxEntriesRelationWidget"_s, 100, QgsSettings::Gui ).toInt() > 0 ).toBool();
74 if ( fetchLimitActive )
75 {
76 mWidget->setFetchLimit( config( u"FetchLimitNumber"_s, QgsSettings().value( u"maxEntriesRelationWidget"_s, 100, QgsSettings::Gui ) ).toInt() );
77 }
78
79 if ( config( u"FilterFields"_s, QVariant() ).isValid() )
80 {
81 mWidget->setFilterFields( config( u"FilterFields"_s ).toStringList() );
82 mWidget->setChainFilters( config( u"ChainFilters"_s ).toBool() );
83 }
84 if ( !config( u"FilterExpression"_s ).toString().isEmpty() )
85 {
86 mWidget->setFilterExpression( config( u"FilterExpression"_s ).toString() );
87 mWidget->setFormFeature( formFeature() );
88 mWidget->setParentFormFeature( ctx->parentFormFeature() );
89 }
90 mWidget->setAllowAddFeatures( config( u"AllowAddFeatures"_s, false ).toBool() );
91
92 mWidget->setOrderExpression( config( u"OrderExpression"_s ).toString() );
93 mWidget->setSortOrder( config( u"OrderDescending"_s, false ).toBool() ? Qt::DescendingOrder : Qt::AscendingOrder );
94
95 const QVariant relationName = config( u"Relation"_s );
96
97 // Store relation data source and provider key
98 mWidget->setReferencedLayerDataSource( config( u"ReferencedLayerDataSource"_s ).toString() );
99 mWidget->setReferencedLayerProviderKey( config( u"ReferencedLayerProviderKey"_s ).toString() );
100 mWidget->setReferencedLayerId( config( u"ReferencedLayerId"_s ).toString() );
101 mWidget->setReferencedLayerName( config( u"ReferencedLayerName"_s ).toString() );
102
103 QgsRelation relation; // invalid relation by default
104 if ( relationName.isValid() )
105 relation = QgsProject::instance()->relationManager()->relation( relationName.toString() );
106 if ( !relation.isValid() && !layer()->referencingRelations( fieldIdx() ).isEmpty() )
107 relation = layer()->referencingRelations( fieldIdx() )[0];
108
109 // If this widget is already embedded by the same relation, reduce functionality
110 do
111 {
112 if ( ctx->relation().id() == relation.id() )
113 {
114 mWidget->setEmbedForm( false );
115 mWidget->setReadOnlySelector( true );
116 mWidget->setAllowMapIdentification( false );
117 mWidget->setOpenFormButtonVisible( false );
118 mWidget->setAllowAddFeatures( false );
119 break;
120 }
121 ctx = ctx->parentContext();
122 } while ( ctx );
123
124 // If AllowNULL is not set in the config, provide a default value based on the
125 // constraints of the referencing fields
126 if ( !config( u"AllowNULL"_s ).isValid() )
127 {
128 mWidget->setRelation( relation, relation.referencingFieldsAllowNull() );
129 }
130 else
131 {
132 mWidget->setRelation( relation, config( u"AllowNULL"_s ).toBool() );
133 }
134
135 connect( mWidget, &QgsRelationReferenceWidget::foreignKeysChanged, this, &QgsRelationReferenceWidgetWrapper::foreignKeysChanged );
136}
137
138void QgsRelationReferenceWidgetWrapper::aboutToSave()
139{
140 // Save changes in the embedded form
142}
143
145{
146 if ( !mWidget )
147 return QgsVariantUtils::createNullVariant( field().type() );
148
149 const QVariantList fkeys = mWidget->foreignKeys();
150
151 if ( fkeys.isEmpty() )
152 {
153 return QgsVariantUtils::createNullVariant( field().type() );
154 }
155 else
156 {
157 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
158 Q_ASSERT( fieldPairs.count() == fkeys.count() );
159 for ( int i = 0; i < fieldPairs.count(); i++ )
160 {
161 if ( fieldPairs.at( i ).referencingField() == field().name() )
162 return fkeys.at( i );
163 }
164 return QgsVariantUtils::createNullVariant( field().type() ); // should not happen
165 }
166}
167
169{
170 return mWidget;
171}
172
174{
175 if ( mWidget )
176 {
177 mWidget->showIndeterminateState();
178 }
179 mIndeterminateState = true;
180}
181
183{
184 if ( !mWidget )
185 return {};
186
187 if ( !mWidget->relation().isValid() )
188 {
189 QVariantList values;
190 for ( int i = 0; i < mWidget->relation().fieldPairs().count(); i++ )
191 {
192 values << QVariant();
193 }
194 return values;
195 }
196 else
197 {
198 QVariantList values = mWidget->foreignKeys();
199 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
200 const int fieldCount = std::min( fieldPairs.count(), values.count() );
201 for ( int i = 0; i < fieldCount; i++ )
202 {
203 if ( fieldPairs.at( i ).referencingField() == field().name() )
204 {
205 values.removeAt( i );
206 break;
207 }
208 }
209 return values;
210 }
211}
212
214{
215 if ( !mWidget || !mWidget->relation().isValid() )
216 return QStringList();
217
218 QStringList fields;
219 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
220 for ( int i = 0; i < fieldPairs.count(); i++ )
221 {
222 if ( fieldPairs.at( i ).referencingField() == field().name() )
223 continue;
224
225 fields << fieldPairs.at( i ).referencingField();
226 }
227 return fields;
228}
229
230void QgsRelationReferenceWidgetWrapper::updateValues( const QVariant &val, const QVariantList &additionalValues )
231{
232 if ( !mWidget || ( !mIndeterminateState && val == value() && QgsVariantUtils::isNull( val ) == QgsVariantUtils::isNull( value() ) ) )
233 return;
234
235 mIndeterminateState = false;
236
237 QVariantList values = additionalValues;
238 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
239 for ( int i = 0; i < fieldPairs.count(); i++ )
240 {
241 if ( fieldPairs.at( i ).referencingField() == field().name() )
242 {
243 values.insert( i, val );
244 break;
245 }
246 }
247 Q_ASSERT( values.count() == fieldPairs.count() );
248
249 mBlockChanges++;
250 mWidget->setForeignKeys( values );
251 mWidget->setFormFeature( formFeature() );
252 mBlockChanges--;
253}
254
256{
257 if ( !mWidget )
258 return;
259
260 mWidget->setRelationEditable( enabled );
261}
262
263void QgsRelationReferenceWidgetWrapper::foreignKeysChanged( const QVariantList &values )
264{
265 if ( mBlockChanges != 0 ) // initial value is being set, we can ignore this signal
266 return;
267
268 QVariant mainValue = QgsVariantUtils::createNullVariant( field().type() );
269
270 if ( !mWidget || !mWidget->relation().isValid() )
271 {
273 emit valueChanged( mainValue );
275 emit valuesChanged( mainValue );
276 return;
277 }
278
279 QVariantList additionalValues = values;
280 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
281 for ( int i = 0; i < fieldPairs.count(); i++ )
282 {
283 if ( fieldPairs.at( i ).referencingField() == field().name() )
284 mainValue = additionalValues.takeAt( i ); // additional values in field pair order remain
285 }
286 Q_ASSERT( additionalValues.count() == values.count() - 1 );
287
289 emit valueChanged( mainValue );
291 emit valuesChanged( mainValue, additionalValues );
292}
293
295{
296 if ( mWidget )
297 {
299 {
300 widget()->setStyleSheet( QString() );
301 }
302 else
303 {
304 switch ( constraintResult() )
305 {
307 mWidget->setStyleSheet( QString() );
308 break;
309
311 mWidget->setStyleSheet( u".QComboBox { background-color: #dd7777; }"_s );
312 break;
313
315 mWidget->setStyleSheet( u".QComboBox { background-color: #ffd85d; }"_s );
316 break;
317 }
318 }
319 }
320}
321
322void QgsRelationReferenceWidgetWrapper::parentFormValueChanged( const QString &attribute, const QVariant &value )
323{
324 // Update the parent feature in the context ( which means to replace the whole context :/ )
326 QgsFeature feature { context().parentFormFeature() };
327 feature.setAttribute( attribute, value );
328 ctx.setParentFormFeature( feature );
329 setContext( ctx );
330
331 // Check if the change might affect the filter expression and the cache needs updates
333 && QgsValueRelationFieldFormatter::expressionParentFormAttributes( mExpression ).contains( attribute ) )
334 {
335 mWidget->setParentFormFeature( context().parentFormFeature() );
336 }
337}
338
339void QgsRelationReferenceWidgetWrapper::widgetValueChanged( const QString &attribute, const QVariant &newValue, bool attributeChanged )
340{
341 if ( attributeChanged )
342 {
343 setFormFeatureAttribute( attribute, newValue );
344 if ( QgsValueRelationFieldFormatter::expressionRequiresFormScope( mWidget->filterExpression() )
345 && QgsValueRelationFieldFormatter::expressionFormAttributes( mWidget->filterExpression() ).contains( attribute ) )
346 {
347 mWidget->setFormFeature( formFeature() );
348 }
349 }
350}
Contains context information for attribute editor widgets.
QgsFeature parentFormFeature() const
Returns the feature of the currently edited parent form in its actual state.
void setParentFormFeature(const QgsFeature &feature)
Sets the feature of the currently edited parent form.
const QgsAttributeEditorContext * parentContext() const
const QgsRelation & relation() const
Returns the attribute relation.
The attribute form widget for vector layer features.
void widgetValueChanged(const QString &attribute, const QVariant &value, bool attributeChanged)
Notifies about changes of attributes.
QgsFeature formFeature() const
The feature currently being edited, in its current state.
Q_DECL_DEPRECATED void valueChanged(const QVariant &value)
Emit this signal, whenever the value changed.
int fieldIdx() const
Access the field index.
QgsEditorWidgetWrapper(QgsVectorLayer *vl, int fieldIdx, QWidget *editor=nullptr, QWidget *parent=nullptr)
Create a new widget wrapper.
void valuesChanged(const QVariant &value, const QVariantList &additionalFieldValues=QVariantList())
Emit this signal, whenever the value changed.
bool setFormFeatureAttribute(const QString &attributeName, const QVariant &attributeValue)
Update the feature currently being edited by changing its attribute attributeName to attributeValue.
QgsField field() const
Access the field.
@ ConstraintResultFailSoft
Widget failed at least one soft (non-enforced) constraint.
@ ConstraintResultPass
Widget passed constraints successfully.
@ ConstraintResultFailHard
Widget failed at least one hard (enforced) constraint.
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.
Map canvas is a class for displaying all GIS data types on a canvas.
A bar for displaying non-blocking messages to the user.
QgsRelationManager * relationManager
Definition qgsproject.h:123
static QgsProject * instance()
Returns the QgsProject singleton instance.
Q_INVOKABLE QgsRelation relation(const QString &id) const
Gets access to a relation by its id.
bool valid() const override
Returns true if the widget has been properly initialized.
QVariant value() const override
Will be used to access the widget's value.
void widgetValueChanged(const QString &attribute, const QVariant &newValue, bool attributeChanged)
Will be called when a value in the current edited form or table row changes.
void showIndeterminateState() override
Sets the widget to display in an indeterminate "mixed value" state.
QgsRelationReferenceWidgetWrapper(QgsVectorLayer *vl, int fieldIdx, QWidget *editor, QgsMapCanvas *canvas, QgsMessageBar *messageBar, QWidget *parent=nullptr)
Constructor for QgsRelationReferenceWidgetWrapper.
void updateConstraintWidgetStatus() override
This should update the widget with a visual cue if a constraint status changed.
QVariantList additionalFieldValues() const override
Will be used to access the widget's values for potential additional fields handled by the widget.
void initWidget(QWidget *editor) override
This method should initialize the editor widget with runtime data.
void parentFormValueChanged(const QString &attribute, const QVariant &value) override
QStringList additionalFields() const override
Returns the list of additional fields which the editor handles.
QWidget * createWidget(QWidget *parent) override
This method should create a new widget with the provided parent.
A widget which shows related features.
bool saveReferencedAttributeForm()
Trigger save of the embedded referenced attribute form.
QgsRelation relation() const
Returns the current relation, which might be invalid.
void foreignKeysChanged(const QVariantList &keys)
Emitted when the foreign keys changed.
Represents a relationship between two vector layers.
Definition qgsrelation.h:42
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...
bool referencingFieldsAllowNull() const
Returns true if none of the referencing fields has a NOT NULL constraint.
Stores settings for use within QGIS.
Definition qgssettings.h:68
static bool expressionRequiresFormScope(const QString &expression)
Check if the expression requires a form scope (i.e.
static bool expressionRequiresParentFormScope(const QString &expression)
Check if the expression requires a parent form scope (i.e.
static QSet< QString > expressionParentFormAttributes(const QString &expression)
Returns a list of attributes required by the parent form's form context expression.
static QSet< QString > expressionFormAttributes(const QString &expression)
Returns a list of attributes required by the form context expression.
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.
Represents a vector layer which manages a vector based dataset.
QList< QgsRelation > referencingRelations(int idx) const
Returns the layer's relations, where the foreign key is on this layer.
QWidget * widget()
Access the widget managed by this wrapper.
const QgsAttributeEditorContext & context() const
Returns information about the context in which this widget is shown.
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.
QVariantMap config() const
Returns the whole config.
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:7451
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:7450