42#include "moc_qgsrelationreferencewidget.cpp"
44using namespace Qt::StringLiterals;
51 for (
int i = 0; i < list.size(); ++i )
63 mTopLayout =
new QVBoxLayout(
this );
64 mTopLayout->setContentsMargins( 0, 0, 0, 0 );
66 setSizePolicy( sizePolicy().horizontalPolicy(), QSizePolicy::Fixed );
68 setLayout( mTopLayout );
70 QHBoxLayout *editLayout =
new QHBoxLayout();
71 editLayout->setContentsMargins( 0, 0, 0, 0 );
72 editLayout->setSpacing( 2 );
75 mChooserContainer =
new QWidget;
76 editLayout->addWidget( mChooserContainer );
77 QHBoxLayout *chooserLayout =
new QHBoxLayout;
78 chooserLayout->setContentsMargins( 0, 0, 0, 0 );
79 mFilterLayout =
new QHBoxLayout;
80 mFilterLayout->setContentsMargins( 0, 0, 0, 0 );
81 mFilterContainer =
new QWidget;
82 mFilterContainer->setLayout( mFilterLayout );
83 mChooserContainer->setLayout( chooserLayout );
84 chooserLayout->addWidget( mFilterContainer );
87 mChooserContainer->layout()->addWidget( mComboBox );
90 mOpenFormButton =
new QToolButton();
92 mOpenFormButton->setText( tr(
"Open Related Feature Form" ) );
93 editLayout->addWidget( mOpenFormButton );
95 mAddEntryButton =
new QToolButton();
97 mAddEntryButton->setText( tr(
"Add New Entry" ) );
98 editLayout->addWidget( mAddEntryButton );
101 mHighlightFeatureButton =
new QToolButton(
this );
102 mHighlightFeatureButton->setPopupMode( QToolButton::MenuButtonPopup );
103 mHighlightFeatureAction =
new QAction(
QgsApplication::getThemeIcon( u
"/mActionHighlightFeature.svg"_s ), tr(
"Highlight feature" ),
this );
104 mScaleHighlightFeatureAction =
new QAction(
QgsApplication::getThemeIcon( u
"/mActionScaleHighlightFeature.svg"_s ), tr(
"Scale and highlight feature" ),
this );
105 mPanHighlightFeatureAction =
new QAction(
QgsApplication::getThemeIcon( u
"/mActionPanHighlightFeature.svg"_s ), tr(
"Pan and highlight feature" ),
this );
106 mHighlightFeatureButton->addAction( mHighlightFeatureAction );
107 mHighlightFeatureButton->addAction( mScaleHighlightFeatureAction );
108 mHighlightFeatureButton->addAction( mPanHighlightFeatureAction );
109 mHighlightFeatureButton->setDefaultAction( mHighlightFeatureAction );
110 editLayout->addWidget( mHighlightFeatureButton );
113 mMapIdentificationButton =
new QToolButton(
this );
115 mMapIdentificationButton->setText( tr(
"Select on Map" ) );
116 mMapIdentificationButton->setCheckable(
true );
117 editLayout->addWidget( mMapIdentificationButton );
120 mRemoveFKButton =
new QToolButton(
this );
122 mRemoveFKButton->setText( tr(
"No Selection" ) );
123 editLayout->addWidget( mRemoveFKButton );
126 mTopLayout->addLayout( editLayout );
130 mAttributeEditorLayout =
new QVBoxLayout( mAttributeEditorFrame );
131 mAttributeEditorFrame->setLayout( mAttributeEditorLayout );
132 mAttributeEditorFrame->setSizePolicy( mAttributeEditorFrame->sizePolicy().horizontalPolicy(), QSizePolicy::Expanding );
133 mTopLayout->addWidget( mAttributeEditorFrame );
136 mInvalidLabel =
new QLabel( tr(
"The relation is not valid. Please make sure your relation definitions are OK." ) );
137 mInvalidLabel->setWordWrap(
true );
138 QFont font = mInvalidLabel->font();
139 font.setItalic(
true );
140 mInvalidLabel->setStyleSheet( u
"QLabel { color: red; } "_s );
141 mInvalidLabel->setFont( font );
142 mTopLayout->addWidget( mInvalidLabel );
145 mMapIdentificationButton->hide();
146 mHighlightFeatureButton->hide();
147 mAttributeEditorFrame->hide();
148 mInvalidLabel->hide();
149 mAddEntryButton->hide();
153 connect( mHighlightFeatureButton, &QToolButton::triggered,
this, &QgsRelationReferenceWidget::highlightActionTriggered );
156 connect( mAddEntryButton, &QAbstractButton::clicked,
this, &QgsRelationReferenceWidget::addEntry );
157 connect( mComboBox, &QComboBox::editTextChanged,
this, &QgsRelationReferenceWidget::updateAddEntryButton );
168 mAllowNull = allowNullValue;
169 mRemoveFKButton->setVisible( allowNullValue && mReadOnlySelector );
173 mReferencedLayerId =
relation.referencedLayerId();
174 mReferencedLayerName =
relation.referencedLayer()->name();
176 mReferencedLayerProviderKey =
relation.referencedLayer()->providerType();
177 mInvalidLabel->hide();
180 mReferencingLayer =
relation.referencingLayer();
181 mReferencedLayer =
relation.referencedLayer();
183 const QList<QgsRelation::FieldPair> fieldPairs =
relation.fieldPairs();
186 mReferencedFields << fieldPair.referencedField();
190 mComboBox->setAllowNull( mAllowNull );
191 mComboBox->setSourceLayer( mReferencedLayer );
192 mComboBox->setIdentifierFields( mReferencedFields );
193 mComboBox->setFilterExpression( mFilterExpression );
194 mComboBox->setFetchLimit( mFetchLimit );
195 mComboBox->setOrderExpression( mOrderExpression );
196 mComboBox->setSortOrder( mSortOrder );
198 mAttributeEditorFrame->setObjectName( u
"referencing/"_s +
relation.name() );
203 mAttributeEditorFrame->setTitle( mReferencedLayer->name() );
205 mAttributeEditorLayout->addWidget( mReferencedAttributeForm );
210 updateAddEntryButton();
214 mInvalidLabel->show();
217 if ( mShown && isVisible() )
230 mFilterContainer->setEnabled( editable );
231 mComboBox->setEnabled( editable && !mReadOnlySelector );
232 mComboBox->setEditable(
true );
233 mMapIdentificationButton->setEnabled( editable );
234 mRemoveFKButton->setEnabled( editable );
235 mIsEditable = editable;
245 if ( values.isEmpty() )
255 if ( !mReferencedLayer )
258 mComboBox->setIdentifierValues( values );
260 if ( mEmbedForm || mChainFilters )
263 mReferencedLayer->getFeatures( request ).nextFeature( mFeature );
268 const int count = std::min( mFilterComboBoxes.size(), mFilterFields.size() );
269 for (
int i = 0; i < count; i++ )
271 QVariant v = mFeature.attribute( mFilterFields[i] );
273 mFilterComboBoxes.at( i )->setCurrentIndex( mFilterComboBoxes.at( i )->findText( f ) );
277 mRemoveFKButton->setEnabled( mIsEditable );
278 highlightFeature( mFeature );
279 updateAttributeEditorFrame( mFeature );
287 if ( mChainFilters && !mFilterComboBoxes.isEmpty() )
289 QComboBox *cb = mFilterComboBoxes.first();
290 cb->setCurrentIndex( 0 );
291 disableChainedComboBoxes( cb );
294 mComboBox->setIdentifierValuesToNull();
295 mRemoveFKButton->setEnabled(
false );
307 return mReferencedAttributeForm->save();
313 if ( mReferencedLayer )
315 mReferencedLayer->getFeatures( mComboBox->currentFeatureRequest() ).nextFeature( f );
323 mRemoveFKButton->setEnabled(
false );
330 if ( fkeys.isEmpty() )
333 return fkeys.at( 0 );
338 return mComboBox->identifierValues();
343 mEditorContext = context;
345 mMessageBar = messageBar;
348 mMapToolIdentify->setButton( mMapIdentificationButton );
350 if ( mEditorContext.cadDockWidget() )
353 mMapToolDigitize->setButton( mAddEntryButton );
354 updateAddEntryButton();
362 setSizePolicy( sizePolicy().horizontalPolicy(), QSizePolicy::MinimumExpanding );
363 mTopLayout->setAlignment( Qt::AlignTop );
366 mAttributeEditorFrame->setVisible( display );
367 mEmbedForm = display;
372 mComboBox->setEnabled( !readOnly );
373 mRemoveFKButton->setVisible( mAllowNull && readOnly );
374 mReadOnlySelector = readOnly;
386 mFilterFields = filterFields;
402 mFilterExpression = expression;
416 if ( mReferencedLayer )
418 QApplication::setOverrideCursor( Qt::WaitCursor );
420 QSet<QString> requestedAttrs;
422 if ( !mFilterFields.isEmpty() )
424 for (
const QString &fieldName : std::as_const( mFilterFields ) )
426 int idx = mReferencedLayer->fields().lookupField( fieldName );
431 QComboBox *cb =
new QComboBox();
432 cb->setProperty(
"Field", fieldName );
433 cb->setProperty(
"FieldAlias", mReferencedLayer->attributeDisplayName( idx ) );
434 mFilterComboBoxes << cb;
435 QVariantList uniqueValues = qgis::setToList( mReferencedLayer->uniqueValues( idx ) );
436 cb->addItem( mReferencedLayer->attributeDisplayName( idx ) );
441 const auto constUniqueValues = uniqueValues;
442 for (
const QVariant &v : constUniqueValues )
444 cb->addItem( v.toString(), v );
447 connect( cb,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
this, &QgsRelationReferenceWidget::filterChanged );
450 requestedAttrs << fieldName;
452 mFilterLayout->addWidget( cb );
461 ? mReferencedLayer->getFeatures()
462 : mReferencedLayer->getFeatures( mFilterExpression );
465 const int count = std::min( mFilterComboBoxes.count(), mFilterFields.count() );
466 for (
int i = 0; i < count - 1; i++ )
468 QVariant cv = ft.
attribute( mFilterFields.at( i ) );
469 QVariant nv = ft.
attribute( mFilterFields.at( i + 1 ) );
472 mFilterCache[mFilterFields[i]][cf] << nf;
476 if ( !mFilterComboBoxes.isEmpty() )
478 QComboBox *cb = mFilterComboBoxes.first();
479 cb->setCurrentIndex( 0 );
480 disableChainedComboBoxes( cb );
486 mFilterContainer->hide();
489 mComboBox->setSourceLayer( mReferencedLayer );
490 mComboBox->setDisplayExpression( mReferencedLayer->displayExpression() );
491 mComboBox->setAllowNull( mAllowNull );
492 mComboBox->setIdentifierFields( mReferencedFields );
493 mComboBox->setFetchLimit( mFetchLimit );
494 mComboBox->setOrderExpression( mOrderExpression );
495 mComboBox->setSortOrder( mSortOrder );
497 if ( !mFilterExpression.isEmpty() )
498 mComboBox->setFilterExpression( mFilterExpression );
502 if ( mChainFilters && mFeature.isValid() )
504 for (
int i = 0; i < mFilterFields.size(); i++ )
506 QVariant v = mFeature.attribute( mFilterFields[i] );
508 mFilterComboBoxes.at( i )->setCurrentIndex( mFilterComboBoxes.at( i )->findText( f ) );
517 QApplication::restoreOverrideCursor();
523void QgsRelationReferenceWidget::highlightActionTriggered( QAction *action )
525 if ( action == mHighlightFeatureAction )
529 else if ( action == mScaleHighlightFeatureAction )
531 highlightFeature( QgsFeature(),
Scale );
533 else if ( action == mPanHighlightFeatureAction )
535 highlightFeature( QgsFeature(),
Pan );
548 attributeDialog->
show();
551void QgsRelationReferenceWidget::highlightFeature(
QgsFeature f, CanvasExtent canvasExtent )
571 if ( canvasExtent ==
Scale )
574 featBBox = mCanvas->mapSettings().layerToMapCoordinates( mReferencedLayer, featBBox );
575 QgsRectangle extent = mCanvas->extent();
580 mCanvas->setExtent( extent,
true );
584 else if ( canvasExtent ==
Pan )
586 QgsGeometry centroid = geom.
centroid();
587 QgsPointXY center = centroid.
asPoint();
588 center = mCanvas->mapSettings().layerToMapCoordinates( mReferencedLayer, center );
589 mCanvas->zoomByFactor( 1.0, ¢er );
594 mHighlight =
new QgsHighlight( mCanvas, f, mReferencedLayer );
595 mHighlight->applyDefaultStyle();
598 QTimer *timer =
new QTimer(
this );
599 timer->setSingleShot(
true );
600 connect( timer, &QTimer::timeout,
this, &QgsRelationReferenceWidget::deleteHighlight );
601 timer->start( 3000 );
604void QgsRelationReferenceWidget::deleteHighlight()
611 mHighlight =
nullptr;
616 if ( !mAllowMapIdentification || !mReferencedLayer )
625 mMapToolIdentify->setLayer( mReferencedLayer );
626 setMapTool( mMapToolIdentify );
632 QString title = tr(
"Relation %1 for %2." ).arg( mRelation.name(), mReferencingLayer->name() );
633 QString msg = tr(
"Identify a feature of %1 to be associated. Press <ESC> to cancel." ).arg( mReferencedLayer->name() );
635 mMessageBar->pushItem( mMessageBarItem );
639void QgsRelationReferenceWidget::comboReferenceChanged()
642 highlightFeature( mFeature );
643 updateAttributeEditorFrame( mFeature );
648void QgsRelationReferenceWidget::comboReferenceFoundChanged(
bool )
650 mReferencedLayer->getFeatures( mComboBox->currentFeatureRequest() ).nextFeature( mFeature );
651 highlightFeature( mFeature );
652 updateAttributeEditorFrame( mFeature );
655void QgsRelationReferenceWidget::updateAttributeEditorFrame(
const QgsFeature &feature )
657 mOpenFormButton->setEnabled( feature.
isValid() );
659 if ( mAttributeEditorFrame && mReferencedAttributeForm )
661 mReferencedAttributeForm->setFeature( feature );
667 return mAllowAddFeatures;
673 updateAddEntryButton();
681void QgsRelationReferenceWidget::featureIdentified(
const QgsFeature &feature )
686 mRemoveFKButton->setEnabled( mIsEditable );
687 highlightFeature( feature );
688 updateAttributeEditorFrame( feature );
694void QgsRelationReferenceWidget::setMapTool(
QgsMapTool *mapTool )
696 mCurrentMapTool = mapTool;
697 mCanvas->setMapTool( mapTool );
699 mWindowWidget = window();
701 mCanvas->window()->raise();
702 mCanvas->activateWindow();
707void QgsRelationReferenceWidget::unsetMapTool()
710 if ( mCurrentMapTool )
713 mCanvas->unsetMapTool( mCurrentMapTool );
715 if ( mCurrentMapTool == mMapToolDigitize )
727void QgsRelationReferenceWidget::onKeyPressed( QKeyEvent *e )
729 if ( e->key() == Qt::Key_Escape )
735void QgsRelationReferenceWidget::mapToolDeactivated()
739 mWindowWidget->raise();
740 mWindowWidget->activateWindow();
743 if ( mMessageBar && mMessageBarItem )
745 mMessageBar->popWidget( mMessageBarItem );
747 mMessageBarItem =
nullptr;
750void QgsRelationReferenceWidget::filterChanged()
754 QMap<QString, QString> filters;
757 QComboBox *scb = qobject_cast<QComboBox *>( sender() );
771 disableChainedComboBoxes( scb );
774 const auto constMFilterComboBoxes = mFilterComboBoxes;
775 for ( QComboBox *cb : constMFilterComboBoxes )
777 if ( cb->currentIndex() != 0 )
779 const QString fieldName = cb->property(
"Field" ).toString();
781 if ( cb->currentText() == nullValue.toString() )
783 filters[fieldName] = u
"\"%1\" IS NULL"_s.arg( fieldName );
789 attrs << mReferencedLayer->fields().lookupField( fieldName );
795 QComboBox *ccb =
nullptr;
796 const auto constMFilterComboBoxes = mFilterComboBoxes;
797 for ( QComboBox *cb : constMFilterComboBoxes )
807 if ( ccb->currentIndex() != 0 )
809 const QString fieldName = cb->property(
"Field" ).toString();
811 cb->blockSignals(
true );
813 cb->addItem( cb->property(
"FieldAlias" ).toString() );
818 const auto txts { mFilterCache[ccb->property(
"Field" ).toString()][ccb->currentText()] };
819 for (
const QString &txt : txts )
821 QMap<QString, QString> filtersAttrs = filters;
826 if ( !expression.isEmpty() && !filtersAttrs.isEmpty() )
827 expression +=
" AND "_L1;
829 expression += filtersAttrs.isEmpty() ? QString() : u
" ( "_s;
831 expression += filtersAttrs.isEmpty() ? QString() : u
" ) "_s;
833 subset << mReferencedLayer->fields().lookupField( fieldName );
835 QgsFeatureIterator it( mReferencedLayer->getFeatures( QgsFeatureRequest().
setFilterExpression( expression ).setSubsetOfAttributes( subset ) ) );
838 while ( it.nextFeature( f ) )
840 if ( !featureIds.contains( f.
id() ) )
841 featureIds << f.
id();
852 cb->addItems( texts );
854 cb->setEnabled(
true );
855 cb->blockSignals(
false );
872void QgsRelationReferenceWidget::addEntry()
874 if ( !mReferencedLayer )
877 const QgsVectorLayerTools *tools = mEditorContext.vectorLayerTools();
886 QgsFeature f( mReferencedLayer->fields() );
891 mMapToolDigitize->setLayer( mReferencedLayer );
892 setMapTool( mMapToolDigitize );
899 QString title = tr(
"Relation %1 for %2." ).arg( mRelation.name(), mReferencingLayer->name() );
902 QString msg = tr(
"Link feature to %1 \"%2\" : Digitize the geometry for the new feature on layer %3. Press <ESC> to cancel." )
903 .arg( mReferencingLayer->name(), displayString, mReferencedLayer->name() );
905 mMessageBar->pushItem( mMessageBarItem );
909void QgsRelationReferenceWidget::entryAdded(
const QgsFeature &feat )
911 QgsFeature f( feat );
915 if ( mComboBox->itemText( mComboBox->currentIndex() ) != mComboBox->currentText() )
917 int fieldIdx = mReferencedLayer->fields().lookupField( mReferencedLayer->displayExpression() );
919 if ( fieldIdx != -1 )
921 attributes.insert( fieldIdx, mComboBox->currentText() );
925 if ( mEditorContext.vectorLayerTools()->addFeature( mReferencedLayer, attributes, f.
geometry(), &f,
this,
false,
true ) )
928 for (
const QString &fieldName : std::as_const( mReferencedFields ) )
933 mAddEntryButton->setEnabled(
false );
939void QgsRelationReferenceWidget::updateAddEntryButton()
941 mAddEntryButton->setVisible( mAllowAddFeatures && mMapToolDigitize );
942 mAddEntryButton->setEnabled( mReferencedLayer && mReferencedLayer->isEditable() );
945void QgsRelationReferenceWidget::disableChainedComboBoxes(
const QComboBox *scb )
947 QComboBox *ccb =
nullptr;
948 const auto constMFilterComboBoxes = mFilterComboBoxes;
949 for ( QComboBox *cb : constMFilterComboBoxes )
961 cb->setCurrentIndex( 0 );
962 if ( ccb->currentIndex() == 0 )
964 cb->setEnabled(
false );
971void QgsRelationReferenceWidget::emitForeignKeysChanged(
const QVariantList &foreignKeys,
bool force )
985 return mReferencedLayerName;
990 mReferencedLayerName = relationLayerName;
995 return mReferencedLayerId;
1000 mReferencedLayerId = relationLayerId;
1005 return mReferencedLayerProviderKey;
1010 mReferencedLayerProviderKey = relationProviderKey;
1015 return mReferencedLayerDataSource;
1021 mReferencedLayerDataSource = resolver.
writePath( relationDataSource );
1026 mComboBox->setFormFeature( formFeature );
1031 mComboBox->setParentFormFeature( parentFormFeature );
static QString nullRepresentation()
Returns the string used to represent the value NULL throughout QGIS.
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
An attribute table dialog for a vector layer.
void show()
Show the dialog non-blocking. Reparents this dialog to be a child of the dialog form.
Contains context information for attribute editor widgets.
@ Single
When showing a single feature (e.g. district information when looking at the form of a house).
@ Embed
A form was embedded as a widget on another form.
@ StandaloneDialog
A form was opened as a new dialog.
A groupbox that collapses/expands when toggled and can save its collapsed and checked states.
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value, QMetaType::Type fieldType=QMetaType::Type::UnknownType)
Create an expression allowing to evaluate if a field is equal to a value.
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.
This offers a combobox with autocompleter that allows selecting features from a layer.
QgsFeatureRequest currentFeatureRequest() const
Shorthand for getting a feature request to query the currently selected feature.
QVariantList identifierValues
void setCurrentFeature(const QgsFeature &feature)
Sets the current index by using the given feature.
void currentFeatureFoundChanged(bool found)
Emitted when the feature picker model changes its feature found state.
void currentFeatureChanged()
Emitted when the current feature changes.
Wraps a request for features to a vector layer (or directly its vector data provider).
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isValid() const
Returns the validity of this feature.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Map canvas is a class for displaying all GIS data types on a canvas.
void keyPressed(QKeyEvent *e)
Emit key press event.
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.
static QgsMessageBarItem * createMessage(const QString &text, QWidget *parent=nullptr)
Creates message bar item widget containing a message text to be displayed on the bar.
Resolves relative paths into absolute paths and vice versa.
QString writePath(const QString &filename) const
Prepare a filename to save it to the project file.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsPathResolver pathResolver() const
Returns path resolver object with considering whether the project uses absolute or relative paths and...
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
bool contains(const QgsRectangle &rect) const
Returns true when rectangle contains other rectangle.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
Defines a relation between matching fields of the two involved tables of a relation.
Represents a relationship between two vector layers.
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.
static QString getFeatureDisplayString(const QgsVectorLayer *layer, const QgsFeature &feature)
Returns a descriptive string for a feature, suitable for displaying to the user.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
bool qgsVariantLessThan(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether the first is less than the second.
#define Q_NOWARN_DEPRECATED_POP
QString qgsMapJoinValues(const QMap< Key, Value > &map, const QString &separator)
Joins all the map values into a single string with each element separated by the given separator.
#define Q_NOWARN_DEPRECATED_PUSH
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
QMap< int, QVariant > QgsAttributeMap
QSet< QgsFeatureId > QgsFeatureIds
QList< int > QgsAttributeList