34#include <QStringListModel>
41#include <nlohmann/json.hpp>
42using namespace nlohmann;
45QgsFilteredTableWidget::QgsFilteredTableWidget( QWidget *parent,
bool showSearch )
49 mSearchWidget->setShowSearchIcon(
true );
50 mSearchWidget->setShowClearButton(
true );
51 mTableWidget =
new QTableWidget(
this );
52 mTableWidget->horizontalHeader()->setSectionResizeMode( QHeaderView::Stretch );
53 mTableWidget->horizontalHeader()->setVisible(
false );
54 mTableWidget->verticalHeader()->setSectionResizeMode( QHeaderView::Stretch );
55 mTableWidget->verticalHeader()->setVisible(
false );
56 mTableWidget->setShowGrid(
false );
57 mTableWidget->setEditTriggers( QAbstractItemView::NoEditTriggers );
58 mTableWidget->setSelectionMode( QAbstractItemView::NoSelection );
59 QVBoxLayout *layout =
new QVBoxLayout();
60 layout->addWidget( mSearchWidget );
61 layout->addWidget( mTableWidget );
62 layout->setContentsMargins( 0, 0, 0, 0 );
63 layout->setSpacing( 0 );
66 mTableWidget->setFocusProxy( mSearchWidget );
67 connect( mSearchWidget, &QgsFilterLineEdit::textChanged,
this, &QgsFilteredTableWidget::filterStringChanged );
68 installEventFilter(
this );
72 mSearchWidget->setVisible(
false );
75 connect( mTableWidget, &QTableWidget::itemChanged,
this, &QgsFilteredTableWidget::itemChanged_p );
78bool QgsFilteredTableWidget::eventFilter( QObject *watched, QEvent *event )
81 if ( event->type() == QEvent::KeyPress )
83 QKeyEvent *keyEvent =
static_cast<QKeyEvent *
>( event );
84 if ( keyEvent->key() == Qt::Key_Escape &&
85 !mSearchWidget->text().isEmpty() )
87 mSearchWidget->clear();
94void QgsFilteredTableWidget::filterStringChanged(
const QString &filterString )
96 auto signalBlockedTableWidget =
whileBlocking( mTableWidget );
97 Q_UNUSED( signalBlockedTableWidget )
98 mTableWidget->clearContents();
99 const int rCount = std::max( 1, (
int ) std::ceil( (
float ) mCache.count() / (
float ) mColumnCount ) );
100 mTableWidget->setRowCount( rCount );
104 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
106 if ( column == mColumnCount )
111 if ( pair.first.value.contains( filterString, Qt::CaseInsensitive ) )
113 QTableWidgetItem *item =
nullptr;
114 item =
new QTableWidgetItem( pair.first.value );
115 item->setData( Qt::UserRole, pair.first.key );
116 item->setData( Qt::ToolTipRole, pair.first.description );
117 item->setCheckState( pair.second );
118 item->setFlags( mEnabledTable ? item->flags() | Qt::ItemIsEnabled : item->flags() & ~Qt::ItemIsEnabled );
119 mTableWidget->setItem( row, column, item );
123 mTableWidget->setRowCount( row + 1 );
126QStringList QgsFilteredTableWidget::selection()
const
129 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
131 if ( pair.second == Qt::Checked )
132 sel.append( pair.first.key.toString() );
137void QgsFilteredTableWidget::checkItems(
const QStringList &checked )
139 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
141 const bool isChecked = checked.contains( pair.first.key.toString() );
142 pair.second = isChecked ? Qt::Checked : Qt::Unchecked;
145 filterStringChanged( mSearchWidget->text() );
153 mCache.append( qMakePair( element, Qt::Unchecked ) );
155 filterStringChanged( mSearchWidget->text() );
158void QgsFilteredTableWidget::setIndeterminateState()
160 for (
int j = 0; j < mTableWidget->rowCount(); j++ )
162 for (
int i = 0; i < mColumnCount; ++i )
164 whileBlocking( mTableWidget )->item( j, i )->setCheckState( Qt::PartiallyChecked );
169void QgsFilteredTableWidget::setEnabledTable(
const bool enabled )
171 if ( mEnabledTable == enabled )
174 mEnabledTable = enabled;
176 mSearchWidget->clear();
178 filterStringChanged( mSearchWidget->text() );
181void QgsFilteredTableWidget::setColumnCount(
const int count )
183 mColumnCount = count;
184 mTableWidget->setColumnCount( count );
187void QgsFilteredTableWidget::itemChanged_p( QTableWidgetItem *item )
189 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
191 if ( pair.first.key == item->data( Qt::UserRole ) )
192 pair.second = item->checkState();
194 emit itemChanged( item );
210 int cbxIdx = mComboBox->currentIndex();
213 v = mComboBox->currentData();
215 v = QVariant(
field().type() );
218 else if ( mTableWidget )
220 QStringList selection = mTableWidget->selection();
223 if ( selection.isEmpty() && !
config( QStringLiteral(
"AllowNull" ) ).toBool( ) )
225 return QVariant( QVariant::Type::List );
230 for (
const QString &s : std::as_const( selection ) )
233 const QVariant::Type type { fkType() };
236 case QVariant::Type::Int:
237 vl.push_back( s.toInt() );
239 case QVariant::Type::LongLong:
240 vl.push_back( s.toLongLong() );
248 if (
layer()->fields().at(
fieldIdx() ).type() == QVariant::Map ||
249 layer()->fields().at(
fieldIdx() ).type() == QVariant::List )
259 else if ( mLineEdit )
263 if ( item.value == mLineEdit->text() )
280 mExpression =
config().value( QStringLiteral(
"FilterExpression" ) ).toString();
282 const bool allowMulti =
config( QStringLiteral(
"AllowMulti" ) ).toBool();
283 const bool useCompleter =
config( QStringLiteral(
"UseCompleter" ) ).toBool();
286 return new QgsFilteredTableWidget( parent, useCompleter );
288 else if ( useCompleter )
294 QComboBox *combo =
new QComboBox( parent );
295 combo->setMinimumContentsLength( 1 );
296 combo->setSizeAdjustPolicy( QComboBox::SizeAdjustPolicy::AdjustToMinimumContentsLengthWithIcon );
304 mComboBox = qobject_cast<QComboBox *>( editor );
305 mTableWidget = qobject_cast<QgsFilteredTableWidget *>( editor );
306 mLineEdit = qobject_cast<QLineEdit *>( editor );
313 mComboBox->view()->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded );
314 connect( mComboBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
317 else if ( mTableWidget )
321 else if ( mLineEdit )
323 connect( mLineEdit, &QLineEdit::textChanged,
this, &QgsValueRelationWidgetWrapper::emitValueChangedInternal, Qt::UniqueConnection );
329 return mTableWidget || mLineEdit || mComboBox;
332void QgsValueRelationWidgetWrapper::updateValues(
const QVariant &value,
const QVariantList & )
336 QStringList checkList;
338 if (
layer()->fields().at(
fieldIdx() ).type() == QVariant::Map ||
339 layer()->fields().at(
fieldIdx() ).type() == QVariant::List )
341 checkList =
value.toStringList();
348 mTableWidget->checkItems( checkList );
350 else if ( mComboBox )
355 for (
int i = 0; i < mComboBox->count(); i++ )
357 QVariant v( mComboBox->itemData( i ) );
370 mComboBox->setCurrentIndex( -1 );
374 mComboBox->addItem(
value.toString().prepend(
'(' ).append(
')' ),
value );
375 mComboBox->setCurrentIndex( mComboBox->findData(
value ) );
380 mComboBox->setCurrentIndex( idx );
383 else if ( mLineEdit )
386 bool wasFound {
false };
389 if ( i.key ==
value )
391 mLineEdit->setText( i.value );
399 mLineEdit->setText( tr(
"(no selection)" ) );
408 if ( attributeChanged )
410 QVariant oldValue(
value( ) );
418 updateValues(
value( ) );
433 QString attributeName( formFields.
names().at(
fieldIdx() ) );
455 if (
context().attributeFormMode() != QgsAttributeEditorContext::Mode::MultiEditMode
457 && ! mCache.isEmpty()
458 && !
config( QStringLiteral(
"AllowNull" ) ).toBool( ) )
462 QTimer::singleShot( 0,
this, [
this ]
464 if ( ! mCache.isEmpty() )
466 updateValues( formFeature().attribute( fieldIdx() ).isValid() ? formFeature().attribute( fieldIdx() ) : mCache.at( 0 ).key );
472int QgsValueRelationWidgetWrapper::columnCount()
const
474 return std::max( 1,
config( QStringLiteral(
"NofColumns" ) ).toInt() );
478QVariant::Type QgsValueRelationWidgetWrapper::fkType()
const
487 return fields.
at( idx ).
type();
490 return QVariant::Type::Invalid;
493void QgsValueRelationWidgetWrapper::populate( )
499 if (
context().parentFormFeature().isValid() )
508 else if ( mCache.empty() )
516 if (
config( QStringLiteral(
"AllowNull" ) ).toBool( ) )
518 whileBlocking( mComboBox )->addItem( tr(
"(no selection)" ), QVariant(
field().type( ) ) );
523 whileBlocking( mComboBox )->addItem( element.value, element.key );
524 if ( !element.description.isEmpty() )
525 mComboBox->setItemData( mComboBox->count() - 1, element.description, Qt::ToolTipRole );
529 else if ( mTableWidget )
531 mTableWidget->setColumnCount( columnCount() );
532 mTableWidget->populate( mCache );
534 else if ( mLineEdit )
537 values.reserve( mCache.size() );
542 QStringListModel *m =
new QStringListModel( values, mLineEdit );
543 QCompleter *completer =
new QCompleter( m, mLineEdit );
544 completer->setCaseSensitivity( Qt::CaseInsensitive );
545 mLineEdit->setCompleter( completer );
553 mTableWidget->setIndeterminateState();
555 else if ( mComboBox )
559 else if ( mLineEdit )
567 if ( mEnabled == enabled )
574 mTableWidget->setEnabledTable( enabled );
587 ctx.setParentFormFeature( feature );
592 && (
config( QStringLiteral(
"Value" ) ).toString() == attribute ||
593 config( QStringLiteral(
"Key" ) ).toString() == attribute ||
602void QgsValueRelationWidgetWrapper::emitValueChangedInternal(
const QString &value )
This class contains context information for attribute editor widgets.
QgsFeature parentFormFeature() const
Returns the feature of the currently edited parent form in its actual state.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Container of fields for a vector layer.
int count() const
Returns number of items.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QStringList names() const
Returns a list with field names.
QLineEdit subclass with built in support for clearing the widget's value and handling custom null val...
static QString buildArray(const QVariantList &list)
Build a postgres array like formatted list in a string from a QVariantList.
static QgsProject * instance()
Returns the QgsProject singleton instance.
static bool isNull(const QVariant &variant)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based data sets.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
bool qgsVariantEqual(const QVariant &lhs, const QVariant &rhs)
Compares two QVariant values and returns whether they are equal, two NULL values are always treated a...
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
QgsSignalBlocker< Object > whileBlocking(Object *object)
Temporarily blocks signals from a QObject while calling a single method from the object.