28#include <QRegularExpression>
31#include "moc_qgsvaluemapconfigdlg.cpp"
38 mValueMapErrorsLabel->setVisible(
false );
39 mValueMapErrorsLabel->setStyleSheet( QStringLiteral(
"QLabel { color : red; }" ) );
41 tableWidget->insertRow( 0 );
43 tableWidget->horizontalHeader()->setSectionsClickable(
true );
44 tableWidget->setSortingEnabled(
true );
46 connect( addNullButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::addNullButtonPushed );
47 connect( removeSelectedButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::removeSelectedButtonPushed );
48 connect( loadFromLayerButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::loadFromLayerButtonPushed );
49 connect( loadFromCSVButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::loadFromCSVButtonPushed );
50 connect( tableWidget, &QTableWidget::cellChanged,
this, &QgsValueMapConfigDlg::vCellChanged );
51 tableWidget->installEventFilter(
this );
56 QList<QVariant> valueList;
59 for (
int i = 0; i < tableWidget->rowCount() - 1; i++ )
61 QTableWidgetItem *ki = tableWidget->item( i, 0 );
62 QTableWidgetItem *vi = tableWidget->item( i, 1 );
67 QString ks = ki->text();
73 if ( !vi || vi->text().isNull() )
75 value.insert( ks, ks );
79 value.insert( vi->text(), ks );
81 valueList.append( value );
85 cfg.insert( QStringLiteral(
"map" ), valueList );
91 tableWidget->clearContents();
92 for (
int i = tableWidget->rowCount() - 1; i > 0; i-- )
94 tableWidget->removeRow( i );
97 QList<QVariant> valueList =
config.value( QStringLiteral(
"map" ) ).toList();
98 QList<QPair<QString, QVariant>> orderedList;
100 if ( valueList.count() > 0 )
102 for (
int i = 0, row = 0; i < valueList.count(); i++, row++ )
104 orderedList.append( qMakePair( valueList[i].toMap().constBegin().value().toString(), valueList[i].toMap().constBegin().key() ) );
110 const QVariantMap values =
config.value( QStringLiteral(
"map" ) ).toMap();
111 for ( QVariantMap::ConstIterator mit = values.constBegin(); mit != values.constEnd(); mit++, row++ )
114 orderedList.append( qMakePair( mit.key(), QVariant() ) );
116 orderedList.append( qMakePair( mit.value().toString(), mit.key() ) );
123void QgsValueMapConfigDlg::vCellChanged(
int row,
int column )
126 if ( row == tableWidget->rowCount() - 1 )
128 tableWidget->insertRow( row + 1 );
134 QTableWidgetItem *item = tableWidget->item( row, 0 );
137 const QString validValue = checkValueLength( item->text() );
138 if ( validValue.length() != item->text().length() )
140 const QString errorMessage = tr(
"Value '%1' has been trimmed (maximum field length: %2)" )
141 .arg( item->text(), QString::number(
layer()->fields().
field(
field() ).length() ) );
142 item->setText( validValue );
143 mValueMapErrorsLabel->setVisible(
true );
144 mValueMapErrorsLabel->setText( QStringLiteral(
"%1<br>%2" ).arg( errorMessage, mValueMapErrorsLabel->text() ) );
152void QgsValueMapConfigDlg::removeSelectedButtonPushed()
154 QList<QTableWidgetItem *> list = tableWidget->selectedItems();
155 QSet<int> rowsToRemove;
158 for ( i = 0; i < list.size(); i++ )
160 if ( list[i]->column() == 0 )
162 const int row = list[i]->row();
163 if ( !rowsToRemove.contains( row ) )
165 rowsToRemove.insert( row );
169 for (
const int rowToRemoved : rowsToRemove )
171 tableWidget->removeRow( rowToRemoved - removed );
179 QList<QPair<QString, QVariant>> orderedMap;
180 const auto end = map.constEnd();
181 for (
auto it = map.constBegin(); it != end; ++it )
183 orderedMap.append( qMakePair( it.key(), it.value() ) );
191 tableWidget->clearContents();
192 mValueMapErrorsLabel->setVisible(
false );
194 for (
int i = tableWidget->rowCount() - 1; i > 0; i-- )
196 tableWidget->removeRow( i );
206 constexpr int maxOverflowErrors { 5 };
207 QStringList reportedErrors;
211 for (
const auto &pair : list )
214 setRow( row, pair.first, QString() );
217 const QString value { pair.first };
219 const QString validValue = checkValueLength( value );
221 if ( validValue.length() != value.length() )
223 if ( reportedErrors.length() < maxOverflowErrors )
225 reportedErrors.push_back( tr(
"Value '%1' has been trimmed (maximum field length: %2)" )
226 .arg( value, QString::number( mappedField.
length() ) ) );
228 else if ( reportedErrors.length() == maxOverflowErrors )
230 reportedErrors.push_back( tr(
"Only first %1 errors have been reported." )
231 .arg( maxOverflowErrors ) );
235 setRow( row, validValue, pair.second.toString() );
238 if ( !reportedErrors.isEmpty() )
240 mValueMapErrorsLabel->setVisible(
true );
241 mValueMapErrorsLabel->setText( reportedErrors.join( QLatin1String(
"<br>" ) ) );
248QString QgsValueMapConfigDlg::checkValueLength(
const QString &value )
258 if ( mappedField.
length() > 0 && value.length() > mappedField.
length() )
260 return value.mid( 0, mappedField.
length() );
268 const QList<QVariant> valueList =
config.value( QStringLiteral(
"map" ) ).toList();
270 if ( !valueList.empty() )
272 for (
const QVariant &value : valueList )
274 const QVariantMap valueMap = value.toMap();
279 comboBox->addItem( valueMap.constBegin().key(), valueMap.constBegin().value() );
284 const QVariantMap map =
config.value( QStringLiteral(
"map" ) ).toMap();
285 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
290 comboBox->addItem( it.key(), it.value() );
298 if ( event->type() == QEvent::KeyPress )
300 QKeyEvent *keyEvent =
static_cast<QKeyEvent *
>( event );
301 if ( keyEvent->matches( QKeySequence::Copy ) )
303 copySelectionToClipboard();
311void QgsValueMapConfigDlg::setRow(
int row,
const QString &value,
const QString &description )
313 QTableWidgetItem *valueCell =
nullptr;
314 QTableWidgetItem *descriptionCell =
new QTableWidgetItem( description );
315 tableWidget->insertRow( row );
319 cellFont.setItalic(
true );
322 valueCell->setFont( cellFont );
323 valueCell->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
324 descriptionCell->setFont( cellFont );
328 valueCell =
new QTableWidgetItem( value );
330 tableWidget->setItem( row, 0, valueCell );
331 tableWidget->setItem( row, 1, descriptionCell );
334void QgsValueMapConfigDlg::copySelectionToClipboard()
336 QAbstractItemModel *model = tableWidget->model();
337 QItemSelectionModel *selection = tableWidget->selectionModel();
338 const QModelIndexList indexes = selection->selectedIndexes();
340 QString clipboardText;
341 QModelIndex previous = indexes.first();
342 auto mimeData = std::make_unique<QMimeData>();
343 for (
const QModelIndex ¤t : indexes )
345 const QString text = model->data( current ).toString();
346 if ( current.row() != previous.row() )
348 clipboardText.append(
'\n' );
350 else if ( current.column() != previous.column() )
352 clipboardText.append(
'\t' );
354 clipboardText.append( text );
357 mimeData->setData( QStringLiteral(
"text/plain" ), clipboardText.toUtf8() );
358 QApplication::clipboard()->setMimeData( mimeData.release() );
361void QgsValueMapConfigDlg::addNullButtonPushed()
366void QgsValueMapConfigDlg::loadFromLayerButtonPushed()
368 QgsAttributeTypeLoadDialog layerDialog(
layer() );
369 if ( !layerDialog.exec() )
372 updateMap( layerDialog.valueMap(), layerDialog.insertNull() );
375void QgsValueMapConfigDlg::loadFromCSVButtonPushed()
377 const QgsSettings settings;
379 const QString fileName = QFileDialog::getOpenFileName(
nullptr, tr(
"Load Value Map from File" ), QDir::homePath() );
380 if ( fileName.isNull() )
389 if ( !f.open( QIODevice::ReadOnly ) )
391 QMessageBox::information(
nullptr, tr(
"Load Value Map from File" ), tr(
"Could not open file %1\nError was: %2" ).arg( filePath, f.errorString() ), QMessageBox::Cancel );
396 s.setAutoDetectUnicode(
true );
398 const thread_local QRegularExpression re(
"(?:^\"|[;,]\")(\"\"|[\\w\\W]*?)(?=\"[;,]|\"$)|(?:^(?!\")|[;,](?!\"))([^;,]*?)(?=$|[;,])|(\\r\\n|\\n)" );
399 QList<QPair<QString, QVariant>> map;
402 const QString l = s.readLine().trimmed();
403 QRegularExpressionMatchIterator matches = re.globalMatch( l );
405 while ( matches.hasNext() && ceils.size() < 2 )
407 const QRegularExpressionMatch match = matches.next();
408 ceils << match.capturedTexts().last().trimmed().replace( QLatin1String(
"\"\"" ), QLatin1String(
"\"" ) );
411 if ( ceils.size() != 2 )
414 QString key = ceils[0];
415 QString val = ceils[1];
418 map.append( qMakePair( key, val ) );
static QString nullRepresentation()
Returns the string used to represent the value NULL throughout QGIS.
Encapsulate a field in an attribute table or data source.
QgsField field(int fieldIdx) const
Returns the field at particular index (must be in range 0..N-1).
Q_INVOKABLE bool exists(int i) const
Returns if a field index is valid.
void loadMapFromCSV(const QString &filePath)
Updates the displayed table with the values from a CSV file.
void setConfig(const QVariantMap &config) override
Update the configuration widget to represent the given configuration.
bool eventFilter(QObject *watched, QEvent *event) override
QgsValueMapConfigDlg(QgsVectorLayer *vl, int fieldIdx, QWidget *parent)
void updateMap(const QMap< QString, QVariant > &map, bool insertNull)
Updates the displayed table with the values from map.
static void populateComboBox(QComboBox *comboBox, const QVariantMap &configuration, bool skipNull)
Populates a comboBox with the appropriate entries based on a value map configuration.
QVariantMap config() override
Create a configuration from the current GUI state.
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
Represents a vector layer which manages a vector based dataset.