QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsrelationreferencewidget.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsrelationreferencewidget.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
17
18#include "qgsapplication.h"
19#include "qgsattributedialog.h"
20#include "qgsattributeform.h"
22#include "qgsexpression.h"
23#include "qgsfeatureiterator.h"
25#include "qgsfields.h"
26#include "qgsgeometry.h"
27#include "qgshighlight.h"
28#include "qgsmapcanvas.h"
31#include "qgsmessagebar.h"
32#include "qgsvectorlayer.h"
33#include "qgsvectorlayerutils.h"
34
35#include <QCompleter>
36#include <QDialog>
37#include <QHBoxLayout>
38#include <QPushButton>
39#include <QString>
40#include <QTimer>
41
42#include "moc_qgsrelationreferencewidget.cpp"
43
44using namespace Qt::StringLiterals;
45
46bool qVariantListIsNull( const QVariantList &list )
47{
48 if ( list.isEmpty() )
49 return true;
50
51 for ( int i = 0; i < list.size(); ++i )
52 {
53 if ( !QgsVariantUtils::isNull( list.at( i ) ) )
54 return false;
55 }
56 return true;
57}
58
59
61 : QWidget( parent )
62{
63 mTopLayout = new QVBoxLayout( this );
64 mTopLayout->setContentsMargins( 0, 0, 0, 0 );
65
66 setSizePolicy( sizePolicy().horizontalPolicy(), QSizePolicy::Fixed );
67
68 setLayout( mTopLayout );
69
70 QHBoxLayout *editLayout = new QHBoxLayout();
71 editLayout->setContentsMargins( 0, 0, 0, 0 );
72 editLayout->setSpacing( 2 );
73
74 // Prepare the container and layout for the filter comboboxes
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 );
85
86 mComboBox = new QgsFeatureListComboBox();
87 mChooserContainer->layout()->addWidget( mComboBox );
88
89 // open form button
90 mOpenFormButton = new QToolButton();
91 mOpenFormButton->setIcon( QgsApplication::getThemeIcon( u"/mActionPropertyItem.svg"_s ) );
92 mOpenFormButton->setText( tr( "Open Related Feature Form" ) );
93 editLayout->addWidget( mOpenFormButton );
94
95 mAddEntryButton = new QToolButton();
96 mAddEntryButton->setIcon( QgsApplication::getThemeIcon( u"/mActionAdd.svg"_s ) );
97 mAddEntryButton->setText( tr( "Add New Entry" ) );
98 editLayout->addWidget( mAddEntryButton );
99
100 // highlight button
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 );
111
112 // map identification button
113 mMapIdentificationButton = new QToolButton( this );
114 mMapIdentificationButton->setIcon( QgsApplication::getThemeIcon( u"/mActionMapIdentification.svg"_s ) );
115 mMapIdentificationButton->setText( tr( "Select on Map" ) );
116 mMapIdentificationButton->setCheckable( true );
117 editLayout->addWidget( mMapIdentificationButton );
118
119 // remove foreign key button
120 mRemoveFKButton = new QToolButton( this );
121 mRemoveFKButton->setIcon( QgsApplication::getThemeIcon( u"/mActionRemove.svg"_s ) );
122 mRemoveFKButton->setText( tr( "No Selection" ) );
123 editLayout->addWidget( mRemoveFKButton );
124
125 // add line to top layout
126 mTopLayout->addLayout( editLayout );
127
128 // embed form
129 mAttributeEditorFrame = new QgsCollapsibleGroupBox( this );
130 mAttributeEditorLayout = new QVBoxLayout( mAttributeEditorFrame );
131 mAttributeEditorFrame->setLayout( mAttributeEditorLayout );
132 mAttributeEditorFrame->setSizePolicy( mAttributeEditorFrame->sizePolicy().horizontalPolicy(), QSizePolicy::Expanding );
133 mTopLayout->addWidget( mAttributeEditorFrame );
134
135 // invalid label
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 );
143
144 // default mode is combobox, no geometric relation and no embed form
145 mMapIdentificationButton->hide();
146 mHighlightFeatureButton->hide();
147 mAttributeEditorFrame->hide();
148 mInvalidLabel->hide();
149 mAddEntryButton->hide();
150
151 // connect buttons
152 connect( mOpenFormButton, &QAbstractButton::clicked, this, &QgsRelationReferenceWidget::openForm );
153 connect( mHighlightFeatureButton, &QToolButton::triggered, this, &QgsRelationReferenceWidget::highlightActionTriggered );
154 connect( mMapIdentificationButton, &QAbstractButton::clicked, this, &QgsRelationReferenceWidget::mapIdentification );
155 connect( mRemoveFKButton, &QAbstractButton::clicked, this, &QgsRelationReferenceWidget::deleteForeignKeys );
156 connect( mAddEntryButton, &QAbstractButton::clicked, this, &QgsRelationReferenceWidget::addEntry );
157 connect( mComboBox, &QComboBox::editTextChanged, this, &QgsRelationReferenceWidget::updateAddEntryButton );
158}
159
161{
162 deleteHighlight();
163 unsetMapTool();
164}
165
167{
168 mAllowNull = allowNullValue;
169 mRemoveFKButton->setVisible( allowNullValue && mReadOnlySelector );
170
171 if ( relation.isValid() )
172 {
173 mReferencedLayerId = relation.referencedLayerId();
174 mReferencedLayerName = relation.referencedLayer()->name();
175 setReferencedLayerDataSource( relation.referencedLayer()->publicSource() );
176 mReferencedLayerProviderKey = relation.referencedLayer()->providerType();
177 mInvalidLabel->hide();
178
179 mRelation = relation;
180 mReferencingLayer = relation.referencingLayer();
181 mReferencedLayer = relation.referencedLayer();
182
183 const QList<QgsRelation::FieldPair> fieldPairs = relation.fieldPairs();
184 for ( const QgsRelation::FieldPair &fieldPair : fieldPairs )
185 {
186 mReferencedFields << fieldPair.referencedField();
187 }
188 if ( mComboBox )
189 {
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 );
197 }
198 mAttributeEditorFrame->setObjectName( u"referencing/"_s + relation.name() );
199
200 if ( mEmbedForm )
201 {
203 mAttributeEditorFrame->setTitle( mReferencedLayer->name() );
204 mReferencedAttributeForm = new QgsAttributeForm( relation.referencedLayer(), QgsFeature(), context, this );
205 mAttributeEditorLayout->addWidget( mReferencedAttributeForm );
206 }
207
208 connect( mReferencedLayer, &QgsVectorLayer::editingStarted, this, &QgsRelationReferenceWidget::updateAddEntryButton );
209 connect( mReferencedLayer, &QgsVectorLayer::editingStopped, this, &QgsRelationReferenceWidget::updateAddEntryButton );
210 updateAddEntryButton();
211 }
212 else
213 {
214 mInvalidLabel->show();
215 }
216
217 if ( mShown && isVisible() )
218 {
219 init();
220 }
221}
222
224{
225 if ( !editable )
226 {
227 unsetMapTool();
228 }
229
230 mFilterContainer->setEnabled( editable );
231 mComboBox->setEnabled( editable && !mReadOnlySelector );
232 mComboBox->setEditable( true );
233 mMapIdentificationButton->setEnabled( editable );
234 mRemoveFKButton->setEnabled( editable );
235 mIsEditable = editable;
236}
237
238void QgsRelationReferenceWidget::setForeignKey( const QVariant &value )
239{
240 setForeignKeys( QVariantList() << value );
241}
242
243void QgsRelationReferenceWidget::setForeignKeys( const QVariantList &values )
244{
245 if ( values.isEmpty() )
246 {
247 return;
248 }
249 if ( qVariantListIsNull( values ) )
250 {
252 return;
253 }
254
255 if ( !mReferencedLayer )
256 return;
257
258 mComboBox->setIdentifierValues( values );
259
260 if ( mEmbedForm || mChainFilters )
261 {
262 QgsFeatureRequest request = mComboBox->currentFeatureRequest();
263 mReferencedLayer->getFeatures( request ).nextFeature( mFeature );
264 }
265 if ( mChainFilters )
266 {
267 QVariant nullValue = QgsApplication::nullRepresentation();
268 const int count = std::min( mFilterComboBoxes.size(), mFilterFields.size() );
269 for ( int i = 0; i < count; i++ )
270 {
271 QVariant v = mFeature.attribute( mFilterFields[i] );
272 QString f = QgsVariantUtils::isNull( v ) ? nullValue.toString() : v.toString();
273 mFilterComboBoxes.at( i )->setCurrentIndex( mFilterComboBoxes.at( i )->findText( f ) );
274 }
275 }
276
277 mRemoveFKButton->setEnabled( mIsEditable );
278 highlightFeature( mFeature ); // TODO : make this async
279 updateAttributeEditorFrame( mFeature );
280
281 emitForeignKeysChanged( foreignKeys() );
282}
283
285{
286 // deactivate filter comboboxes
287 if ( mChainFilters && !mFilterComboBoxes.isEmpty() )
288 {
289 QComboBox *cb = mFilterComboBoxes.first();
290 cb->setCurrentIndex( 0 );
291 disableChainedComboBoxes( cb );
292 }
293
294 mComboBox->setIdentifierValuesToNull();
295 mRemoveFKButton->setEnabled( false );
296 updateAttributeEditorFrame( QgsFeature() );
297
298 emitForeignKeysChanged( foreignKeys() );
299}
300
302{
303 if ( !mEmbedForm )
304 // if there is no embedded form, everything is fine anyway
305 return true;
306
307 return mReferencedAttributeForm->save();
308}
309
311{
312 QgsFeature f;
313 if ( mReferencedLayer )
314 {
315 mReferencedLayer->getFeatures( mComboBox->currentFeatureRequest() ).nextFeature( f );
316 }
317 return f;
318}
319
321{
322 whileBlocking( mComboBox )->setIdentifierValuesToNull();
323 mRemoveFKButton->setEnabled( false );
324 updateAttributeEditorFrame( QgsFeature() );
325}
326
328{
329 QVariantList fkeys;
330 if ( fkeys.isEmpty() )
331 return QgsVariantUtils::createNullVariant( QMetaType::Type::Int );
332 else
333 return fkeys.at( 0 );
334}
335
337{
338 return mComboBox->identifierValues();
339}
340
342{
343 mEditorContext = context;
344 mCanvas = canvas;
345 mMessageBar = messageBar;
346
347 mMapToolIdentify.reset( new QgsMapToolIdentifyFeature( mCanvas ) );
348 mMapToolIdentify->setButton( mMapIdentificationButton );
349
350 if ( mEditorContext.cadDockWidget() )
351 {
352 mMapToolDigitize.reset( new QgsMapToolDigitizeFeature( mCanvas, mEditorContext.cadDockWidget() ) );
353 mMapToolDigitize->setButton( mAddEntryButton );
354 updateAddEntryButton();
355 }
356}
357
359{
360 if ( display )
361 {
362 setSizePolicy( sizePolicy().horizontalPolicy(), QSizePolicy::MinimumExpanding );
363 mTopLayout->setAlignment( Qt::AlignTop );
364 }
365
366 mAttributeEditorFrame->setVisible( display );
367 mEmbedForm = display;
368}
369
371{
372 mComboBox->setEnabled( !readOnly );
373 mRemoveFKButton->setVisible( mAllowNull && readOnly );
374 mReadOnlySelector = readOnly;
375}
376
378{
379 mHighlightFeatureButton->setVisible( allowMapIdentification );
380 mMapIdentificationButton->setVisible( allowMapIdentification );
381 mAllowMapIdentification = allowMapIdentification;
382}
383
384void QgsRelationReferenceWidget::setFilterFields( const QStringList &filterFields )
385{
386 mFilterFields = filterFields;
387}
388
390{
391 mOpenFormButton->setVisible( openFormButtonVisible );
392 mOpenFormButtonVisible = openFormButtonVisible;
393}
394
399
400void QgsRelationReferenceWidget::setFilterExpression( const QString &expression )
401{
402 mFilterExpression = expression;
403}
404
406{
407 Q_UNUSED( e )
408
409 mShown = true;
410 if ( !mInitialized )
411 init();
412}
413
415{
416 if ( mReferencedLayer )
417 {
418 QApplication::setOverrideCursor( Qt::WaitCursor );
419
420 QSet<QString> requestedAttrs;
421
422 if ( !mFilterFields.isEmpty() )
423 {
424 for ( const QString &fieldName : std::as_const( mFilterFields ) )
425 {
426 int idx = mReferencedLayer->fields().lookupField( fieldName );
427
428 if ( idx == -1 )
429 continue;
430
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 ) );
437 QVariant nullValue = QgsApplication::nullRepresentation();
438 cb->addItem( nullValue.toString(), QgsVariantUtils::createNullVariant( mReferencedLayer->fields().at( idx ).type() ) );
439
440 std::sort( uniqueValues.begin(), uniqueValues.end(), qgsVariantLessThan );
441 const auto constUniqueValues = uniqueValues;
442 for ( const QVariant &v : constUniqueValues )
443 {
444 cb->addItem( v.toString(), v );
445 }
446
447 connect( cb, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsRelationReferenceWidget::filterChanged );
448
449 // Request this attribute for caching
450 requestedAttrs << fieldName;
451
452 mFilterLayout->addWidget( cb );
453 }
454
455 if ( mChainFilters )
456 {
457 QVariant nullValue = QgsApplication::nullRepresentation();
458
459 QgsFeature ft;
460 QgsFeatureIterator fit = mFilterExpression.isEmpty() ? mReferencedLayer->getFeatures() : mReferencedLayer->getFeatures( mFilterExpression );
461 while ( fit.nextFeature( ft ) )
462 {
463 const int count = std::min( mFilterComboBoxes.count(), mFilterFields.count() );
464 for ( int i = 0; i < count - 1; i++ )
465 {
466 QVariant cv = ft.attribute( mFilterFields.at( i ) );
467 QVariant nv = ft.attribute( mFilterFields.at( i + 1 ) );
468 QString cf = QgsVariantUtils::isNull( cv ) ? nullValue.toString() : cv.toString();
469 QString nf = QgsVariantUtils::isNull( nv ) ? nullValue.toString() : nv.toString();
470 mFilterCache[mFilterFields[i]][cf] << nf;
471 }
472 }
473
474 if ( !mFilterComboBoxes.isEmpty() )
475 {
476 QComboBox *cb = mFilterComboBoxes.first();
477 cb->setCurrentIndex( 0 );
478 disableChainedComboBoxes( cb );
479 }
480 }
481 }
482 else
483 {
484 mFilterContainer->hide();
485 }
486
487 mComboBox->setSourceLayer( mReferencedLayer );
488 mComboBox->setDisplayExpression( mReferencedLayer->displayExpression() );
489 mComboBox->setAllowNull( mAllowNull );
490 mComboBox->setIdentifierFields( mReferencedFields );
491 mComboBox->setFetchLimit( mFetchLimit );
492 mComboBox->setOrderExpression( mOrderExpression );
493 mComboBox->setSortOrder( mSortOrder );
494
495 if ( !mFilterExpression.isEmpty() )
496 mComboBox->setFilterExpression( mFilterExpression );
497
498 QVariant nullValue = QgsApplication::nullRepresentation();
499
500 if ( mChainFilters && mFeature.isValid() )
501 {
502 for ( int i = 0; i < mFilterFields.size(); i++ )
503 {
504 QVariant v = mFeature.attribute( mFilterFields[i] );
505 QString f = QgsVariantUtils::isNull( v ) ? nullValue.toString() : v.toString();
506 mFilterComboBoxes.at( i )->setCurrentIndex( mFilterComboBoxes.at( i )->findText( f ) );
507 }
508 }
509
510 // Only connect after iterating, to have only one iterator on the referenced table at once
511 connect( mComboBox, &QgsFeatureListComboBox::currentFeatureChanged, this, &QgsRelationReferenceWidget::comboReferenceChanged );
512 // To avoid wrongly signaling a foreign key change, handle model feature found state following feature gathering separately
513 connect( mComboBox, &QgsFeatureListComboBox::currentFeatureFoundChanged, this, &QgsRelationReferenceWidget::comboReferenceFoundChanged );
514
515 QApplication::restoreOverrideCursor();
516
517 mInitialized = true;
518 }
519}
520
521void QgsRelationReferenceWidget::highlightActionTriggered( QAction *action )
522{
523 if ( action == mHighlightFeatureAction )
524 {
525 highlightFeature();
526 }
527 else if ( action == mScaleHighlightFeatureAction )
528 {
529 highlightFeature( QgsFeature(), Scale );
530 }
531 else if ( action == mPanHighlightFeatureAction )
532 {
533 highlightFeature( QgsFeature(), Pan );
534 }
535}
536
538{
540
541 if ( !feat.isValid() )
542 return;
543
545 QgsAttributeDialog *attributeDialog = new QgsAttributeDialog( mReferencedLayer, new QgsFeature( feat ), true, this, true, context );
546 attributeDialog->show();
547}
548
549void QgsRelationReferenceWidget::highlightFeature( QgsFeature f, CanvasExtent canvasExtent )
550{
551 if ( !mCanvas )
552 return;
553
554 if ( !f.isValid() )
555 {
556 f = referencedFeature();
557 if ( !f.isValid() )
558 return;
559 }
560
561 if ( !f.hasGeometry() )
562 {
563 return;
564 }
565
566 QgsGeometry geom = f.geometry();
567
568 // scale or pan
569 if ( canvasExtent == Scale )
570 {
571 QgsRectangle featBBox = geom.boundingBox();
572 featBBox = mCanvas->mapSettings().layerToMapCoordinates( mReferencedLayer, featBBox );
573 QgsRectangle extent = mCanvas->extent();
574 if ( !extent.contains( featBBox ) )
575 {
576 extent.combineExtentWith( featBBox );
577 extent.scale( 1.1 );
578 mCanvas->setExtent( extent, true );
579 mCanvas->refresh();
580 }
581 }
582 else if ( canvasExtent == Pan )
583 {
584 QgsGeometry centroid = geom.centroid();
585 QgsPointXY center = centroid.asPoint();
586 center = mCanvas->mapSettings().layerToMapCoordinates( mReferencedLayer, center );
587 mCanvas->zoomByFactor( 1.0, &center ); // refresh is done in this method
588 }
589
590 // highlight
591 deleteHighlight();
592 mHighlight = new QgsHighlight( mCanvas, f, mReferencedLayer );
593 mHighlight->applyDefaultStyle();
594 mHighlight->show();
595
596 QTimer *timer = new QTimer( this );
597 timer->setSingleShot( true );
598 connect( timer, &QTimer::timeout, this, &QgsRelationReferenceWidget::deleteHighlight );
599 timer->start( 3000 );
600}
601
602void QgsRelationReferenceWidget::deleteHighlight()
603{
604 if ( mHighlight )
605 {
606 mHighlight->hide();
607 delete mHighlight;
608 }
609 mHighlight = nullptr;
610}
611
613{
614 if ( !mAllowMapIdentification || !mReferencedLayer )
615 return;
616
617 const QgsVectorLayerTools *tools = mEditorContext.vectorLayerTools();
618 if ( !tools )
619 return;
620 if ( !mCanvas )
621 return;
622
623 mMapToolIdentify->setLayer( mReferencedLayer );
624 setMapTool( mMapToolIdentify );
625
626 connect( mMapToolIdentify, qOverload<const QgsFeature &>( &QgsMapToolIdentifyFeature::featureIdentified ), this, &QgsRelationReferenceWidget::featureIdentified );
627
628 if ( mMessageBar )
629 {
630 QString title = tr( "Relation %1 for %2." ).arg( mRelation.name(), mReferencingLayer->name() );
631 QString msg = tr( "Identify a feature of %1 to be associated. Press &lt;ESC&gt; to cancel." ).arg( mReferencedLayer->name() );
632 mMessageBarItem = QgsMessageBar::createMessage( title, msg, this );
633 mMessageBar->pushItem( mMessageBarItem );
634 }
635}
636
637void QgsRelationReferenceWidget::comboReferenceChanged()
638{
639 mReferencedLayer->getFeatures( mComboBox->currentFeatureRequest() ).nextFeature( mFeature );
640 highlightFeature( mFeature );
641 updateAttributeEditorFrame( mFeature );
642
643 emitForeignKeysChanged( mComboBox->identifierValues() );
644}
645
646void QgsRelationReferenceWidget::comboReferenceFoundChanged( bool )
647{
648 mReferencedLayer->getFeatures( mComboBox->currentFeatureRequest() ).nextFeature( mFeature );
649 highlightFeature( mFeature );
650 updateAttributeEditorFrame( mFeature );
651}
652
653void QgsRelationReferenceWidget::updateAttributeEditorFrame( const QgsFeature &feature )
654{
655 mOpenFormButton->setEnabled( feature.isValid() );
656 // Check if we're running with an embedded frame we need to update
657 if ( mAttributeEditorFrame && mReferencedAttributeForm )
658 {
659 mReferencedAttributeForm->setFeature( feature );
660 }
661}
662
664{
665 return mAllowAddFeatures;
666}
667
669{
670 mAllowAddFeatures = allowAddFeatures;
671 updateAddEntryButton();
672}
673
675{
676 return mRelation;
677}
678
679void QgsRelationReferenceWidget::featureIdentified( const QgsFeature &feature )
680{
681 mComboBox->setCurrentFeature( feature );
682 mFeature = feature;
683
684 mRemoveFKButton->setEnabled( mIsEditable );
685 highlightFeature( feature );
686 updateAttributeEditorFrame( feature );
687 emitForeignKeysChanged( foreignKeys(), true );
688
689 unsetMapTool();
690}
691
692void QgsRelationReferenceWidget::setMapTool( QgsMapTool *mapTool )
693{
694 mCurrentMapTool = mapTool;
695 mCanvas->setMapTool( mapTool );
696
697 mWindowWidget = window();
698
699 mCanvas->window()->raise();
700 mCanvas->activateWindow();
701 mCanvas->setFocus();
702 connect( mapTool, &QgsMapTool::deactivated, this, &QgsRelationReferenceWidget::mapToolDeactivated );
703}
704
705void QgsRelationReferenceWidget::unsetMapTool()
706{
707 // deactivate map tools if activated
708 if ( mCurrentMapTool )
709 {
710 /* this will call mapToolDeactivated */
711 mCanvas->unsetMapTool( mCurrentMapTool );
712
713 if ( mCurrentMapTool == mMapToolDigitize )
714 {
715 disconnect( mCanvas, &QgsMapCanvas::keyPressed, this, &QgsRelationReferenceWidget::onKeyPressed );
716 disconnect( mMapToolDigitize, &QgsMapToolDigitizeFeature::digitizingCompleted, this, &QgsRelationReferenceWidget::entryAdded );
717 }
718 else
719 {
720 disconnect( mMapToolIdentify, qOverload<const QgsFeature &>( &QgsMapToolIdentifyFeature::featureIdentified ), this, &QgsRelationReferenceWidget::featureIdentified );
721 }
722 }
723}
724
725void QgsRelationReferenceWidget::onKeyPressed( QKeyEvent *e )
726{
727 if ( e->key() == Qt::Key_Escape )
728 {
729 unsetMapTool();
730 }
731}
732
733void QgsRelationReferenceWidget::mapToolDeactivated()
734{
735 if ( mWindowWidget )
736 {
737 mWindowWidget->raise();
738 mWindowWidget->activateWindow();
739 }
740
741 if ( mMessageBar && mMessageBarItem )
742 {
743 mMessageBar->popWidget( mMessageBarItem );
744 }
745 mMessageBarItem = nullptr;
746}
747
748void QgsRelationReferenceWidget::filterChanged()
749{
750 QVariant nullValue = QgsApplication::nullRepresentation();
751
752 QMap<QString, QString> filters;
753 QgsAttributeList attrs;
754
755 QComboBox *scb = qobject_cast<QComboBox *>( sender() );
756
757 Q_ASSERT( scb );
758
759 QgsFeature f;
760 QgsFeatureIds featureIds;
761 QString filterExpression = mFilterExpression;
762
763 // wrap the expression with parentheses as it might contain `OR`
764 if ( !filterExpression.isEmpty() )
765 filterExpression = u" ( %1 ) "_s.arg( filterExpression );
766
767 // comboboxes have to be disabled before building filters
768 if ( mChainFilters )
769 disableChainedComboBoxes( scb );
770
771 // build filters
772 const auto constMFilterComboBoxes = mFilterComboBoxes;
773 for ( QComboBox *cb : constMFilterComboBoxes )
774 {
775 if ( cb->currentIndex() != 0 )
776 {
777 const QString fieldName = cb->property( "Field" ).toString();
778
779 if ( cb->currentText() == nullValue.toString() )
780 {
781 filters[fieldName] = u"\"%1\" IS NULL"_s.arg( fieldName );
782 }
783 else
784 {
785 filters[fieldName] = QgsExpression::createFieldEqualityExpression( fieldName, cb->currentText() );
786 }
787 attrs << mReferencedLayer->fields().lookupField( fieldName );
788 }
789 }
790
791 if ( mChainFilters )
792 {
793 QComboBox *ccb = nullptr;
794 const auto constMFilterComboBoxes = mFilterComboBoxes;
795 for ( QComboBox *cb : constMFilterComboBoxes )
796 {
797 if ( !ccb )
798 {
799 if ( cb == scb )
800 ccb = cb;
801
802 continue;
803 }
804
805 if ( ccb->currentIndex() != 0 )
806 {
807 const QString fieldName = cb->property( "Field" ).toString();
808
809 cb->blockSignals( true );
810 cb->clear();
811 cb->addItem( cb->property( "FieldAlias" ).toString() );
812
813 // ccb = scb
814 // cb = scb + 1
815 QStringList texts;
816 const auto txts { mFilterCache[ccb->property( "Field" ).toString()][ccb->currentText()] };
817 for ( const QString &txt : txts )
818 {
819 QMap<QString, QString> filtersAttrs = filters;
820 filtersAttrs[fieldName] = QgsExpression::createFieldEqualityExpression( fieldName, txt );
821 QgsAttributeList subset = attrs;
822
823 QString expression = filterExpression;
824 if ( !expression.isEmpty() && !filtersAttrs.isEmpty() )
825 expression += " AND "_L1;
826
827 expression += filtersAttrs.isEmpty() ? QString() : u" ( "_s;
828 expression += qgsMapJoinValues( filtersAttrs, " AND "_L1 );
829 expression += filtersAttrs.isEmpty() ? QString() : u" ) "_s;
830
831 subset << mReferencedLayer->fields().lookupField( fieldName );
832
833 QgsFeatureIterator it( mReferencedLayer->getFeatures( QgsFeatureRequest().setFilterExpression( expression ).setSubsetOfAttributes( subset ) ) );
834
835 bool found = false;
836 while ( it.nextFeature( f ) )
837 {
838 if ( !featureIds.contains( f.id() ) )
839 featureIds << f.id();
840
841 found = true;
842 }
843
844 // item is only provided if at least 1 feature exists
845 if ( found )
846 texts << txt;
847 }
848
849 texts.sort();
850 cb->addItems( texts );
851
852 cb->setEnabled( true );
853 cb->blockSignals( false );
854
855 ccb = cb;
856 }
857 }
858 }
859
860 if ( !filterExpression.isEmpty() && !filters.isEmpty() )
861 filterExpression += " AND "_L1;
862
863 filterExpression += filters.isEmpty() ? QString() : u" ( "_s;
864 filterExpression += qgsMapJoinValues( filters, " AND "_L1 );
865 filterExpression += filters.isEmpty() ? QString() : u" ) "_s;
866
867 mComboBox->setFilterExpression( filterExpression );
868}
869
870void QgsRelationReferenceWidget::addEntry()
871{
872 if ( !mReferencedLayer )
873 return;
874
875 const QgsVectorLayerTools *tools = mEditorContext.vectorLayerTools();
876 if ( !tools )
877 return;
878 if ( !mCanvas )
879 return;
880
881 // no geometry, skip the digitizing
882 if ( mReferencedLayer->geometryType() == Qgis::GeometryType::Unknown || mReferencedLayer->geometryType() == Qgis::GeometryType::Null )
883 {
884 QgsFeature f( mReferencedLayer->fields() );
885 entryAdded( f );
886 return;
887 }
888
889 mMapToolDigitize->setLayer( mReferencedLayer );
890 setMapTool( mMapToolDigitize );
891
892 connect( mMapToolDigitize, &QgsMapToolDigitizeFeature::digitizingCompleted, this, &QgsRelationReferenceWidget::entryAdded );
893 connect( mCanvas, &QgsMapCanvas::keyPressed, this, &QgsRelationReferenceWidget::onKeyPressed );
894
895 if ( mMessageBar )
896 {
897 QString title = tr( "Relation %1 for %2." ).arg( mRelation.name(), mReferencingLayer->name() );
898
899 QString displayString = QgsVectorLayerUtils::getFeatureDisplayString( mReferencingLayer, mComboBox->formFeature() );
900 QString msg
901 = tr( "Link feature to %1 \"%2\" : Digitize the geometry for the new feature on layer %3. Press &lt;ESC&gt; to cancel." ).arg( mReferencingLayer->name(), displayString, mReferencedLayer->name() );
902 mMessageBarItem = QgsMessageBar::createMessage( title, msg, this );
903 mMessageBar->pushItem( mMessageBarItem );
904 }
905}
906
907void QgsRelationReferenceWidget::entryAdded( const QgsFeature &feat )
908{
909 QgsFeature f( feat );
910 QgsAttributeMap attributes;
911
912 // if custom text is in the combobox and the displayExpression is simply a field, use the current text for the new feature
913 if ( mComboBox->itemText( mComboBox->currentIndex() ) != mComboBox->currentText() )
914 {
915 int fieldIdx = mReferencedLayer->fields().lookupField( mReferencedLayer->displayExpression() );
916
917 if ( fieldIdx != -1 )
918 {
919 attributes.insert( fieldIdx, mComboBox->currentText() );
920 }
921 }
922
923 if ( mEditorContext.vectorLayerTools()->addFeature( mReferencedLayer, attributes, f.geometry(), &f, this, false, true ) )
924 {
925 QVariantList attrs;
926 for ( const QString &fieldName : std::as_const( mReferencedFields ) )
927 attrs << f.attribute( fieldName );
928
929 setForeignKeys( attrs );
930
931 mAddEntryButton->setEnabled( false );
932 }
933
934 unsetMapTool();
935}
936
937void QgsRelationReferenceWidget::updateAddEntryButton()
938{
939 mAddEntryButton->setVisible( mAllowAddFeatures && mMapToolDigitize );
940 mAddEntryButton->setEnabled( mReferencedLayer && mReferencedLayer->isEditable() );
941}
942
943void QgsRelationReferenceWidget::disableChainedComboBoxes( const QComboBox *scb )
944{
945 QComboBox *ccb = nullptr;
946 const auto constMFilterComboBoxes = mFilterComboBoxes;
947 for ( QComboBox *cb : constMFilterComboBoxes )
948 {
949 if ( !ccb )
950 {
951 if ( cb == scb )
952 {
953 ccb = cb;
954 }
955
956 continue;
957 }
958
959 cb->setCurrentIndex( 0 );
960 if ( ccb->currentIndex() == 0 )
961 {
962 cb->setEnabled( false );
963 }
964
965 ccb = cb;
966 }
967}
968
969void QgsRelationReferenceWidget::emitForeignKeysChanged( const QVariantList &foreignKeys, bool force )
970{
971 if ( foreignKeys == mForeignKeys && force == false && qVariantListIsNull( foreignKeys ) == qVariantListIsNull( mForeignKeys ) )
972 return;
973
974 mForeignKeys = foreignKeys;
976 emit foreignKeyChanged( foreignKeys.at( 0 ) );
979}
980
982{
983 return mReferencedLayerName;
984}
985
986void QgsRelationReferenceWidget::setReferencedLayerName( const QString &relationLayerName )
987{
988 mReferencedLayerName = relationLayerName;
989}
990
992{
993 return mReferencedLayerId;
994}
995
996void QgsRelationReferenceWidget::setReferencedLayerId( const QString &relationLayerId )
997{
998 mReferencedLayerId = relationLayerId;
999}
1000
1002{
1003 return mReferencedLayerProviderKey;
1004}
1005
1006void QgsRelationReferenceWidget::setReferencedLayerProviderKey( const QString &relationProviderKey )
1007{
1008 mReferencedLayerProviderKey = relationProviderKey;
1009}
1010
1012{
1013 return mReferencedLayerDataSource;
1014}
1015
1016void QgsRelationReferenceWidget::setReferencedLayerDataSource( const QString &relationDataSource )
1017{
1018 const QgsPathResolver resolver { QgsProject::instance()->pathResolver() };
1019 mReferencedLayerDataSource = resolver.writePath( relationDataSource );
1020}
1021
1023{
1024 mComboBox->setFormFeature( formFeature );
1025}
1026
1028{
1029 mComboBox->setParentFormFeature( parentFormFeature );
1030}
@ Unknown
Unknown types.
Definition qgis.h:383
@ Null
No geometry.
Definition qgis.h:384
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.
The attribute form widget for vector layer features.
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.
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...
Definition qgsfeature.h:60
QgsFeatureId id
Definition qgsfeature.h:68
QgsGeometry geometry
Definition qgsfeature.h:71
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.
This tool digitizes geometry of new point/line/polygon features on already existing vector layers.
void digitizingCompleted(const QgsFeature &feature)
Emitted whenever the digitizing has been successfully completed.
A map tool to identify a feature on a chosen layer.
void featureIdentified(const QgsFeature &feature)
Emitted when a feature has been identified.
Abstract base class for all map tools.
Definition qgsmaptool.h:72
void deactivated()
Emitted when the map tool is deactivated.
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.
void showEvent(QShowEvent *e) override
bool allowMapIdentification() const
determines if the widget offers the possibility to select the related feature on the map (using a ded...
void setFilterExpression(const QString &filterExpression)
If not empty, will be used as filter expression.
QString filterExpression() const
Returns the currently set filter expression.
void setReferencedLayerProviderKey(const QString &referencedLayerProviderKey)
Set the data provider key of the referenced layer to referencedLayerProviderKey.
QString referencedLayerDataSource() const
Returns the public data source of the referenced layer.
bool allowAddFeatures() const
Determines if a button for adding new features should be shown.
Q_DECL_DEPRECATED void setForeignKey(const QVariant &value)
this sets the related feature using from the foreign key
QString referencedLayerProviderKey() const
Returns the data provider key of the referenced layer.
void setChainFilters(bool chainFilters)
Set if filters are chained.
QString referencedLayerId() const
Returns the id of the referenced layer.
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.
bool saveReferencedAttributeForm()
Trigger save of the embedded referenced attribute form.
void showIndeterminateState()
Sets the widget to display in an indeterminate "mixed value" state.
void openForm()
open the form of the related feature in a new dialog
void setReferencedLayerDataSource(const QString &referencedLayerDataSource)
Set the public data source of the referenced layer to referencedLayerDataSource.
void setParentFormFeature(const QgsFeature &parentFormFeature)
Set the current parent form feature.
void setFilterFields(const QStringList &filterFields)
Sets the fields for which filter comboboxes will be created.
void setAllowMapIdentification(bool allowMapIdentification)
Q_DECL_DEPRECATED void foreignKeyChanged(const QVariant &key)
Emitted when the foreign key changed.
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.
bool chainFilters() const
Determines if the filters are chained.
QVariantList foreignKeys() const
returns the related feature foreign key
void setForeignKeys(const QVariantList &values)
Sets the related feature using the foreign keys.
Q_DECL_DEPRECATED QVariant foreignKey() const
returns the related feature foreign key
void foreignKeysChanged(const QVariantList &keys)
Emitted when the foreign keys changed.
void setRelation(const QgsRelation &relation, bool allowNullValue)
void setOpenFormButtonVisible(bool openFormButtonVisible)
QgsFeature referencedFeature() const
Returns the related feature (from the referenced layer) if no feature is related, it returns an inval...
void mapIdentification()
activate the map tool to select a new related feature on the map
void setAllowAddFeatures(bool allowAddFeatures)
Determines if a button for adding new features should be shown.
void deleteForeignKeys()
unset the currently related feature
QString referencedLayerName() const
Returns the name of the referenced layer.
void setFormFeature(const QgsFeature &formFeature)
Set the current form feature (from the referencing layer).
Defines a relation between matching fields of the two involved tables of a relation.
Definition qgsrelation.h:71
Represents a relationship between two vector layers.
Definition qgsrelation.h:42
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.
Used to handle basic editing operations on vector layers.
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.
Definition qgis.cpp:596
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:7504
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.
Definition qgis.h:7046
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:7503
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
Definition qgis.h:6880
QMap< int, QVariant > QgsAttributeMap
QSet< QgsFeatureId > QgsFeatureIds
QList< int > QgsAttributeList
Definition qgsfield.h:30
bool qVariantListIsNull(const QVariantList &list)