34#include <QStringListModel>
40#include <QStandardItemModel>
42#include <nlohmann/json.hpp>
43using namespace nlohmann;
46QgsFilteredTableWidget::QgsFilteredTableWidget( QWidget *parent,
bool showSearch,
bool displayGroupName )
48 , mDisplayGroupName( displayGroupName )
51 mSearchWidget->setShowSearchIcon(
true );
52 mSearchWidget->setShowClearButton(
true );
53 mTableWidget =
new QTableWidget(
this );
54 mTableWidget->horizontalHeader()->setSectionResizeMode( QHeaderView::Stretch );
55 mTableWidget->horizontalHeader()->setVisible(
false );
56 mTableWidget->verticalHeader()->setSectionResizeMode( QHeaderView::Stretch );
57 mTableWidget->verticalHeader()->setVisible(
false );
58 mTableWidget->setShowGrid(
false );
59 mTableWidget->setEditTriggers( QAbstractItemView::NoEditTriggers );
60 mTableWidget->setSelectionMode( QAbstractItemView::NoSelection );
61 QVBoxLayout *layout =
new QVBoxLayout();
62 layout->addWidget( mSearchWidget );
63 layout->addWidget( mTableWidget );
64 layout->setContentsMargins( 0, 0, 0, 0 );
65 layout->setSpacing( 0 );
68 mTableWidget->setFocusProxy( mSearchWidget );
69 connect( mSearchWidget, &QgsFilterLineEdit::textChanged,
this, &QgsFilteredTableWidget::filterStringChanged );
70 installEventFilter(
this );
74 mSearchWidget->setVisible(
false );
77 connect( mTableWidget, &QTableWidget::itemChanged,
this, &QgsFilteredTableWidget::itemChanged_p );
80bool QgsFilteredTableWidget::eventFilter( QObject *watched, QEvent *event )
83 if ( event->type() == QEvent::KeyPress )
85 QKeyEvent *keyEvent =
static_cast<QKeyEvent *
>( event );
86 if ( keyEvent->key() == Qt::Key_Escape &&
87 !mSearchWidget->text().isEmpty() )
89 mSearchWidget->clear();
96void QgsFilteredTableWidget::filterStringChanged(
const QString &filterString )
98 auto signalBlockedTableWidget =
whileBlocking( mTableWidget );
99 Q_UNUSED( signalBlockedTableWidget )
101 mTableWidget->clearContents();
102 if ( !mCache.isEmpty() )
105 groups << QVariant();
106 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
108 if ( !groups.contains( pair.first.group ) )
110 groups << pair.first.group;
113 const int groupsCount = mDisplayGroupName ? groups.count() : groups.count() - 1;
115 const int rCount = std::max( 1, (
int ) std::ceil( (
float )( mCache.count() + groupsCount ) / (
float ) mColumnCount ) );
116 mTableWidget->setRowCount( rCount );
120 QVariant currentGroup;
121 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
123 if ( column == mColumnCount )
128 if ( currentGroup != pair.first.group )
130 currentGroup = pair.first.group;
131 if ( mDisplayGroupName || !( row == 0 && column == 0 ) )
133 QTableWidgetItem *item =
new QTableWidgetItem( mDisplayGroupName ? pair.first.group.toString() : QString() );
134 item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
135 mTableWidget->setItem( row, column, item );
137 if ( column == mColumnCount )
144 if ( pair.first.value.contains( filterString, Qt::CaseInsensitive ) )
146 QTableWidgetItem *item =
new QTableWidgetItem( pair.first.value );
147 item->setData( Qt::UserRole, pair.first.key );
148 item->setData( Qt::ToolTipRole, pair.first.description );
149 item->setCheckState( pair.second );
150 item->setFlags( mEnabledTable ? item->flags() | Qt::ItemIsEnabled : item->flags() & ~Qt::ItemIsEnabled );
151 mTableWidget->setItem( row, column, item );
155 mTableWidget->setRowCount( row + 1 );
159QStringList QgsFilteredTableWidget::selection()
const
162 for (
const QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : std::as_const( mCache ) )
164 if ( pair.second == Qt::Checked )
165 sel.append( pair.first.key.toString() );
170void QgsFilteredTableWidget::checkItems(
const QStringList &checked )
172 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
174 const bool isChecked = checked.contains( pair.first.key.toString() );
175 pair.second = isChecked ? Qt::Checked : Qt::Unchecked;
178 filterStringChanged( mSearchWidget->text() );
186 mCache.append( qMakePair( element, Qt::Unchecked ) );
188 filterStringChanged( mSearchWidget->text() );
191void QgsFilteredTableWidget::setIndeterminateState()
193 for (
int rowIndex = 0; rowIndex < mTableWidget->rowCount(); rowIndex++ )
195 for (
int columnIndex = 0; columnIndex < mColumnCount; ++columnIndex )
197 if ( item( rowIndex, columnIndex ) )
199 whileBlocking( mTableWidget )->item( rowIndex, columnIndex )->setCheckState( Qt::PartiallyChecked );
209void QgsFilteredTableWidget::setEnabledTable(
const bool enabled )
211 if ( mEnabledTable == enabled )
214 mEnabledTable = enabled;
216 mSearchWidget->clear();
218 filterStringChanged( mSearchWidget->text() );
221void QgsFilteredTableWidget::setColumnCount(
const int count )
223 mColumnCount = count;
224 mTableWidget->setColumnCount( count );
227void QgsFilteredTableWidget::itemChanged_p( QTableWidgetItem *item )
229 for ( QPair<QgsValueRelationFieldFormatter::ValueRelationItem, Qt::CheckState> &pair : mCache )
231 if ( pair.first.key == item->data( Qt::UserRole ) )
232 pair.second = item->checkState();
234 emit itemChanged( item );
250 int cbxIdx = mComboBox->currentIndex();
253 v = mComboBox->currentData();
258 else if ( mTableWidget )
260 QStringList selection = mTableWidget->selection();
263 if ( selection.isEmpty() && !
config( QStringLiteral(
"AllowNull" ) ).toBool( ) )
270 for (
const QString &s : std::as_const( selection ) )
273 const QMetaType::Type type { fkType() };
276 case QMetaType::Type::Int:
277 vl.push_back( s.toInt() );
279 case QMetaType::Type::LongLong:
280 vl.push_back( s.toLongLong() );
288 if (
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantMap ||
289 layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantList )
299 else if ( mLineEdit )
303 if ( item.value == mLineEdit->text() )
320 mExpression =
config().value( QStringLiteral(
"FilterExpression" ) ).toString();
322 const bool allowMulti =
config( QStringLiteral(
"AllowMulti" ) ).toBool();
323 const bool useCompleter =
config( QStringLiteral(
"UseCompleter" ) ).toBool();
326 const bool displayGroupName =
config( QStringLiteral(
"DisplayGroupName" ) ).toBool();
327 return new QgsFilteredTableWidget( parent, useCompleter, displayGroupName );
329 else if ( useCompleter )
336 combo->setMinimumContentsLength( 1 );
337 combo->setSizeAdjustPolicy( QComboBox::SizeAdjustPolicy::AdjustToMinimumContentsLengthWithIcon );
344 mComboBox = qobject_cast<QComboBox *>( editor );
345 mTableWidget = qobject_cast<QgsFilteredTableWidget *>( editor );
346 mLineEdit = qobject_cast<QLineEdit *>( editor );
353 mComboBox->view()->setVerticalScrollBarPolicy( Qt::ScrollBarAsNeeded );
354 connect( mComboBox,
static_cast<void ( QComboBox::* )(
int )
>( &QComboBox::currentIndexChanged ),
357 else if ( mTableWidget )
361 else if ( mLineEdit )
363 if (
QgsFilterLineEdit *filterLineEdit = qobject_cast<QgsFilterLineEdit *>( editor ) )
367 if ( mSubWidgetSignalBlocking == 0 )
373 connect( mLineEdit, &QLineEdit::textChanged,
this, &QgsValueRelationWidgetWrapper::emitValueChangedInternal, Qt::UniqueConnection );
380 return mTableWidget || mLineEdit || mComboBox;
383void QgsValueRelationWidgetWrapper::updateValues(
const QVariant &value,
const QVariantList & )
387 QStringList checkList;
389 if (
layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantMap ||
390 layer()->fields().at(
fieldIdx() ).type() == QMetaType::Type::QVariantList )
392 checkList =
value.toStringList();
399 mTableWidget->checkItems( checkList );
401 else if ( mComboBox )
406 for (
int i = 0; i < mComboBox->count(); i++ )
408 QVariant v( mComboBox->itemData( i ) );
421 mComboBox->setCurrentIndex( -1 );
425 mComboBox->addItem(
value.toString().prepend(
'(' ).append(
')' ),
value );
426 mComboBox->setCurrentIndex( mComboBox->findData(
value ) );
431 mComboBox->setCurrentIndex( idx );
434 else if ( mLineEdit )
436 mSubWidgetSignalBlocking ++;
438 bool wasFound {
false };
441 if ( i.key ==
value )
443 mLineEdit->setText( i.value );
451 mLineEdit->setText( tr(
"(no selection)" ) );
453 mSubWidgetSignalBlocking --;
461 if ( attributeChanged )
463 QVariant oldValue(
value( ) );
471 updateValues(
value( ) );
486 QString attributeName( formFields.
names().at(
fieldIdx() ) );
510 && ! mCache.isEmpty()
511 && !
config( QStringLiteral(
"AllowNull" ) ).toBool( ) )
515 QTimer::singleShot( 0,
this, [
this ]
517 if ( ! mCache.isEmpty() )
519 updateValues( formFeature().attribute( fieldIdx() ).isValid() ? formFeature().attribute( fieldIdx() ) : mCache.at( 0 ).key );
525int QgsValueRelationWidgetWrapper::columnCount()
const
527 return std::max( 1,
config( QStringLiteral(
"NofColumns" ) ).toInt() );
531QMetaType::Type QgsValueRelationWidgetWrapper::fkType()
const
540 return fields.
at( idx ).
type();
543 return QMetaType::Type::UnknownType;
546void QgsValueRelationWidgetWrapper::populate()
552 if (
context().parentFormFeature().isValid() )
561 else if ( mCache.empty() )
568 mComboBox->blockSignals(
true );
570 const bool allowNull =
config( QStringLiteral(
"AllowNull" ) ).toBool();
576 if ( !mCache.isEmpty() )
578 QVariant currentGroup;
579 QStandardItemModel *model = qobject_cast<QStandardItemModel *>( mComboBox->model() );
580 const bool displayGroupName =
config( QStringLiteral(
"DisplayGroupName" ) ).toBool();
583 if ( currentGroup != element.group )
585 if ( mComboBox->count() > ( allowNull ? 1 : 0 ) )
587 mComboBox->insertSeparator( mComboBox->count() );
589 if ( displayGroupName )
591 mComboBox->addItem( element.group.toString() );
592 QStandardItem *item = model->item( mComboBox->count() - 1 );
593 item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
595 currentGroup = element.group;
598 mComboBox->addItem( element.value, element.key );
600 if ( !element.description.isEmpty() )
602 mComboBox->setItemData( mComboBox->count() - 1, element.description, Qt::ToolTipRole );
606 mComboBox->blockSignals(
false );
608 else if ( mTableWidget )
610 mTableWidget->setColumnCount( columnCount() );
611 mTableWidget->populate( mCache );
613 else if ( mLineEdit )
616 values.reserve( mCache.size() );
621 QStringListModel *m =
new QStringListModel( values, mLineEdit );
622 QCompleter *completer =
new QCompleter( m, mLineEdit );
624 const Qt::MatchFlags completerMatchFlags {
config().contains( QStringLiteral(
"CompleterMatchFlags" ) ) ?
static_cast<Qt::MatchFlags
>(
config().value( QStringLiteral(
"CompleterMatchFlags" ), Qt::MatchFlag::MatchStartsWith ).toInt( ) ) : Qt::MatchFlag::MatchStartsWith };
626 if ( completerMatchFlags.testFlag( Qt::MatchFlag::MatchContains ) )
628 completer->setFilterMode( Qt::MatchFlag::MatchContains );
632 completer->setFilterMode( Qt::MatchFlag::MatchStartsWith );
634 completer->setCaseSensitivity( Qt::CaseInsensitive );
635 mLineEdit->setCompleter( completer );
643 mTableWidget->setIndeterminateState();
645 else if ( mComboBox )
649 else if ( mLineEdit )
657 if ( mEnabled == enabled )
664 mTableWidget->setEnabledTable( enabled );
677 ctx.setParentFormFeature( feature );
682 && (
config( QStringLiteral(
"Value" ) ).toString() == attribute ||
683 config( QStringLiteral(
"Key" ) ).toString() == attribute ||
692void 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.