28#include <QRegularExpression>
32#include "moc_qgsvaluemapconfigdlg.cpp"
34using namespace Qt::StringLiterals;
41 mValueMapErrorsLabel->setVisible(
false );
42 mValueMapErrorsLabel->setStyleSheet( u
"QLabel { color : red; }"_s );
44 tableWidget->insertRow( 0 );
46 tableWidget->horizontalHeader()->setSectionsClickable(
true );
47 tableWidget->setSortingEnabled(
true );
49 connect( addNullButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::addNullButtonPushed );
50 connect( removeSelectedButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::removeSelectedButtonPushed );
51 connect( loadFromLayerButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::loadFromLayerButtonPushed );
52 connect( loadFromCSVButton, &QAbstractButton::clicked,
this, &QgsValueMapConfigDlg::loadFromCSVButtonPushed );
53 connect( tableWidget, &QTableWidget::cellChanged,
this, &QgsValueMapConfigDlg::vCellChanged );
54 tableWidget->installEventFilter(
this );
59 QList<QVariant> valueList;
62 for (
int i = 0; i < tableWidget->rowCount() - 1; i++ )
64 QTableWidgetItem *ki = tableWidget->item( i, 0 );
65 QTableWidgetItem *vi = tableWidget->item( i, 1 );
70 QString ks = ki->text();
76 if ( !vi || vi->text().isNull() )
78 value.insert( ks, ks );
82 value.insert( vi->text(), ks );
84 valueList.append( value );
88 cfg.insert( u
"map"_s, valueList );
94 tableWidget->clearContents();
95 for (
int i = tableWidget->rowCount() - 1; i > 0; i-- )
97 tableWidget->removeRow( i );
100 QList<QVariant> valueList =
config.value( u
"map"_s ).toList();
101 QList<QPair<QString, QVariant>> orderedList;
103 if ( valueList.count() > 0 )
105 for (
int i = 0, row = 0; i < valueList.count(); i++, row++ )
107 orderedList.append( qMakePair( valueList[i].toMap().constBegin().value().toString(), valueList[i].toMap().constBegin().key() ) );
113 const QVariantMap values =
config.value( u
"map"_s ).toMap();
114 for ( QVariantMap::ConstIterator mit = values.constBegin(); mit != values.constEnd(); mit++, row++ )
117 orderedList.append( qMakePair( mit.key(), QVariant() ) );
119 orderedList.append( qMakePair( mit.value().toString(), mit.key() ) );
126void QgsValueMapConfigDlg::vCellChanged(
int row,
int column )
129 if ( row == tableWidget->rowCount() - 1 )
131 tableWidget->insertRow( row + 1 );
137 QTableWidgetItem *item = tableWidget->item( row, 0 );
140 const QString validValue = checkValueLength( item->text() );
141 if ( validValue.length() != item->text().length() )
143 const QString errorMessage = tr(
"Value '%1' has been trimmed (maximum field length: %2)" )
144 .arg( item->text(), QString::number(
layer()->fields().
field(
field() ).length() ) );
145 item->setText( validValue );
146 mValueMapErrorsLabel->setVisible(
true );
147 mValueMapErrorsLabel->setText( u
"%1<br>%2"_s.arg( errorMessage, mValueMapErrorsLabel->text() ) );
155void QgsValueMapConfigDlg::removeSelectedButtonPushed()
157 QList<QTableWidgetItem *> list = tableWidget->selectedItems();
158 QSet<int> rowsToRemove;
161 for ( i = 0; i < list.size(); i++ )
163 if ( list[i]->column() == 0 )
165 const int row = list[i]->row();
166 if ( !rowsToRemove.contains( row ) )
168 rowsToRemove.insert( row );
172 for (
const int rowToRemoved : rowsToRemove )
174 tableWidget->removeRow( rowToRemoved - removed );
182 QList<QPair<QString, QVariant>> orderedMap;
183 const auto end = map.constEnd();
184 for (
auto it = map.constBegin(); it != end; ++it )
186 orderedMap.append( qMakePair( it.key(), it.value() ) );
194 tableWidget->clearContents();
195 mValueMapErrorsLabel->setVisible(
false );
197 for (
int i = tableWidget->rowCount() - 1; i > 0; i-- )
199 tableWidget->removeRow( i );
209 constexpr int maxOverflowErrors { 5 };
210 QStringList reportedErrors;
214 for (
const auto &pair : list )
217 setRow( row, pair.first, QString() );
220 const QString value { pair.first };
222 const QString validValue = checkValueLength( value );
224 if ( validValue.length() != value.length() )
226 if ( reportedErrors.length() < maxOverflowErrors )
228 reportedErrors.push_back( tr(
"Value '%1' has been trimmed (maximum field length: %2)" )
229 .arg( value, QString::number( mappedField.
length() ) ) );
231 else if ( reportedErrors.length() == maxOverflowErrors )
233 reportedErrors.push_back( tr(
"Only first %1 errors have been reported." )
234 .arg( maxOverflowErrors ) );
238 setRow( row, validValue, pair.second.toString() );
241 if ( !reportedErrors.isEmpty() )
243 mValueMapErrorsLabel->setVisible(
true );
244 mValueMapErrorsLabel->setText( reportedErrors.join(
"<br>"_L1 ) );
251QString QgsValueMapConfigDlg::checkValueLength(
const QString &value )
261 if ( mappedField.
length() > 0 && value.length() > mappedField.
length() )
263 return value.mid( 0, mappedField.
length() );
271 const QList<QVariant> valueList =
config.value( u
"map"_s ).toList();
273 if ( !valueList.empty() )
275 for (
const QVariant &value : valueList )
277 const QVariantMap valueMap = value.toMap();
282 comboBox->addItem( valueMap.constBegin().key(), valueMap.constBegin().value() );
287 const QVariantMap map =
config.value( u
"map"_s ).toMap();
288 for (
auto it = map.constBegin(); it != map.constEnd(); ++it )
293 comboBox->addItem( it.key(), it.value() );
301 if ( event->type() == QEvent::KeyPress )
303 QKeyEvent *keyEvent =
static_cast<QKeyEvent *
>( event );
304 if ( keyEvent->matches( QKeySequence::Copy ) )
306 copySelectionToClipboard();
314void QgsValueMapConfigDlg::setRow(
int row,
const QString &value,
const QString &description )
316 QTableWidgetItem *valueCell =
nullptr;
317 QTableWidgetItem *descriptionCell =
new QTableWidgetItem( description );
318 tableWidget->insertRow( row );
322 cellFont.setItalic(
true );
325 valueCell->setFont( cellFont );
326 valueCell->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEnabled );
327 descriptionCell->setFont( cellFont );
331 valueCell =
new QTableWidgetItem( value );
333 tableWidget->setItem( row, 0, valueCell );
334 tableWidget->setItem( row, 1, descriptionCell );
337void QgsValueMapConfigDlg::copySelectionToClipboard()
339 QAbstractItemModel *model = tableWidget->model();
340 QItemSelectionModel *selection = tableWidget->selectionModel();
341 const QModelIndexList indexes = selection->selectedIndexes();
343 QString clipboardText;
344 QModelIndex previous = indexes.first();
345 auto mimeData = std::make_unique<QMimeData>();
346 for (
const QModelIndex ¤t : indexes )
348 const QString text = model->data( current ).toString();
349 if ( current.row() != previous.row() )
351 clipboardText.append(
'\n' );
353 else if ( current.column() != previous.column() )
355 clipboardText.append(
'\t' );
357 clipboardText.append( text );
360 mimeData->setData( u
"text/plain"_s, clipboardText.toUtf8() );
361 QApplication::clipboard()->setMimeData( mimeData.release() );
364void QgsValueMapConfigDlg::addNullButtonPushed()
369void QgsValueMapConfigDlg::loadFromLayerButtonPushed()
371 QgsAttributeTypeLoadDialog layerDialog(
layer() );
372 if ( !layerDialog.exec() )
375 updateMap( layerDialog.valueMap(), layerDialog.insertNull() );
378void QgsValueMapConfigDlg::loadFromCSVButtonPushed()
380 const QgsSettings settings;
382 const QString fileName = QFileDialog::getOpenFileName(
nullptr, tr(
"Load Value Map from File" ), QDir::homePath() );
383 if ( fileName.isNull() )
392 if ( !f.open( QIODevice::ReadOnly ) )
394 QMessageBox::information(
nullptr, tr(
"Load Value Map from File" ), tr(
"Could not open file %1\nError was: %2" ).arg( filePath, f.errorString() ), QMessageBox::Cancel );
399 s.setAutoDetectUnicode(
true );
401 const thread_local QRegularExpression re(
"(?:^\"|[;,]\")(\"\"|[\\w\\W]*?)(?=\"[;,]|\"$)|(?:^(?!\")|[;,](?!\"))([^;,]*?)(?=$|[;,])|(\\r\\n|\\n)" );
402 QList<QPair<QString, QVariant>> map;
405 const QString l = s.readLine().trimmed();
406 QRegularExpressionMatchIterator matches = re.globalMatch( l );
408 while ( matches.hasNext() && ceils.size() < 2 )
410 const QRegularExpressionMatch match = matches.next();
411 ceils << match.capturedTexts().last().trimmed().replace(
"\"\""_L1,
"\""_L1 );
414 if ( ceils.size() != 2 )
417 QString key = ceils[0];
418 QString val = ceils[1];
421 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.