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 --;
464 QVariant oldValue(
value( ) );
472 updateValues(
value( ) );
487 QString attributeName( formFields.
names().at(
fieldIdx() ) );
511 && ! mCache.isEmpty()
512 && !
config( QStringLiteral(
"AllowNull" ) ).toBool( ) )
516 QTimer::singleShot( 0,
this, [
this ]
518 if ( ! mCache.isEmpty() )
520 updateValues( formFeature().attribute( fieldIdx() ).isValid() ? formFeature().attribute( fieldIdx() ) : mCache.at( 0 ).key );
526int QgsValueRelationWidgetWrapper::columnCount()
const
528 return std::max( 1,
config( QStringLiteral(
"NofColumns" ) ).toInt() );
532QMetaType::Type QgsValueRelationWidgetWrapper::fkType()
const
541 return fields.
at( idx ).
type();
544 return QMetaType::Type::UnknownType;
547void QgsValueRelationWidgetWrapper::populate()
553 if (
context().parentFormFeature().isValid() )
562 else if ( mCache.empty() )
569 mComboBox->blockSignals(
true );
571 const bool allowNull =
config( QStringLiteral(
"AllowNull" ) ).toBool();
577 if ( !mCache.isEmpty() )
579 QVariant currentGroup;
580 QStandardItemModel *model = qobject_cast<QStandardItemModel *>( mComboBox->model() );
581 const bool displayGroupName =
config( QStringLiteral(
"DisplayGroupName" ) ).toBool();
584 if ( currentGroup != element.group )
586 if ( mComboBox->count() > ( allowNull ? 1 : 0 ) )
588 mComboBox->insertSeparator( mComboBox->count() );
590 if ( displayGroupName )
592 mComboBox->addItem( element.group.toString() );
593 QStandardItem *item = model->item( mComboBox->count() - 1 );
594 item->setFlags( item->flags() & ~Qt::ItemIsEnabled );
596 currentGroup = element.group;
599 mComboBox->addItem( element.value, element.key );
601 if ( !element.description.isEmpty() )
603 mComboBox->setItemData( mComboBox->count() - 1, element.description, Qt::ToolTipRole );
607 mComboBox->blockSignals(
false );
609 else if ( mTableWidget )
611 mTableWidget->setColumnCount( columnCount() );
612 mTableWidget->populate( mCache );
614 else if ( mLineEdit )
617 values.reserve( mCache.size() );
622 QStringListModel *m =
new QStringListModel( values, mLineEdit );
623 QCompleter *completer =
new QCompleter( m, mLineEdit );
625 const Qt::MatchFlags completerMatchFlags {
config().contains( QStringLiteral(
"CompleterMatchFlags" ) ) ?
static_cast<Qt::MatchFlags
>(
config().value( QStringLiteral(
"CompleterMatchFlags" ), Qt::MatchFlag::MatchStartsWith ).toInt( ) ) : Qt::MatchFlag::MatchStartsWith };
627 if ( completerMatchFlags.testFlag( Qt::MatchFlag::MatchContains ) )
629 completer->setFilterMode( Qt::MatchFlag::MatchContains );
633 completer->setFilterMode( Qt::MatchFlag::MatchStartsWith );
635 completer->setCaseSensitivity( Qt::CaseInsensitive );
636 mLineEdit->setCompleter( completer );
644 mTableWidget->setIndeterminateState();
646 else if ( mComboBox )
650 else if ( mLineEdit )
658 if ( mEnabled == enabled )
665 mTableWidget->setEnabledTable( enabled );
678 ctx.setParentFormFeature( feature );
683 && (
config( QStringLiteral(
"Value" ) ).toString() == attribute ||
684 config( QStringLiteral(
"Key" ) ).toString() == attribute ||
693void 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.