18#include <nlohmann/json.hpp>
35#include <QStandardItemModel>
36#include <QStringListModel>
40#include "moc_qgsvaluerelationwidgetwrapper.cpp"
42using namespace nlohmann;
45QgsFilteredTableWidget::QgsFilteredTableWidget( QWidget *parent,
bool showSearch,
bool displayGroupName )
47 , mDisplayGroupName( displayGroupName )
50 mSearchWidget->setShowSearchIcon(
true );
51 mSearchWidget->setShowClearButton(
true );
52 mTableWidget =
new QTableWidget(
this );
53 mTableWidget->horizontalHeader()->setSectionResizeMode( QHeaderView::Stretch );
54 mTableWidget->horizontalHeader()->setVisible(
false );
55 mTableWidget->verticalHeader()->setSectionResizeMode( QHeaderView::Stretch );
56 mTableWidget->verticalHeader()->setVisible(
false );
57 mTableWidget->setShowGrid(
false );
58 mTableWidget->setEditTriggers( QAbstractItemView::NoEditTriggers );
59 mTableWidget->setSelectionMode( QAbstractItemView::NoSelection );
60 mTableWidget->setContextMenuPolicy( Qt::CustomContextMenu );
62 QVBoxLayout *layout =
new QVBoxLayout();
63 layout->addWidget( mSearchWidget );
64 layout->addWidget( mTableWidget );
65 layout->setContentsMargins( 0, 0, 0, 0 );
66 layout->setSpacing( 0 );
69 mTableWidget->setFocusProxy( mSearchWidget );
70 connect( mSearchWidget, &QgsFilterLineEdit::textChanged,
this, &QgsFilteredTableWidget::filterStringChanged );
71 installEventFilter(
this );
75 mSearchWidget->setVisible(
false );
78 connect( mTableWidget, &QTableWidget::itemChanged,
this, &QgsFilteredTableWidget::itemChanged_p );
79 connect( mTableWidget, &QTableWidget::customContextMenuRequested,
this, &QgsFilteredTableWidget::onTableWidgetCustomContextMenuRequested );
82bool QgsFilteredTableWidget::eventFilter( QObject *watched, QEvent *event )
85 if ( event->type() == QEvent::KeyPress )
87 QKeyEvent *keyEvent =
static_cast<QKeyEvent *
>( event );
88 if ( keyEvent->key() == Qt::Key_Escape && !mSearchWidget->text().isEmpty() )
90 mSearchWidget->clear();
97void QgsFilteredTableWidget::filterStringChanged(
const QString &filterString )
99 auto signalBlockedTableWidget =
whileBlocking( mTableWidget );
100 Q_UNUSED( signalBlockedTableWidget )
102 mTableWidget->clearContents();
103 if ( !mCache.isEmpty() )
106 groups << QVariant();
107 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
109 if ( !groups.contains( pair.first.group ) )
111 groups << pair.first.group;
114 const int groupsCount = mDisplayGroupName ? groups.count() : groups.count() - 1;
116 const int rCount = std::max( 1, (
int ) std::ceil( (
float ) ( mCache.count() + groupsCount ) / (
float ) mColumnCount ) );
117 mTableWidget->setRowCount( rCount );
121 QVariant currentGroup;
122 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
124 if ( column == mColumnCount )
129 if ( currentGroup != pair.first.group )
131 currentGroup = pair.first.group;
132 if ( mDisplayGroupName || !( row == 0 && column == 0 ) )
134 QTableWidgetItem *item =
new QTableWidgetItem( mDisplayGroupName ? pair.first.group.toString() : QString() );
135 item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
136 mTableWidget->setItem( row, column, item );
138 if ( column == mColumnCount )
145 if ( pair.first.value.contains( filterString, Qt::CaseInsensitive ) )
147 QTableWidgetItem *item =
new QTableWidgetItem( pair.first.value );
148 item->setData( Qt::UserRole, pair.first.key );
149 item->setData( Qt::ToolTipRole, pair.first.description );
150 item->setCheckState( pair.second );
151 item->setFlags( mEnabledTable ? item->flags() | Qt::ItemIsEnabled : item->flags() & ~Qt::ItemIsEnabled );
152 mTableWidget->setItem( row, column, item );
156 mTableWidget->setRowCount( row + 1 );
160QStringList QgsFilteredTableWidget::selection()
const
163 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
165 if ( pair.second == Qt::Checked )
166 sel.append( pair.first.key.toString() );
171void QgsFilteredTableWidget::checkItems(
const QStringList &checked )
173 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
175 const bool isChecked = checked.contains( pair.first.key.toString() );
176 pair.second = isChecked ? Qt::Checked : Qt::Unchecked;
179 filterStringChanged( mSearchWidget->text() );
187 mCache.append( qMakePair( element, Qt::Unchecked ) );
189 filterStringChanged( mSearchWidget->text() );
192void QgsFilteredTableWidget::setIndeterminateState()
194 for (
int rowIndex = 0; rowIndex < mTableWidget->rowCount(); rowIndex++ )
196 for (
int columnIndex = 0; columnIndex < mColumnCount; ++columnIndex )
198 if ( item( rowIndex, columnIndex ) )
200 whileBlocking( mTableWidget )->item( rowIndex, columnIndex )->setCheckState( Qt::PartiallyChecked );
210void QgsFilteredTableWidget::setEnabledTable(
const bool enabled )
212 if ( mEnabledTable == enabled )
215 mEnabledTable = enabled;
217 mSearchWidget->clear();
219 filterStringChanged( mSearchWidget->text() );
222void QgsFilteredTableWidget::setColumnCount(
const int count )
224 mColumnCount = count;
225 mTableWidget->setColumnCount( count );
228void QgsFilteredTableWidget::itemChanged_p( QTableWidgetItem *item )
230 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
232 if ( pair.first.key == item->data( Qt::UserRole ) )
233 pair.second = item->checkState();
235 emit itemChanged( item );
238void QgsFilteredTableWidget::onTableWidgetCustomContextMenuRequested(
const QPoint &pos )
243 QAction *actionTableWidgetSelectAll =
new QAction( tr(
"Select All" ),
this );
244 QAction *actionTableWidgetDeselectAll =
new QAction( tr(
"Deselect All" ),
this );
245 connect( actionTableWidgetSelectAll, &QAction::triggered,
this, &QgsFilteredTableWidget::onTableWidgetMenuActionSelectAllTriggered );
246 connect( actionTableWidgetDeselectAll, &QAction::triggered,
this, &QgsFilteredTableWidget::onTableWidgetMenuActionDeselectAllTriggered );
248 QMenu *tableWidgetMenu =
new QMenu( mTableWidget );
249 tableWidgetMenu->addAction( actionTableWidgetSelectAll );
250 tableWidgetMenu->addAction( actionTableWidgetDeselectAll );
252 tableWidgetMenu->exec( QCursor::pos() );
255 disconnect( actionTableWidgetSelectAll, &QAction::triggered,
nullptr,
nullptr );
256 disconnect( actionTableWidgetDeselectAll, &QAction::triggered,
nullptr,
nullptr );
257 actionTableWidgetSelectAll->deleteLater();
258 actionTableWidgetDeselectAll->deleteLater();
261 tableWidgetMenu->deleteLater();
264void QgsFilteredTableWidget::onTableWidgetMenuActionSelectAllTriggered()
266 for (
int rowIndex = 0; rowIndex < mTableWidget->rowCount(); ++rowIndex )
268 for (
int columnIndex = 0; columnIndex < mTableWidget->columnCount(); ++columnIndex )
270 QTableWidgetItem *item =
whileBlocking( mTableWidget )->item( rowIndex, columnIndex );
271 if ( item && ( item->flags() & Qt::ItemIsEnabled ) )
273 item->setCheckState( Qt::Checked );
279void QgsFilteredTableWidget::onTableWidgetMenuActionDeselectAllTriggered()
281 for (
int rowIndex = 0; rowIndex < mTableWidget->rowCount(); ++rowIndex )
283 for (
int columnIndex = 0; columnIndex < mTableWidget->columnCount(); ++columnIndex )
285 QTableWidgetItem *item =
whileBlocking( mTableWidget )->item( rowIndex, columnIndex );
286 if ( item && ( item->flags() & Qt::ItemIsEnabled ) )
288 item->setCheckState( Qt::Unchecked );
307 int cbxIdx = mComboBox->currentIndex();
310 v = mComboBox->currentData();
315 else if ( mTableWidget )
317 QStringList selection = mTableWidget->selection();
320 if ( selection.isEmpty() && !
config( QStringLiteral(
"AllowNull" ) ).toBool() )
327 for (
const QString &s : std::as_const( selection ) )
330 const QMetaType::Type type { fkType() };
333 case QMetaType::Type::Int:
334 vl.push_back( s.toInt() );
336 case QMetaType::Type::LongLong:
337 vl.push_back( s.toLongLong() );
345 if (
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantMap ||
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantList )
355 else if ( mLineEdit )
359 if ( item.value == mLineEdit->text() )
376 mExpression =
config().value( QStringLiteral(
"FilterExpression" ) ).toString();
378 const bool allowMulti =
config( QStringLiteral(
"AllowMulti" ) ).toBool();
379 const bool useCompleter =
config( QStringLiteral(
"UseCompleter" ) ).toBool();
382 const bool displayGroupName =
config( QStringLiteral(
"DisplayGroupName" ) ).toBool();
383 return new QgsFilteredTableWidget( parent, useCompleter, displayGroupName );
385 else if ( useCompleter )
392 combo->setMinimumContentsLength( 1 );
393 combo->setSizeAdjustPolicy( QComboBox::SizeAdjustPolicy::AdjustToMinimumContentsLengthWithIcon );
400 mComboBox = qobject_cast<QComboBox *>( editor );
401 mTableWidget = qobject_cast<QgsFilteredTableWidget *>( editor );
402 mLineEdit = qobject_cast<QLineEdit *>( editor );
409 mComboBox->view()->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded );
412 else if ( mTableWidget )
416 else if ( mLineEdit )
418 if (
QgsFilterLineEdit *filterLineEdit = qobject_cast<QgsFilterLineEdit *>( editor ) )
421 if ( mSubWidgetSignalBlocking == 0 )
427 connect( mLineEdit, &QLineEdit::textChanged,
this, &QgsValueRelationWidgetWrapper::emitValueChangedInternal, Qt::UniqueConnection );
434 return mTableWidget || mLineEdit || mComboBox;
437void QgsValueRelationWidgetWrapper::updateValues(
const QVariant &value,
const QVariantList & )
439 updateValue(
value,
true );
442void QgsValueRelationWidgetWrapper::updateValue(
const QVariant &value,
bool forceComboInsertion )
446 QStringList checkList;
448 if (
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantMap ||
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantList )
450 checkList =
value.toStringList();
457 mTableWidget->checkItems( checkList );
459 else if ( mComboBox )
464 for (
int i = 0; i < mComboBox->count(); i++ )
466 QVariant v( mComboBox->itemData( i ) );
480 for (
int i = 0; i < mComboBox->count(); i++ )
488 mComboBox->setCurrentIndex( idx );
492 mComboBox->addItem(
value.toString().prepend(
'(' ).append(
')' ),
value );
493 mComboBox->setCurrentIndex( mComboBox->findData(
value ) );
498 mComboBox->setCurrentIndex( idx );
501 else if ( mLineEdit )
503 mSubWidgetSignalBlocking++;
505 bool wasFound {
false };
506 for (
const QgsValueRelationFieldFormatter::ValueRelationItem &i : std::as_const( mCache ) )
508 if ( i.key ==
value )
510 mLineEdit->setText( i.value );
518 mLineEdit->setText( tr(
"(no selection)" ) );
520 mSubWidgetSignalBlocking--;
530 if ( attributeChanged || isMultieditMode )
532 QVariant oldValue(
value() );
540 updateValue( isMultieditMode ? oldValue :
value(),
false );
555 QString attributeName( formFields.
names().at(
fieldIdx() ) );
585 && !
config( QStringLiteral(
"AllowNull" ) ).toBool() )
589 QTimer::singleShot( 0,
this, [
this] {
590 if ( !mCache.isEmpty() )
598int QgsValueRelationWidgetWrapper::columnCount()
const
600 return std::max( 1,
config( QStringLiteral(
"NofColumns" ) ).toInt() );
604QMetaType::Type QgsValueRelationWidgetWrapper::fkType()
const
609 QgsFields fields =
layer->fields();
613 return fields.
at( idx ).
type();
616 return QMetaType::Type::UnknownType;
619void QgsValueRelationWidgetWrapper::populate()
624 if (
context().parentFormFeature().isValid() )
633 else if ( mCache.empty() )
640 mComboBox->blockSignals(
true );
642 const bool allowNull =
config( QStringLiteral(
"AllowNull" ) ).toBool();
648 if ( !mCache.isEmpty() )
650 QVariant currentGroup;
651 QStandardItemModel *model = qobject_cast<QStandardItemModel *>( mComboBox->model() );
652 const bool displayGroupName =
config( QStringLiteral(
"DisplayGroupName" ) ).toBool();
653 for (
const QgsValueRelationFieldFormatter::ValueRelationItem &element : std::as_const( mCache ) )
655 if ( currentGroup != element.group )
657 if ( mComboBox->count() > ( allowNull ? 1 : 0 ) )
659 mComboBox->insertSeparator( mComboBox->count() );
661 if ( displayGroupName )
663 mComboBox->addItem( element.group.toString() );
664 QStandardItem *item = model->item( mComboBox->count() - 1 );
665 item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
667 currentGroup = element.group;
670 mComboBox->addItem( element.value, element.key );
672 if ( !element.description.isEmpty() )
674 mComboBox->setItemData( mComboBox->count() - 1, element.description, Qt::ToolTipRole );
678 mComboBox->blockSignals(
false );
680 else if ( mTableWidget )
682 mTableWidget->setColumnCount( columnCount() );
683 mTableWidget->populate( mCache );
685 else if ( mLineEdit )
688 values.reserve( mCache.size() );
689 for (
const QgsValueRelationFieldFormatter::ValueRelationItem &i : std::as_const( mCache ) )
693 QStringListModel *m =
new QStringListModel( values, mLineEdit );
694 QCompleter *completer =
new QCompleter( m, mLineEdit );
696 const Qt::MatchFlags completerMatchFlags {
config().contains( QStringLiteral(
"CompleterMatchFlags" ) ) ?
static_cast<Qt::MatchFlags
>(
config().value( QStringLiteral(
"CompleterMatchFlags" ), Qt::MatchFlag::MatchStartsWith ).toInt() ) : Qt::MatchFlag::MatchStartsWith };
698 if ( completerMatchFlags.testFlag( Qt::MatchFlag::MatchContains ) )
700 completer->setFilterMode( Qt::MatchFlag::MatchContains );
704 completer->setFilterMode( Qt::MatchFlag::MatchStartsWith );
706 completer->setCaseSensitivity( Qt::CaseInsensitive );
707 mLineEdit->setCompleter( completer );
715 mTableWidget->setIndeterminateState();
717 else if ( mComboBox )
721 else if ( mLineEdit )
729 if ( mEnabled == enabled )
736 mTableWidget->setEnabledTable( enabled );
759void QgsValueRelationWidgetWrapper::emitValueChangedInternal(
const QString &
value )
Contains context information for attribute editor widgets.
QgsFeature parentFormFeature() const
Returns the feature of the currently edited parent form in its actual state.
void setParentFormFeature(const QgsFeature &feature)
Sets the feature of the currently edited parent form.
@ MultiEditMode
Multi edit mode, for editing fields of multiple features at once.
Mode attributeFormMode() const
Returns current attributeFormMode.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Q_INVOKABLE bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
bool isValid() const
Returns the validity of this feature.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Container of fields for a vector layer.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
QLineEdit subclass with built in support for clearing the widget's value and handling custom null val...
void valueChanged(const QString &value)
Same as textChanged() but with support for null values.
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, 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.
Represents a vector layer which manages a vector based dataset.
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.