17#include "moc_qgsvaluerelationwidgetwrapper.cpp"
30#include <QStringListModel>
36#include <QStandardItemModel>
38#include <nlohmann/json.hpp>
39using namespace nlohmann;
42QgsFilteredTableWidget::QgsFilteredTableWidget( QWidget *parent,
bool showSearch,
bool displayGroupName )
44 , mDisplayGroupName( displayGroupName )
47 mSearchWidget->setShowSearchIcon(
true );
48 mSearchWidget->setShowClearButton(
true );
49 mTableWidget =
new QTableWidget(
this );
50 mTableWidget->horizontalHeader()->setSectionResizeMode( QHeaderView::Stretch );
51 mTableWidget->horizontalHeader()->setVisible(
false );
52 mTableWidget->verticalHeader()->setSectionResizeMode( QHeaderView::Stretch );
53 mTableWidget->verticalHeader()->setVisible(
false );
54 mTableWidget->setShowGrid(
false );
55 mTableWidget->setEditTriggers( QAbstractItemView::NoEditTriggers );
56 mTableWidget->setSelectionMode( QAbstractItemView::NoSelection );
57 QVBoxLayout *layout =
new QVBoxLayout();
58 layout->addWidget( mSearchWidget );
59 layout->addWidget( mTableWidget );
60 layout->setContentsMargins( 0, 0, 0, 0 );
61 layout->setSpacing( 0 );
64 mTableWidget->setFocusProxy( mSearchWidget );
65 connect( mSearchWidget, &QgsFilterLineEdit::textChanged,
this, &QgsFilteredTableWidget::filterStringChanged );
66 installEventFilter(
this );
70 mSearchWidget->setVisible(
false );
73 connect( mTableWidget, &QTableWidget::itemChanged,
this, &QgsFilteredTableWidget::itemChanged_p );
76bool QgsFilteredTableWidget::eventFilter( QObject *watched, QEvent *event )
79 if ( event->type() == QEvent::KeyPress )
81 QKeyEvent *keyEvent =
static_cast<QKeyEvent *
>( event );
82 if ( keyEvent->key() == Qt::Key_Escape && !mSearchWidget->text().isEmpty() )
84 mSearchWidget->clear();
91void QgsFilteredTableWidget::filterStringChanged(
const QString &filterString )
93 auto signalBlockedTableWidget =
whileBlocking( mTableWidget );
94 Q_UNUSED( signalBlockedTableWidget )
96 mTableWidget->clearContents();
97 if ( !mCache.isEmpty() )
100 groups << QVariant();
101 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
103 if ( !groups.contains( pair.first.group ) )
105 groups << pair.first.group;
108 const int groupsCount = mDisplayGroupName ? groups.count() : groups.count() - 1;
110 const int rCount = std::max( 1, (
int ) std::ceil( (
float ) ( mCache.count() + groupsCount ) / (
float ) mColumnCount ) );
111 mTableWidget->setRowCount( rCount );
115 QVariant currentGroup;
116 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
118 if ( column == mColumnCount )
123 if ( currentGroup != pair.first.group )
125 currentGroup = pair.first.group;
126 if ( mDisplayGroupName || !( row == 0 && column == 0 ) )
128 QTableWidgetItem *item =
new QTableWidgetItem( mDisplayGroupName ? pair.first.group.toString() : QString() );
129 item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
130 mTableWidget->setItem( row, column, item );
132 if ( column == mColumnCount )
139 if ( pair.first.value.contains( filterString, Qt::CaseInsensitive ) )
141 QTableWidgetItem *item =
new QTableWidgetItem( pair.first.value );
142 item->setData( Qt::UserRole, pair.first.key );
143 item->setData( Qt::ToolTipRole, pair.first.description );
144 item->setCheckState( pair.second );
145 item->setFlags( mEnabledTable ? item->flags() | Qt::ItemIsEnabled : item->flags() & ~Qt::ItemIsEnabled );
146 mTableWidget->setItem( row, column, item );
150 mTableWidget->setRowCount( row + 1 );
154QStringList QgsFilteredTableWidget::selection()
const
157 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
159 if ( pair.second == Qt::Checked )
160 sel.append( pair.first.key.toString() );
165void QgsFilteredTableWidget::checkItems(
const QStringList &checked )
167 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
169 const bool isChecked = checked.contains( pair.first.key.toString() );
170 pair.second = isChecked ? Qt::Checked : Qt::Unchecked;
173 filterStringChanged( mSearchWidget->text() );
181 mCache.append( qMakePair( element, Qt::Unchecked ) );
183 filterStringChanged( mSearchWidget->text() );
186void QgsFilteredTableWidget::setIndeterminateState()
188 for (
int rowIndex = 0; rowIndex < mTableWidget->rowCount(); rowIndex++ )
190 for (
int columnIndex = 0; columnIndex < mColumnCount; ++columnIndex )
192 if ( item( rowIndex, columnIndex ) )
194 whileBlocking( mTableWidget )->item( rowIndex, columnIndex )->setCheckState( Qt::PartiallyChecked );
204void QgsFilteredTableWidget::setEnabledTable(
const bool enabled )
206 if ( mEnabledTable == enabled )
209 mEnabledTable = enabled;
211 mSearchWidget->clear();
213 filterStringChanged( mSearchWidget->text() );
216void QgsFilteredTableWidget::setColumnCount(
const int count )
218 mColumnCount = count;
219 mTableWidget->setColumnCount( count );
222void QgsFilteredTableWidget::itemChanged_p( QTableWidgetItem *item )
224 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
226 if ( pair.first.key == item->data( Qt::UserRole ) )
227 pair.second = item->checkState();
229 emit itemChanged( item );
245 int cbxIdx = mComboBox->currentIndex();
248 v = mComboBox->currentData();
253 else if ( mTableWidget )
255 QStringList selection = mTableWidget->selection();
258 if ( selection.isEmpty() && !
config( QStringLiteral(
"AllowNull" ) ).toBool() )
265 for (
const QString &s : std::as_const( selection ) )
268 const QMetaType::Type type { fkType() };
271 case QMetaType::Type::Int:
272 vl.push_back( s.toInt() );
274 case QMetaType::Type::LongLong:
275 vl.push_back( s.toLongLong() );
283 if (
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantMap ||
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantList )
293 else if ( mLineEdit )
297 if ( item.value == mLineEdit->text() )
314 mExpression =
config().value( QStringLiteral(
"FilterExpression" ) ).toString();
316 const bool allowMulti =
config( QStringLiteral(
"AllowMulti" ) ).toBool();
317 const bool useCompleter =
config( QStringLiteral(
"UseCompleter" ) ).toBool();
320 const bool displayGroupName =
config( QStringLiteral(
"DisplayGroupName" ) ).toBool();
321 return new QgsFilteredTableWidget( parent, useCompleter, displayGroupName );
323 else if ( useCompleter )
330 combo->setMinimumContentsLength( 1 );
331 combo->setSizeAdjustPolicy( QComboBox::SizeAdjustPolicy::AdjustToMinimumContentsLengthWithIcon );
338 mComboBox = qobject_cast<QComboBox *>( editor );
339 mTableWidget = qobject_cast<QgsFilteredTableWidget *>( editor );
340 mLineEdit = qobject_cast<QLineEdit *>( editor );
347 mComboBox->view()->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded );
350 else if ( mTableWidget )
354 else if ( mLineEdit )
356 if (
QgsFilterLineEdit *filterLineEdit = qobject_cast<QgsFilterLineEdit *>( editor ) )
359 if ( mSubWidgetSignalBlocking == 0 )
365 connect( mLineEdit, &QLineEdit::textChanged,
this, &QgsValueRelationWidgetWrapper::emitValueChangedInternal, Qt::UniqueConnection );
372 return mTableWidget || mLineEdit || mComboBox;
375void QgsValueRelationWidgetWrapper::updateValues(
const QVariant &value,
const QVariantList & )
377 updateValue(
value,
true );
380void QgsValueRelationWidgetWrapper::updateValue(
const QVariant &value,
bool forceComboInsertion )
384 QStringList checkList;
386 if (
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantMap ||
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantList )
388 checkList =
value.toStringList();
395 mTableWidget->checkItems( checkList );
397 else if ( mComboBox )
402 for (
int i = 0; i < mComboBox->count(); i++ )
404 QVariant v( mComboBox->itemData( i ) );
417 mComboBox->setCurrentIndex( -1 );
421 mComboBox->addItem(
value.toString().prepend(
'(' ).append(
')' ),
value );
422 mComboBox->setCurrentIndex( mComboBox->findData(
value ) );
427 mComboBox->setCurrentIndex( idx );
430 else if ( mLineEdit )
432 mSubWidgetSignalBlocking++;
434 bool wasFound {
false };
437 if ( i.key ==
value )
439 mLineEdit->setText( i.value );
447 mLineEdit->setText( tr(
"(no selection)" ) );
449 mSubWidgetSignalBlocking--;
460 QVariant oldValue(
value() );
468 updateValue( oldValue,
false );
483 QString attributeName( formFields.
names().at(
fieldIdx() ) );
508 && !
config( QStringLiteral(
"AllowNull" ) ).toBool() )
512 QTimer::singleShot( 0,
this, [
this] {
513 if ( !mCache.isEmpty() )
515 updateValues( formFeature().attribute( fieldIdx() ).isValid() ? formFeature().attribute( fieldIdx() ) : mCache.at( 0 ).key );
521int QgsValueRelationWidgetWrapper::columnCount()
const
523 return std::max( 1,
config( QStringLiteral(
"NofColumns" ) ).toInt() );
527QMetaType::Type QgsValueRelationWidgetWrapper::fkType()
const
536 return fields.
at( idx ).
type();
539 return QMetaType::Type::UnknownType;
542void QgsValueRelationWidgetWrapper::populate()
547 if (
context().parentFormFeature().isValid() )
556 else if ( mCache.empty() )
563 mComboBox->blockSignals(
true );
565 const bool allowNull =
config( QStringLiteral(
"AllowNull" ) ).toBool();
571 if ( !mCache.isEmpty() )
573 QVariant currentGroup;
574 QStandardItemModel *model = qobject_cast<QStandardItemModel *>( mComboBox->model() );
575 const bool displayGroupName =
config( QStringLiteral(
"DisplayGroupName" ) ).toBool();
578 if ( currentGroup != element.group )
580 if ( mComboBox->count() > ( allowNull ? 1 : 0 ) )
582 mComboBox->insertSeparator( mComboBox->count() );
584 if ( displayGroupName )
586 mComboBox->addItem( element.group.toString() );
587 QStandardItem *item = model->item( mComboBox->count() - 1 );
588 item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
590 currentGroup = element.group;
593 mComboBox->addItem( element.value, element.key );
595 if ( !element.description.isEmpty() )
597 mComboBox->setItemData( mComboBox->count() - 1, element.description, Qt::ToolTipRole );
601 mComboBox->blockSignals(
false );
603 else if ( mTableWidget )
605 mTableWidget->setColumnCount( columnCount() );
606 mTableWidget->populate( mCache );
608 else if ( mLineEdit )
611 values.reserve( mCache.size() );
616 QStringListModel *m =
new QStringListModel( values, mLineEdit );
617 QCompleter *completer =
new QCompleter( m, mLineEdit );
619 const Qt::MatchFlags completerMatchFlags {
config().contains( QStringLiteral(
"CompleterMatchFlags" ) ) ?
static_cast<Qt::MatchFlags
>(
config().value( QStringLiteral(
"CompleterMatchFlags" ), Qt::MatchFlag::MatchStartsWith ).toInt() ) : Qt::MatchFlag::MatchStartsWith };
621 if ( completerMatchFlags.testFlag( Qt::MatchFlag::MatchContains ) )
623 completer->setFilterMode( Qt::MatchFlag::MatchContains );
627 completer->setFilterMode( Qt::MatchFlag::MatchStartsWith );
629 completer->setCaseSensitivity( Qt::CaseInsensitive );
630 mLineEdit->setCompleter( completer );
638 mTableWidget->setIndeterminateState();
640 else if ( mComboBox )
644 else if ( mLineEdit )
652 if ( mEnabled == enabled )
659 mTableWidget->setEnabledTable( enabled );
671 ctx.setParentFormFeature( feature );
682void 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.
@ MultiEditMode
Multi edit mode, for editing fields of multiple features at once.
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.
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 data sets.
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.