QGIS API Documentation 3.39.0-Master (d85f3c2a281)
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#include "qgsproject.h"
19#include "qgsrelationmanager.h"
21#include "qgsattributeform.h"
22
23QgsRelationReferenceWidgetWrapper::QgsRelationReferenceWidgetWrapper( QgsVectorLayer *vl, int fieldIdx, QWidget *editor, QgsMapCanvas *canvas, QgsMessageBar *messageBar, QWidget *parent )
24 : QgsEditorWidgetWrapper( vl, fieldIdx, editor, parent )
25 , mCanvas( canvas )
26 , mMessageBar( messageBar )
27 , mIndeterminateState( false )
28{
29}
30
32{
34 return w;
35}
36
38{
39 QgsRelationReferenceWidget *w = qobject_cast<QgsRelationReferenceWidget *>( editor );
40 if ( !w )
41 {
42 w = new QgsRelationReferenceWidget( editor );
43 }
44
45 mWidget = w;
46
47 const QgsAttributeEditorContext *ctx = &context();
48
49 mWidget->setEditorContext( *ctx, mCanvas, mMessageBar );
50
51 const bool showForm = config( QStringLiteral( "ShowForm" ), false ).toBool();
52 const bool mapIdent = config( QStringLiteral( "MapIdentification" ), false ).toBool();
53 const bool readOnlyWidget = config( QStringLiteral( "ReadOnly" ), false ).toBool();
54 const bool showOpenFormButton = config( QStringLiteral( "ShowOpenFormButton" ), true ).toBool();
55
56 mWidget->setEmbedForm( showForm );
57 mWidget->setReadOnlySelector( readOnlyWidget );
58 mWidget->setAllowMapIdentification( mapIdent );
59 mWidget->setOpenFormButtonVisible( showOpenFormButton );
60
61 const bool fetchLimitActive = config( QStringLiteral( "FetchLimitActive" ), QgsSettings().value( QStringLiteral( "maxEntriesRelationWidget" ), 100, QgsSettings::Gui ).toInt() > 0 ).toBool();
62 if ( fetchLimitActive )
63 {
64 mWidget->setFetchLimit( config( QStringLiteral( "FetchLimitNumber" ), QgsSettings().value( QStringLiteral( "maxEntriesRelationWidget" ), 100, QgsSettings::Gui ) ).toInt() );
65 }
66
67 if ( config( QStringLiteral( "FilterFields" ), QVariant() ).isValid() )
68 {
69 mWidget->setFilterFields( config( QStringLiteral( "FilterFields" ) ).toStringList() );
70 mWidget->setChainFilters( config( QStringLiteral( "ChainFilters" ) ).toBool() );
71 }
72 if ( !config( QStringLiteral( "FilterExpression" ) ).toString().isEmpty() )
73 {
74 mWidget->setFilterExpression( config( QStringLiteral( "FilterExpression" ) ).toString() );
75 }
76 mWidget->setAllowAddFeatures( config( QStringLiteral( "AllowAddFeatures" ), false ).toBool() );
77
78 const QVariant relationName = config( QStringLiteral( "Relation" ) );
79
80 // Store relation data source and provider key
81 mWidget->setReferencedLayerDataSource( config( QStringLiteral( "ReferencedLayerDataSource" ) ).toString() );
82 mWidget->setReferencedLayerProviderKey( config( QStringLiteral( "ReferencedLayerProviderKey" ) ).toString() );
83 mWidget->setReferencedLayerId( config( QStringLiteral( "ReferencedLayerId" ) ).toString() );
84 mWidget->setReferencedLayerName( config( QStringLiteral( "ReferencedLayerName" ) ).toString() );
85
86 QgsRelation relation; // invalid relation by default
87 if ( relationName.isValid() )
88 relation = QgsProject::instance()->relationManager()->relation( relationName.toString() );
89 if ( !relation.isValid() && !layer()->referencingRelations( fieldIdx() ).isEmpty() )
90 relation = layer()->referencingRelations( fieldIdx() )[0];
91
92 // If this widget is already embedded by the same relation, reduce functionality
93 do
94 {
95 if ( ctx->relation().id() == relation.id() )
96 {
97 mWidget->setEmbedForm( false );
98 mWidget->setReadOnlySelector( true );
99 mWidget->setAllowMapIdentification( false );
100 mWidget->setOpenFormButtonVisible( false );
101 mWidget->setAllowAddFeatures( false );
102 break;
103 }
104 ctx = ctx->parentContext();
105 }
106 while ( ctx );
107
108 // If AllowNULL is not set in the config, provide a default value based on the
109 // constraints of the referencing fields
110 if ( !config( QStringLiteral( "AllowNULL" ) ).isValid() )
111 {
112 mWidget->setRelation( relation, relation.referencingFieldsAllowNull() );
113 }
114 else
115 {
116 mWidget->setRelation( relation, config( QStringLiteral( "AllowNULL" ) ).toBool() );
117 }
118
119 connect( mWidget, &QgsRelationReferenceWidget::foreignKeysChanged, this, &QgsRelationReferenceWidgetWrapper::foreignKeysChanged );
120}
121
123{
124 if ( !mWidget )
125 return QgsVariantUtils::createNullVariant( field().type() );
126
127 const QVariantList fkeys = mWidget->foreignKeys();
128
129 if ( fkeys.isEmpty() )
130 {
131 return QgsVariantUtils::createNullVariant( field().type() );
132 }
133 else
134 {
135 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
136 Q_ASSERT( fieldPairs.count() == fkeys.count() );
137 for ( int i = 0; i < fieldPairs.count(); i++ )
138 {
139 if ( fieldPairs.at( i ).referencingField() == field().name() )
140 return fkeys.at( i );
141 }
142 return QgsVariantUtils::createNullVariant( field().type() ); // should not happen
143 }
144}
145
147{
148 return mWidget;
149}
150
152{
153 if ( mWidget )
154 {
155 mWidget->showIndeterminateState();
156 }
157 mIndeterminateState = true;
158}
159
161{
162 if ( !mWidget )
163 return {};
164
165 if ( !mWidget->relation().isValid() )
166 {
167 QVariantList values;
168 for ( int i = 0; i < mWidget->relation().fieldPairs().count(); i++ )
169 {
170 values << QVariant();
171 }
172 return values;
173 }
174 else
175 {
176 QVariantList values = mWidget->foreignKeys();
177 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
178 const int fieldCount = std::min( fieldPairs.count(), values.count() );
179 for ( int i = 0; i < fieldCount; i++ )
180 {
181 if ( fieldPairs.at( i ).referencingField() == field().name() )
182 {
183 values.removeAt( i );
184 break;
185 }
186 }
187 return values;
188 }
189}
190
192{
193 if ( !mWidget || !mWidget->relation().isValid() )
194 return QStringList();
195
196 QStringList fields;
197 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
198 for ( int i = 0; i < fieldPairs.count(); i++ )
199 {
200 if ( fieldPairs.at( i ).referencingField() == field().name() )
201 continue;
202
203 fields << fieldPairs.at( i ).referencingField();
204 }
205 return fields;
206}
207
208void QgsRelationReferenceWidgetWrapper::updateValues( const QVariant &val, const QVariantList &additionalValues )
209{
210 if ( !mWidget || ( !mIndeterminateState && val == value() && QgsVariantUtils::isNull( val ) == QgsVariantUtils::isNull( value() ) ) )
211 return;
212
213 mIndeterminateState = false;
214
215 QVariantList values = additionalValues;
216 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
217 for ( int i = 0; i < fieldPairs.count(); i++ )
218 {
219 if ( fieldPairs.at( i ).referencingField() == field().name() )
220 {
221 values.insert( i, val );
222 break;
223 }
224 }
225 Q_ASSERT( values.count() == fieldPairs.count() );
226
227 mBlockChanges++;
228 mWidget->setForeignKeys( values );
229 mWidget->setFormFeature( formFeature() );
230 mBlockChanges--;
231}
232
234{
235 if ( !mWidget )
236 return;
237
238 mWidget->setRelationEditable( enabled );
239}
240
241void QgsRelationReferenceWidgetWrapper::foreignKeysChanged( const QVariantList &values )
242{
243 if ( mBlockChanges != 0 ) // initial value is being set, we can ignore this signal
244 return;
245
246 QVariant mainValue = QgsVariantUtils::createNullVariant( field().type() );
247
248 if ( !mWidget || !mWidget->relation().isValid() )
249 {
251 emit valueChanged( mainValue );
253 emit valuesChanged( mainValue );
254 return;
255 }
256
257 QVariantList additionalValues = values;
258 const QList<QgsRelation::FieldPair> fieldPairs = mWidget->relation().fieldPairs();
259 for ( int i = 0; i < fieldPairs.count(); i++ )
260 {
261 if ( fieldPairs.at( i ).referencingField() == field().name() )
262 mainValue = additionalValues.takeAt( i ); // additional values in field pair order remain
263 }
264 Q_ASSERT( additionalValues.count() == values.count() - 1 );
265
267 emit valueChanged( mainValue );
269 emit valuesChanged( mainValue, additionalValues );
270}
271
273{
274 if ( mWidget )
275 {
277 {
278 widget()->setStyleSheet( QString() );
279 }
280 else
281 {
282 switch ( constraintResult() )
283 {
285 mWidget->setStyleSheet( QString() );
286 break;
287
289 mWidget->setStyleSheet( QStringLiteral( ".QComboBox { background-color: #dd7777; }" ) );
290 break;
291
293 mWidget->setStyleSheet( QStringLiteral( ".QComboBox { background-color: #ffd85d; }" ) );
294 break;
295 }
296 }
297 }
298}
This class contains context information for attribute editor widgets.
const QgsAttributeEditorContext * parentContext() const
const QgsRelation & relation() const
Returns the attribute relation.
Manages an editor widget Widget and wrapper share the same parent.
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.
void valuesChanged(const QVariant &value, const QVariantList &additionalFieldValues=QVariantList())
Emit this signal, whenever the value changed.
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.
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:117
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 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.
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.
void setFilterExpression(const QString &filterExpression)
If not empty, will be used as filter expression.
void setReferencedLayerProviderKey(const QString &referencedLayerProviderKey)
Set the data provider key of the referenced layer to referencedLayerProviderKey.
void setChainFilters(bool chainFilters)
Set if filters are chained.
void setEditorContext(const QgsAttributeEditorContext &context, QgsMapCanvas *canvas, QgsMessageBar *messageBar)
Sets the editor context.
void setReferencedLayerName(const QString &referencedLayerName)
Set the name of the referenced layer to referencedLayerName.
void showIndeterminateState()
Sets the widget to display in an indeterminate "mixed value" state.
void setReferencedLayerDataSource(const QString &referencedLayerDataSource)
Set the public data source of the referenced layer to referencedLayerDataSource.
void setFilterFields(const QStringList &filterFields)
Sets the fields for which filter comboboxes will be created.
void setAllowMapIdentification(bool allowMapIdentification)
QgsRelation relation() const
Returns the current relation, which might be invalid.
void setReferencedLayerId(const QString &referencedLayerId)
Set the id of the referenced layer to referencedLayerId.
QVariantList foreignKeys() const
returns the related feature foreign key
void setForeignKeys(const QVariantList &values)
Sets the related feature using the foreign keys.
void foreignKeysChanged(const QVariantList &keys)
Emitted when the foreign keys changed.
void setRelation(const QgsRelation &relation, bool allowNullValue)
void setOpenFormButtonVisible(bool openFormButtonVisible)
void setAllowAddFeatures(bool allowAddFeatures)
Determines if a button for adding new features should be shown.
void setFetchLimit(int fetchLimit)
Set the limit of fetched features (0 means all features)
void setFormFeature(const QgsFeature &formFeature)
Set the current form feature (from the referencing layer)
Represents a relationship between two vector layers.
Definition qgsrelation.h:44
QString id
Definition qgsrelation.h:47
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.
This class is a composition of two QSettings instances:
Definition qgssettings.h:64
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 data sets.
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.
QVariantMap config() const
Returns the whole config.
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:6434
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:6433