29#include <QRegularExpression>
36 mValueMapErrorsLabel->setVisible(
false );
37 mValueMapErrorsLabel->setStyleSheet( QStringLiteral(
"QLabel { color : red; }" ) );
39 tableWidget->insertRow( 0 );
41 tableWidget->horizontalHeader()->setSectionsClickable(
true );
42 tableWidget->setSortingEnabled(
true );
44 connect( addNullButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::addNullButtonPushed );
45 connect( removeSelectedButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::removeSelectedButtonPushed );
46 connect( loadFromLayerButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::loadFromLayerButtonPushed );
47 connect( loadFromCSVButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::loadFromCSVButtonPushed );
48 connect( tableWidget, &QTableWidget::cellChanged,
this, &QgsValueMapConfigDlg::vCellChanged );
49 tableWidget->installEventFilter(
this );
54 QList<QVariant> valueList;
57 for (
int i = 0; i < tableWidget->rowCount() - 1; i++ )
59 QTableWidgetItem *ki = tableWidget->item( i, 0 );
60 QTableWidgetItem *vi = tableWidget->item( i, 1 );
65 QString ks = ki->text();
71 if ( !vi || vi->text().isNull() )
73 value.insert( ks, ks );
77 value.insert( vi->text(), ks );
79 valueList.append( value );
83 cfg.insert( QStringLiteral(
"map" ), valueList );
89 tableWidget->clearContents();
90 for (
int i = tableWidget->rowCount() - 1; i > 0; i-- )
92 tableWidget->removeRow( i );
95 QList<QVariant> valueList =
config.value( QStringLiteral(
"map" ) ).toList();
96 QList<QPair<QString, QVariant>> orderedList;
98 if ( valueList.count() > 0 )
100 for (
int i = 0, row = 0; i < valueList.count(); i++, row++ )
102 orderedList.append( qMakePair( valueList[i].toMap().constBegin().value().toString(), valueList[i].toMap().constBegin().key() ) );
108 const QVariantMap values =
config.value( QStringLiteral(
"map" ) ).toMap();
109 for ( QVariantMap::ConstIterator mit = values.constBegin(); mit != values.constEnd(); mit++, row++ )
112 orderedList.append( qMakePair( mit.key(), QVariant() ) );
114 orderedList.append( qMakePair( mit.value().toString(), mit.key() ) );
122void QgsValueMapConfigDlg::vCellChanged(
int row,
int column )
125 if ( row == tableWidget->rowCount() - 1 )
127 tableWidget->insertRow( row + 1 );
133 QTableWidgetItem *item = tableWidget->item( row, 0 );
136 const QString validValue = checkValueLength( item->text() );
137 if ( validValue.length() != item->text().length() )
139 const QString errorMessage = tr(
"Value '%1' has been trimmed (maximum field length: %2)" )
140 .arg( item->text(), QString::number(
layer()->fields().
field(
field() ).length() ) );
141 item->setText( validValue );
142 mValueMapErrorsLabel->setVisible(
true );
143 mValueMapErrorsLabel->setText( QStringLiteral(
"%1<br>%2" ).arg( errorMessage, mValueMapErrorsLabel->text() ) );
151void QgsValueMapConfigDlg::removeSelectedButtonPushed()
153 QList<QTableWidgetItem *> list = tableWidget->selectedItems();
154 QSet<int> rowsToRemove;
157 for ( i = 0; i < list.size(); i++ )
159 if ( list[i]->column() == 0 )
161 const int row = list[i]->row();
162 if ( !rowsToRemove.contains( row ) )
164 rowsToRemove.insert( row );
168 for (
const int rowToRemoved : rowsToRemove )
170 tableWidget->removeRow( rowToRemoved - removed );
178 QList<QPair<QString, QVariant>> orderedMap;
179 const auto end = map.constEnd();
180 for (
auto it = map.constBegin(); it != end; ++it )
182 orderedMap.append( qMakePair( it.key(), it.value() ) );
190 tableWidget->clearContents();
191 mValueMapErrorsLabel->setVisible(
false );
193 for (
int i = tableWidget->rowCount() - 1; i > 0; i-- )
195 tableWidget->removeRow( i );
205 constexpr int maxOverflowErrors { 5 };
206 QStringList reportedErrors;
210 for (
const auto &pair : list )
213 setRow( row, pair.first, QString() );
216 const QString value { pair.first };
218 const QString validValue = checkValueLength( value ) ;
220 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 )
253 if ( mappedField.length() > 0 && value.length() > mappedField.length() )
255 return value.mid( 0, mappedField.length() );
263 const QList<QVariant> valueList =
config.value( QStringLiteral(
"map" ) ).toList();
265 if ( !valueList.empty() )
267 for (
const QVariant &value : valueList )
269 const QVariantMap valueMap = value.toMap();
274 comboBox->addItem( valueMap.constBegin().key(), valueMap.constBegin().value() );
279 const QVariantMap map =
config.value( QStringLiteral(
"map" ) ).toMap();
280 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
285 comboBox->addItem( it.key(), it.value() );
293 if ( event->type() == QEvent::KeyPress )
295 QKeyEvent *keyEvent =
static_cast<QKeyEvent *
>( event );
296 if ( keyEvent->matches( QKeySequence::Copy ) )
298 copySelectionToClipboard();
306void QgsValueMapConfigDlg::setRow(
int row,
const QString &value,
const QString &description )
309 QTableWidgetItem *valueCell =
nullptr;
310 QTableWidgetItem *descriptionCell =
new QTableWidgetItem( description );
311 tableWidget->insertRow( row );
315 cellFont.setItalic(
true );
317 valueCell->setFont( cellFont );
318 valueCell->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
319 descriptionCell->setFont( cellFont );
323 valueCell =
new QTableWidgetItem( value );
325 tableWidget->setItem( row, 0, valueCell );
326 tableWidget->setItem( row, 1, descriptionCell );
329void QgsValueMapConfigDlg::copySelectionToClipboard()
331 QAbstractItemModel *model = tableWidget->model();
332 QItemSelectionModel *selection = tableWidget->selectionModel();
333 const QModelIndexList indexes = selection->selectedIndexes();
335 QString clipboardText;
336 QModelIndex previous = indexes.first();
337 std::unique_ptr<QMimeData> mimeData = std::make_unique<QMimeData>();
338 for (
const QModelIndex ¤t : indexes )
340 const QString text = model->data( current ).toString();
341 if ( current.row() != previous.row() )
343 clipboardText.append(
'\n' );
345 else if ( current.column() != previous.column() )
347 clipboardText.append(
'\t' );
349 clipboardText.append( text );
352 mimeData->setData( QStringLiteral(
"text/plain" ), clipboardText.toUtf8() );
353 QApplication::clipboard()->setMimeData( mimeData.release() );
356void QgsValueMapConfigDlg::addNullButtonPushed()
361void QgsValueMapConfigDlg::loadFromLayerButtonPushed()
364 if ( !layerDialog.exec() )
367 updateMap( layerDialog.valueMap(), layerDialog.insertNull() );
370void QgsValueMapConfigDlg::loadFromCSVButtonPushed()
374 const QString fileName = QFileDialog::getOpenFileName(
nullptr, tr(
"Load Value Map from File" ), QDir::homePath() );
375 if ( fileName.isNull() )
384 if ( !f.open( QIODevice::ReadOnly ) )
386 QMessageBox::information(
nullptr,
387 tr(
"Load Value Map from File" ),
388 tr(
"Could not open file %1\nError was: %2" ).arg( filePath, f.errorString() ),
389 QMessageBox::Cancel );
394 s.setAutoDetectUnicode(
true );
396 const thread_local QRegularExpression re(
"(?:^\"|[;,]\")(\"\"|[\\w\\W]*?)(?=\"[;,]|\"$)|(?:^(?!\")|[;,](?!\"))([^;,]*?)(?=$|[;,])|(\\r\\n|\\n)" );
397 QList<QPair<QString, QVariant>> map;
400 const QString l = s.readLine().trimmed();
401 QRegularExpressionMatchIterator matches = re.globalMatch( l );
403 while ( matches.hasNext() && ceils.size() < 2 )
405 const QRegularExpressionMatch match = matches.next();
406 ceils << match.capturedTexts().last().trimmed().replace( QLatin1String(
"\"\"" ), QLatin1String(
"\"" ) );
409 if ( ceils.size() != 2 )
412 QString key = ceils[0];
413 QString val = ceils[1];
416 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.
This class is a composition of two QSettings instances:
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 data sets.