QGIS API Documentation  2.18.21-Las Palmas (9fba24a)
qgsvaluerelationwidgetwrapper.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvaluerelationwidgetwrapper.cpp
3  --------------------------------------
4  Date : 5.1.2014
5  Copyright : (C) 2014 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 "qgis.h"
19 #include "qgsfield.h"
20 #include "qgsmaplayerregistry.h"
22 #include "qgsvectorlayer.h"
23 #include "qgsfilterlineedit.h"
24 
25 #include <QStringListModel>
26 #include <QCompleter>
27 
30 {
31  return qgsVariantLessThan( p1.first, p2.first );
32 }
33 
36 {
37  return qgsVariantLessThan( p1.second, p2.second );
38 }
39 
41  : QgsEditorWidgetWrapper( vl, fieldIdx, editor, parent )
42  , mComboBox( nullptr )
43  , mListWidget( nullptr )
44  , mLineEdit( nullptr )
45  , mLayer( nullptr )
46  , mEnabled( false )
47 {
48 }
49 
50 
52 {
53  QVariant v;
54 
55  if ( mComboBox )
56  {
57  int cbxIdx = mComboBox->currentIndex();
58  if ( cbxIdx > -1 )
59  {
60  v = mComboBox->itemData( mComboBox->currentIndex() );
61  }
62  }
63 
64  if ( mListWidget )
65  {
66  QStringList selection;
67  for ( int i = 0; i < mListWidget->count(); ++i )
68  {
69  QListWidgetItem* item = mListWidget->item( i );
70  if ( item->checkState() == Qt::Checked )
71  selection << item->data( Qt::UserRole ).toString();
72  }
73 
74  v = selection.join( "," ).prepend( '{' ).append( '}' );
75  }
76 
77  if ( mLineEdit )
78  {
79  Q_FOREACH ( const ValueRelationItem& i , mCache )
80  {
81  if ( i.second == mLineEdit->text() )
82  {
83  v = i.first;
84  break;
85  }
86  }
87  }
88 
89  return v;
90 }
91 
93 {
94  if ( config( "AllowMulti" ).toBool() )
95  {
96  return new QListWidget( parent );
97  }
98  else if ( config( "UseCompleter" ).toBool() )
99  {
100  return new QgsFilterLineEdit( parent );
101  }
102  {
103  return new QComboBox( parent );
104  }
105 }
106 
108 {
109  mCache = createCache( config() );
110 
111  mComboBox = qobject_cast<QComboBox*>( editor );
112  mListWidget = qobject_cast<QListWidget*>( editor );
113  mLineEdit = qobject_cast<QLineEdit*>( editor );
114 
115  if ( mComboBox )
116  {
117  if ( config( "AllowNull" ).toBool() )
118  {
119  mComboBox->addItem( tr( "(no selection)" ), QVariant( field().type() ) );
120  }
121 
122  Q_FOREACH ( const ValueRelationItem& element, mCache )
123  {
124  mComboBox->addItem( element.second, element.first );
125  }
126 
127  connect( mComboBox, SIGNAL( currentIndexChanged( int ) ), this, SLOT( valueChanged() ) );
128  }
129  else if ( mListWidget )
130  {
131  Q_FOREACH ( const ValueRelationItem& element, mCache )
132  {
133  QListWidgetItem *item;
134  item = new QListWidgetItem( element.second );
135  item->setData( Qt::UserRole, element.first );
136 
137  mListWidget->addItem( item );
138  }
139  connect( mListWidget, SIGNAL( itemChanged( QListWidgetItem* ) ), this, SLOT( valueChanged() ) );
140  }
141  else if ( mLineEdit )
142  {
143  QStringList values;
144  Q_FOREACH ( const ValueRelationItem& i, mCache )
145  {
146  values << i.second;
147  }
148 
149  QStringListModel* m = new QStringListModel( values, mLineEdit );
150  QCompleter* completer = new QCompleter( m, mLineEdit );
151  completer->setCaseSensitivity( Qt::CaseInsensitive );
152  mLineEdit->setCompleter( completer );
153 
154  connect( mLineEdit, SIGNAL( textChanged( QString ) ), this, SLOT( onValueChanged() ) );
155  }
156 }
157 
159 {
160  return mListWidget || mLineEdit || mComboBox;
161 }
162 
164 {
165  if ( mListWidget )
166  {
167  QStringList checkList = value.toString().remove( QChar( '{' ) ).remove( QChar( '}' ) ).split( ',' );
168 
169  for ( int i = 0; i < mListWidget->count(); ++i )
170  {
171  QListWidgetItem* item = mListWidget->item( i );
172  item->setCheckState( checkList.contains( item->data( Qt::UserRole ).toString() ) ? Qt::Checked : Qt::Unchecked );
173  }
174  }
175  else if ( mComboBox )
176  {
177  mComboBox->setCurrentIndex( mComboBox->findData( value ) );
178  }
179  else if ( mLineEdit )
180  {
181  Q_FOREACH ( ValueRelationItem i, mCache )
182  {
183  if ( i.first == value )
184  {
185  mLineEdit->setText( i.second );
186  break;
187  }
188  }
189  }
190 }
191 
192 
194 {
195  ValueRelationCache cache;
196 
197  QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( QgsMapLayerRegistry::instance()->mapLayer( config.value( "Layer" ).toString() ) );
198 
199  if ( !layer )
200  return cache;
201 
202  int ki = layer->fieldNameIndex( config.value( "Key" ).toString() );
203  int vi = layer->fieldNameIndex( config.value( "Value" ).toString() );
204 
205  QgsFeatureRequest request;
206 
208  request.setSubsetOfAttributes( QgsAttributeList() << ki << vi );
209  if ( !config.value( "FilterExpression" ).toString().isEmpty() )
210  {
211  request.setFilterExpression( config.value( "FilterExpression" ).toString() );
212  }
213 
214  QgsFeatureIterator fit = layer->getFeatures( request );
215 
216  QgsFeature f;
217  while ( fit.nextFeature( f ) )
218  {
219  cache.append( ValueRelationItem( f.attribute( ki ), f.attribute( vi ).toString() ) );
220  }
221 
222  if ( config.value( "OrderByValue" ).toBool() )
223  {
224  qSort( cache.begin(), cache.end(), orderByValueLessThan );
225  }
226  else
227  {
228  qSort( cache.begin(), cache.end(), orderByKeyLessThan );
229  }
230 
231  return cache;
232 }
233 
235 {
236  if ( mListWidget )
237  {
238  mListWidget->blockSignals( true );
239  for ( int i = 0; i < mListWidget->count(); ++i )
240  {
241  mListWidget->item( i )->setCheckState( Qt::PartiallyChecked );
242  }
243  mListWidget->blockSignals( false );
244  }
245  else if ( mComboBox )
246  {
247  whileBlocking( mComboBox )->setCurrentIndex( -1 );
248  }
249  else if ( mLineEdit )
250  {
251  whileBlocking( mLineEdit )->clear();
252  }
253 }
254 
256 {
257  if ( mEnabled == enabled )
258  return;
259 
260  mEnabled = enabled;
261 
262  if ( mListWidget )
263  {
264  for ( int i = 0; i < mListWidget->count(); ++i )
265  {
266  QListWidgetItem *item = mListWidget->item( i );
267 
268  if ( enabled )
269  item->setFlags( item->flags() | Qt::ItemIsEnabled );
270  else
271  item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
272  }
273  }
274  else
276 }
Wrapper for iterator of features from vector data provider or vector layer.
void setCaseSensitivity(Qt::CaseSensitivity caseSensitivity)
QString & append(QChar ch)
Qt::CheckState checkState() const
void valueChanged()
Will call the value() method to determine the emitted value.
QgsField field() const
Access the field.
void showIndeterminateState() override
Sets the widget to display in an indeterminate "mixed value" state.
void append(const T &value)
iterator begin()
Manages an editor widget Widget and wrapper share the same parent.
QgsMapLayer * mapLayer(const QString &theLayerId) const
Retrieve a pointer to a registered layer by layer ID.
QStringList split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
QString & prepend(QChar ch)
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest())
Query the provider for features specified in request.
bool contains(const QString &str, Qt::CaseSensitivity cs) const
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
void setValue(const QVariant &value) override
virtual void setEnabled(bool enabled) override
Is used to enable or disable the edit functionality of the managed widget.
QString join(const QString &separator) const
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:187
QString & remove(int position, int n)
bool valid() const override
Return true if the widget has been properly initialized.
Qt::ItemFlags flags() const
QString tr(const char *sourceText, const char *disambiguation, int n)
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:269
void addItem(const QString &text, const QVariant &userData)
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
QVariantMap QgsEditorWidgetConfig
Holds a set of configuration parameters for a editor widget wrapper.
QPair< QVariant, QString > ValueRelationItem
void setFlags(QFlags< Qt::ItemFlag > flags)
void initWidget(QWidget *editor) override
This method should initialize the editor widget with runtime data.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
virtual QVariant data(int role) const
QList< int > QgsAttributeList
QLineEdit subclass with built in support for clearing the widget&#39;s value and handling custom null val...
QgsFeatureRequest & setFlags(const QgsFeatureRequest::Flags &flags)
Set flags that affect how features will be fetched.
void setCheckState(Qt::CheckState state)
QListWidgetItem * item(int row) const
QVariant itemData(int index, int role) const
bool blockSignals(bool block)
virtual void setData(int role, const QVariant &value)
void setEnabled(bool enabled) override
Is used to enable or disable the edit functionality of the managed widget.
static ValueRelationCache createCache(const QgsEditorWidgetConfig &config)
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.
Definition: qgis.h:333
static QgsMapLayerRegistry * instance()
Returns the instance pointer, creating the object on the first call.
int findData(const QVariant &data, int role, QFlags< Qt::MatchFlag > flags) const
QWidget * createWidget(QWidget *parent) override
This method should create a new widget with the provided parent.
static bool orderByValueLessThan(const QgsValueRelationWidgetWrapper::ValueRelationItem &p1, const QgsValueRelationWidgetWrapper::ValueRelationItem &p2)
QgsEditorWidgetConfig config() const
Returns the whole config.
int fieldIdx() const
Access the field index.
bool nextFeature(QgsFeature &f)
QgsVectorLayer * layer() const
Access the QgsVectorLayer, you are working on.
Geometry is not required. It may still be returned if e.g. required for a filter condition.
bool connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type)
QObject * parent() const
static bool orderByKeyLessThan(const QgsValueRelationWidgetWrapper::ValueRelationItem &p1, const QgsValueRelationWidgetWrapper::ValueRelationItem &p2)
Represents a vector layer which manages a vector based data sets.
QVariant attribute(const QString &name) const
Lookup attribute value from attribute name.
Definition: qgsfeature.cpp:271
QString toString() const
iterator end()
int fieldNameIndex(const QString &fieldName) const
Returns the index of a field name or -1 if the field does not exist.
QVariant value() const override
Will be used to access the widget&#39;s value.
QgsValueRelationWidgetWrapper(QgsVectorLayer *vl, int fieldIdx, QWidget *editor=nullptr, QWidget *parent=nullptr)