QGIS API Documentation 3.37.0-Master (fdefdf9c27f)
qgsfeaturelistcombobox.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsfeaturelistcombobox.cpp - QgsFeatureListComboBox
3 ---------------------
4 begin : 10.3.2017
5 copyright : (C) 2017 by Matthias Kuhn
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 ***************************************************************************/
16
18#include "qgsanimatedicon.h"
19#include "qgsfilterlineedit.h"
20#include "qgslogger.h"
21#include "qgsapplication.h"
22
23#include <QCompleter>
24#include <QLineEdit>
25#include <QKeyEvent>
26
28 : QComboBox( parent )
29 , mModel( new QgsFeatureFilterModel( this ) )
30 , mCompleter( new QCompleter( mModel ) )
31{
32 setMinimumContentsLength( 1 );
33 setSizeAdjustPolicy( QComboBox::SizeAdjustPolicy::AdjustToMinimumContentsLengthWithIcon );
34 mCompleter->setCaseSensitivity( Qt::CaseInsensitive );
35 mCompleter->setFilterMode( Qt::MatchContains );
36 setEditable( true );
37 setCompleter( mCompleter );
38 mCompleter->setWidget( this );
42 connect( mModel, &QgsFeatureFilterModel::isLoadingChanged, this, &QgsFeatureListComboBox::onLoadingChanged );
43 connect( mModel, &QgsFeatureFilterModel::filterJobCompleted, this, &QgsFeatureListComboBox::onFilterUpdateCompleted );
46 connect( mModel, &QgsFeatureFilterModel::extraIdentifierValueIndexChanged, this, &QgsFeatureListComboBox::setCurrentIndex );
48 connect( mCompleter, static_cast<void( QCompleter::* )( const QModelIndex & )>( &QCompleter::highlighted ), this, &QgsFeatureListComboBox::onItemSelected );
49 connect( mCompleter, static_cast<void( QCompleter::* )( const QModelIndex & )>( &QCompleter::activated ), this, &QgsFeatureListComboBox::onActivated );
50 connect( mModel, &QgsFeatureFilterModel::beginUpdate, this, &QgsFeatureListComboBox::storeLineEditState );
51 connect( mModel, &QgsFeatureFilterModel::endUpdate, this, &QgsFeatureListComboBox::restoreLineEditState );
53 connect( mModel, &QgsFeatureFilterModel::dataChanged, this, &QgsFeatureListComboBox::onDataChanged );
54
55 connect( this, static_cast<void( QgsFeatureListComboBox::* )( int )>( &QgsFeatureListComboBox::currentIndexChanged ), this, &QgsFeatureListComboBox::onCurrentIndexChanged );
56
57 mLineEdit = new QgsFilterLineEdit( nullptr, QgsApplication::nullRepresentation() );
58 mLineEdit->setSelectOnFocus( true );
59 mLineEdit->setShowClearButton( true );
60
61 setLineEdit( mLineEdit );
62 setModel( mModel );
63
64 connect( mLineEdit, &QgsFilterLineEdit::textEdited, this, &QgsFeatureListComboBox::onCurrentTextChanged );
65 connect( mLineEdit, &QgsFilterLineEdit::cleared, this, &QgsFeatureListComboBox::onFilterLineEditCleared );
66
68
69 setToolTip( tr( "Just start typing what you are looking for." ) );
70}
71
73{
74 return mModel->sourceLayer();
75}
76
78{
79 mModel->setSourceLayer( sourceLayer );
80}
81
83{
84 QVariantList values;
85 const QStringList fields = mModel->identifierFields();
86 for ( const QString &field : fields )
87 {
88 values << feature.attribute( field );
89 }
90 setIdentifierValues( values );
91}
92
94{
95 return mModel->displayExpression();
96}
97
98void QgsFeatureListComboBox::setDisplayExpression( const QString &expression )
99{
100 mModel->setDisplayExpression( expression );
101}
102
103void QgsFeatureListComboBox::onCurrentTextChanged( const QString &text )
104{
105 mIsCurrentlyEdited = true;
106 mPopupRequested = true;
107 mModel->setFilterValue( text );
108}
109
110void QgsFeatureListComboBox::onFilterLineEditCleared()
111{
112 // Reset the combobox when the search is cleared
113 const QString clearedValue = allowNull() ? mLineEdit->nullValue() : mLineEdit->defaultValue();
114 mModel->setFilterValue( clearedValue );
115}
116
117void QgsFeatureListComboBox::onFilterUpdateCompleted()
118{
119 if ( mPopupRequested )
120 mCompleter->complete();
121
122 mPopupRequested = false;
123}
124
125void QgsFeatureListComboBox::onLoadingChanged()
126{
127 mLineEdit->setShowSpinner( mModel->isLoading() );
128}
129
130void QgsFeatureListComboBox::onItemSelected( const QModelIndex &index )
131{
132 setCurrentIndex( index.row() );
133}
134
135void QgsFeatureListComboBox::onCurrentIndexChanged( int i )
136{
137 if ( !mLineEdit->hasStateStored() )
138 mIsCurrentlyEdited = false;
139 const QModelIndex modelIndex = mModel->index( i, 0, QModelIndex() );
140 mModel->setExtraIdentifierValues( mModel->data( modelIndex, static_cast< int >( QgsFeatureFilterModel::CustomRole::IdentifierValues ) ).toList() );
141 mLineEdit->setText( mModel->data( modelIndex, static_cast< int >( QgsFeatureFilterModel::CustomRole::Value ) ).toString() );
142 mLineEdit->setFont( mModel->data( modelIndex, Qt::FontRole ).value<QFont>() );
143 QPalette palette = mLineEdit->palette();
144 palette.setBrush( mLineEdit->foregroundRole(), mModel->data( modelIndex, Qt::ForegroundRole ).value<QBrush>() );
145 mLineEdit->setPalette( palette );
146}
147
148void QgsFeatureListComboBox::onActivated( QModelIndex modelIndex )
149{
150 setIdentifierValues( mModel->data( modelIndex, static_cast< int >( QgsFeatureFilterModel::CustomRole::IdentifierValues ) ).toList() );
151 mLineEdit->setText( mModel->data( modelIndex, static_cast< int >( QgsFeatureFilterModel::CustomRole::Value ) ).toString() );
152}
153
154void QgsFeatureListComboBox::storeLineEditState()
155{
156 if ( mIsCurrentlyEdited )
157 {
158 mLineEdit->storeState( );
159 }
160}
161
162void QgsFeatureListComboBox::restoreLineEditState()
163{
164 if ( mIsCurrentlyEdited )
165 {
166 mLineEdit->restoreState( );
167 }
168}
169
171{
172 int index = -1;
173
174 if ( allowNull() )
175 {
176 index = findText( QgsApplication::nullRepresentation( ) );
177 }
178
179 return index;
180}
181
182void QgsFeatureListComboBox::onDataChanged( const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles )
183{
184 Q_UNUSED( roles )
185 if ( !mIsCurrentlyEdited )
186 {
187 const int currentIndex = mModel->extraIdentifierValueIndex();
188 if ( currentIndex >= topLeft.row() && currentIndex <= bottomRight.row() )
189 {
190 const QModelIndex modelIndex = mModel->index( currentIndex, 0, QModelIndex() );
191 mLineEdit->setText( mModel->data( modelIndex, static_cast< int >( QgsFeatureFilterModel::CustomRole::Value ) ).toString() );
192 }
193 }
194}
195
197{
198 const QStringList list = mModel->identifierFields();
199 if ( list.isEmpty() )
200 return QString();
201 else
202 return list.at( 0 );
203}
204
206{
207 return mModel->identifierFields();
208}
209
210void QgsFeatureListComboBox::setIdentifierField( const QString &identifierField )
211{
212 mModel->setIdentifierFields( QStringList() << identifierField );
213}
214
215void QgsFeatureListComboBox::setIdentifierFields( const QStringList &identifierFields )
216{
218}
219
221{
222 return mModel->index( currentIndex(), 0, QModelIndex() );
223}
224
226{
227 Q_UNUSED( event )
228 QComboBox::focusOutEvent( event );
229 mLineEdit->setText( mModel->data( currentModelIndex(), static_cast< int >( QgsFeatureFilterModel::CustomRole::Value ) ).toString() );
230}
231
233{
234 if ( event->key() == Qt::Key_Escape )
235 {
236 mLineEdit->setText( mModel->data( currentModelIndex(), static_cast< int >( QgsFeatureFilterModel::CustomRole::Value ) ).toString() );
237 }
238 QComboBox::keyReleaseEvent( event );
239}
240
242{
243 return mModel->allowNull();
244}
245
247{
248 mModel->setAllowNull( allowNull );
250}
251
253{
254 return mModel->fetchLimit();
255}
256
258{
259 mModel->setFetchLimit( fetchLimit );
260}
261
263{
265 return mModel->extraIdentifierValues().value( 0 );
267}
268
270{
271 return mModel->extraIdentifierValues();
272}
273
274void QgsFeatureListComboBox::setIdentifierValue( const QVariant &identifierValue )
275{
276 setIdentifierValues( QVariantList() << identifierValue );
277}
278
279void QgsFeatureListComboBox::setIdentifierValues( const QVariantList &identifierValues )
280{
282}
283
285{
287}
288
290{
291 if ( mModel->extraIdentifierValues().isEmpty() )
292 {
293 return QgsFeatureRequest().setFilterFids( QgsFeatureIds() ); // NULL: Return a request that's guaranteed to not return anything
294 }
295 else
296 {
297 QStringList filtersAttrs;
298 const QStringList identifierFields = mModel->identifierFields();
299 const QVariantList values = mModel->extraIdentifierValues();
300 for ( int i = 0; i < identifierFields.count(); i++ )
301 {
302 if ( i >= values.count() )
303 {
304 filtersAttrs << QgsExpression::createFieldEqualityExpression( identifierFields.at( i ), QVariant() );
305 }
306 else
307 {
308 filtersAttrs << QgsExpression::createFieldEqualityExpression( identifierFields.at( i ), values.at( i ) );
309 }
310 }
311 const QString expression = filtersAttrs.join( QLatin1String( " AND " ) );
312 return QgsFeatureRequest().setFilterExpression( expression );
313 }
314}
315
317{
318 return mModel->filterExpression();
319}
320
321void QgsFeatureListComboBox::setFilterExpression( const QString &filterExpression )
322{
324}
static QString nullRepresentation()
This string is used to represent the value NULL throughout QGIS.
static QString createFieldEqualityExpression(const QString &fieldName, const QVariant &value, QVariant::Type fieldType=QVariant::Type::Invalid)
Create an expression allowing to evaluate if a field is equal to a value.
Provides a list of features based on filter conditions.
void setExtraIdentifierValues(const QVariantList &extraIdentifierValues)
Allows specifying one value that does not need to match the filter criteria but will still be availab...
void setExtraIdentifierValueToNull() override
Allows specifying one value that does not need to match the filter criteria but will still be availab...
QStringList identifierFields
A set of fields of sourceLayer that is unique and should be used to identify features.
QVariantList extraIdentifierValues
The values that identifies the current feature.
void identifierFieldsChanged()
The identifier field should be a unique field that can be used to identify individual features.
void setIdentifierFields(const QStringList &identifierFields)
The identifier field should be a unique field that can be used to identify individual features.
This offers a combobox with autocompleter that allows selecting features from a layer.
void setIdentifierValues(const QVariantList &identifierValues)
The identifier values of the currently selected feature.
void keyPressEvent(QKeyEvent *event) override
Q_DECL_DEPRECATED void setIdentifierField(const QString &identifierField)
Field name that will be used to uniquely identify the current feature.
void setDisplayExpression(const QString &displayExpression)
The display expression will be used to display features as well as the value to match the typed text ...
QModelIndex currentModelIndex() const
The index of the currently selected item.
void setFilterExpression(const QString &filterExpression)
An additional expression to further restrict the available features.
void setIdentifierFields(const QStringList &identifierFields)
Field name that will be used to uniquely identify the current feature.
void allowNullChanged()
Determines if a NULL value should be available in the list.
QgsFeatureListComboBox(QWidget *parent=nullptr)
Create a new QgsFeatureListComboBox, optionally specifying a parent.
void focusOutEvent(QFocusEvent *event) override
void setSourceLayer(QgsVectorLayer *sourceLayer)
The layer from which features should be listed.
void modelUpdated()
The underlying model has been updated.
QgsFeatureRequest currentFeatureRequest() const
Shorthand for getting a feature request to query the currently selected feature.
void setIdentifierValuesToNull()
Sets the identifier values of the currently selected feature to NULL value(s).
void identifierValueChanged()
The identifier value of the currently selected feature.
void sourceLayerChanged()
The layer from which features should be listed.
void setCurrentFeature(const QgsFeature &feature)
Sets the current index by using the given feature.
int nullIndex() const
Returns the current index of the NULL value, or -1 if NULL values are not allowed.
int fetchLimit() const
Returns the feature request fetch limit.
Q_DECL_DEPRECATED void setIdentifierValue(const QVariant &identifierValue)
The identifier value of the currently selected feature.
void currentFeatureChanged()
Emitted when the current feature changes.
QStringList identifierFields() const
Field name that will be used to uniquely identify the current feature.
void setAllowNull(bool allowNull)
Determines if a NULL value should be available in the list.
void displayExpressionChanged()
The display expression will be used to display features as well as the the value to match the typed t...
void identifierFieldChanged()
Field name that will be used to uniquely identify the current feature.
void setFetchLimit(int fetchLimit)
Defines the feature request fetch limit If set to 0, no limit is applied when fetching.
void filterExpressionChanged()
An additional expression to further restrict the available features.
void extraIdentifierValueIndexChanged(int index)
The index at which the extra identifier value is available within the model.
void beginUpdate()
Notification that the model is about to be changed because a job was completed.
void setFilterValue(const QString &filterValue)
This value will be used to filter the features available from this model.
void filterExpressionChanged()
An additional filter expression to apply, next to the filterValue.
void setFetchLimit(int fetchLimit)
Defines the feature request fetch limit If set to 0, no limit is applied when fetching.
void extraIdentifierValueChanged()
Allows specifying one value that does not need to match the filter criteria but will still be availab...
@ IdentifierValues
Used to retrieve the identifierValues (primary keys) of a feature.
@ Value
Used to retrieve the displayExpression of a feature.
void filterJobCompleted()
Indicates that a filter job has been completed and new data may be available.
void setAllowNull(bool allowNull)
Add a NULL entry to the list.
void setDisplayExpression(const QString &displayExpression)
The display expression will be used for.
bool isLoading() const
Indicator if the model is currently performing any feature iteration in the background.
QVariant data(const QModelIndex &index, int role) const override
QModelIndex index(int row, int column, const QModelIndex &parent) const override
void sourceLayerChanged()
The source layer from which features will be fetched.
void setFilterExpression(const QString &filterExpression)
An additional filter expression to apply, next to the filterValue.
void allowNullChanged()
Add a NULL entry to the list.
void currentFeatureChanged()
Emitted when the current feature in the model has changed This emitted both when the extra value chan...
void isLoadingChanged()
Indicator if the model is currently performing any feature iteration in the background.
void endUpdate()
Notification that the model change is finished.
void displayExpressionChanged()
The display expression will be used for.
void setSourceLayer(QgsVectorLayer *sourceLayer)
The source layer from which features will be fetched.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Definition: qgsfeature.cpp:335
QLineEdit subclass with built in support for clearing the widget's value and handling custom null val...
void restoreState()
Restores the current state of the line edit (selection and cursor position)
void storeState()
Stores the current state of the line edit (selection and cursor position)
@ ClearToNull
Reset value to null.
@ ClearToDefault
Reset value to default value (see defaultValue() )
void setShowClearButton(bool visible)
Sets whether the widget's clear button is visible.
bool hasStateStored() const
Returns if a state is already saved.
void setSelectOnFocus(bool selectOnFocus)
Will select all text when this widget receives the focus.
void cleared()
Emitted when the widget is cleared.
void setShowSpinner(bool showSpinner)
Show a spinner icon.
void setClearMode(ClearMode mode)
Sets the clear mode for the widget.
Represents a vector layer which manages a vector based data sets.
#define Q_NOWARN_DEPRECATED_POP
Definition: qgis.h:5776
#define Q_NOWARN_DEPRECATED_PUSH
Definition: qgis.h:5775
QSet< QgsFeatureId > QgsFeatureIds
Definition: qgsfeatureid.h:37