QGIS API Documentation 3.41.0-Master (45a0abf3bec)
Loading...
Searching...
No Matches
qgsnewgeopackagelayerdialog.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsnewgeopackagelayerdialog.cpp
3
4 -------------------
5 begin : April 2016
6 copyright : (C) 2016 by Even Rouault
7 email : even.rouault at spatialys.com
8 ***************************************************************************/
9
10/***************************************************************************
11 * *
12 * This program is free software; you can redistribute it and/or modify *
13 * it under the terms of the GNU General Public License as published by *
14 * the Free Software Foundation; either version 2 of the License, or *
15 * (at your option) any later version. *
16 * *
17 ***************************************************************************/
18
19
21#include "moc_qgsnewgeopackagelayerdialog.cpp"
22
23#include "qgis.h"
24#include "qgsapplication.h"
25#include "qgsvectorlayer.h"
26#include "qgsproject.h"
28#include "qgssettings.h"
29#include "qgshelp.h"
30#include "qgsogrutils.h"
31#include "qgsgui.h"
33#include "qgsiconutils.h"
34#include "qgsvariantutils.h"
35
36#include <QPushButton>
37#include <QLineEdit>
38#include <QMessageBox>
39#include <QFileDialog>
40#include <QCompleter>
41
42#include <ogr_api.h>
43#include <ogr_srs_api.h>
44#include <gdal_version.h>
45#include <cpl_error.h>
46#include <cpl_string.h>
47
48#define DEFAULT_OGR_FID_COLUMN_TITLE "fid" // default value from OGR
49
51 : QDialog( parent, fl )
52{
53 setupUi( this );
54 setObjectName( QStringLiteral( "QgsNewGeoPackageLayerDialog" ) );
56
57 connect( mAddAttributeButton, &QToolButton::clicked, this, &QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked );
58 connect( mRemoveAttributeButton, &QToolButton::clicked, this, &QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked );
59 connect( mFieldTypeBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged );
60 connect( mGeometryTypeBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged );
61 connect( mTableNameEdit, &QLineEdit::textChanged, this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged );
62 connect( mTableNameEdit, &QLineEdit::textEdited, this, &QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited );
63 connect( mLayerIdentifierEdit, &QLineEdit::textEdited, this, &QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited );
64 connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsNewGeoPackageLayerDialog::buttonBox_accepted );
65 connect( buttonBox, &QDialogButtonBox::rejected, this, &QgsNewGeoPackageLayerDialog::buttonBox_rejected );
66 connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsNewGeoPackageLayerDialog::showHelp );
67 connect( mButtonUp, &QToolButton::clicked, this, &QgsNewGeoPackageLayerDialog::moveFieldsUp );
68 connect( mButtonDown, &QToolButton::clicked, this, &QgsNewGeoPackageLayerDialog::moveFieldsDown );
69
70 mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) );
71 mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) );
72
73 const auto addGeomItem = [this]( OGRwkbGeometryType ogrGeomType )
74 {
75 const Qgis::WkbType qgsType = QgsOgrUtils::ogrGeometryTypeToQgsWkbType( ogrGeomType );
76 mGeometryTypeBox->addItem( QgsIconUtils::iconForWkbType( qgsType ), QgsWkbTypes::translatedDisplayString( qgsType ), ogrGeomType );
77 };
78
79 addGeomItem( wkbNone );
80 addGeomItem( wkbPoint );
81 addGeomItem( wkbLineString );
82 addGeomItem( wkbPolygon );
83 addGeomItem( wkbMultiPoint );
84 addGeomItem( wkbMultiLineString );
85 addGeomItem( wkbMultiPolygon );
86
87#if 0
88 // QGIS always create CompoundCurve and there's no real interest of having just CircularString. CompoundCurve are more useful
89 addGeomItem( wkbCircularString );
90#endif
91 addGeomItem( wkbCompoundCurve );
92 addGeomItem( wkbCurvePolygon );
93 addGeomItem( wkbMultiCurve );
94 addGeomItem( wkbMultiSurface );
95 mGeometryTypeBox->setCurrentIndex( -1 );
96
97 mGeometryWithZCheckBox->setEnabled( false );
98 mGeometryWithMCheckBox->setEnabled( false );
99 mGeometryColumnEdit->setEnabled( false );
100 mGeometryColumnEdit->setText( QStringLiteral( "geometry" ) );
101 mFeatureIdColumnEdit->setPlaceholderText( QStringLiteral( DEFAULT_OGR_FID_COLUMN_TITLE ) );
102 mCheckBoxCreateSpatialIndex->setEnabled( false );
103 mCrsSelector->setEnabled( false );
104 mCrsSelector->setShowAccuracyWarnings( true );
105
106 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::QString ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::QString ), "text" );
107 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::Int ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::Int ), "integer" );
108 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::LongLong ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::LongLong ), "integer64" );
109 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::Double ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::Double ), "real" );
110 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::QDate ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::QDate ), "date" );
111 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::QDateTime ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::QDateTime ), "datetime" );
112 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::Bool ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::Bool ), "bool" );
113 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::QByteArray ), QgsVariantUtils::typeToDisplayString( QMetaType::Type::QByteArray ), "binary" );
114 mFieldTypeBox->addItem( QgsFields::iconForFieldType( QMetaType::Type::QVariantMap ), tr( "JSON" ), "json" );
115
116 mOkButton = buttonBox->button( QDialogButtonBox::Ok );
117 mOkButton->setEnabled( false );
118
119 connect( mFieldNameEdit, &QLineEdit::textChanged, this, &QgsNewGeoPackageLayerDialog::fieldNameChanged );
120 connect( mAttributeView, &QTreeWidget::itemSelectionChanged, this, &QgsNewGeoPackageLayerDialog::selectionChanged );
121 connect( mTableNameEdit, &QLineEdit::textChanged, this, &QgsNewGeoPackageLayerDialog::checkOk );
122 connect( mGeometryTypeBox, static_cast<void( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsNewGeoPackageLayerDialog::checkOk );
123
124 mAddAttributeButton->setEnabled( false );
125 mRemoveAttributeButton->setEnabled( false );
126 mButtonUp->setEnabled( false );
127 mButtonDown->setEnabled( false );
128
129 mCheckBoxCreateSpatialIndex->setChecked( true );
130
131 const QgsSettings settings;
132 mDatabase->setStorageMode( QgsFileWidget::SaveFile );
133 mDatabase->setFilter( tr( "GeoPackage" ) + " (*.gpkg)" );
134 mDatabase->setDialogTitle( tr( "Select Existing or Create a New GeoPackage Database File…" ) );
135 mDatabase->setDefaultRoot( settings.value( QStringLiteral( "UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() );
136 mDatabase->setConfirmOverwrite( false );
137 connect( mDatabase, &QgsFileWidget::fileChanged, this, [ = ]( const QString & filePath )
138 {
139 QgsSettings settings;
140 const QFileInfo tmplFileInfo( filePath );
141 settings.setValue( QStringLiteral( "UI/lastVectorFileFilterDir" ), tmplFileInfo.absolutePath() );
142 if ( !filePath.isEmpty() && !mTableNameEdited )
143 {
144 const QFileInfo fileInfo( filePath );
145 mTableNameEdit->setText( fileInfo.baseName() );
146 }
147 checkOk();
148 } );
149
150 QgsProviderConnectionModel *ogrProviderModel = new QgsProviderConnectionModel( QStringLiteral( "ogr" ), this );
151
152 QCompleter *completer = new QCompleter( this );
153 completer->setModel( ogrProviderModel );
154 completer->setCompletionRole( static_cast< int >( QgsProviderConnectionModel::CustomRole::Uri ) );
155 completer->setCompletionMode( QCompleter::PopupCompletion );
156 completer->setFilterMode( Qt::MatchContains );
157 mDatabase->lineEdit()->setCompleter( completer );
158}
159
161{
162 mCrsSelector->setCrs( crs );
163}
164
166{
167 mDatabase->setReadOnly( true );
168}
169
170void QgsNewGeoPackageLayerDialog::mFieldTypeBox_currentIndexChanged( int )
171{
172 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
173 mFieldLengthEdit->setEnabled( myType == QLatin1String( "text" ) );
174 if ( myType != QLatin1String( "text" ) )
175 mFieldLengthEdit->clear();
176}
177
178
179void QgsNewGeoPackageLayerDialog::mGeometryTypeBox_currentIndexChanged( int )
180{
181 const OGRwkbGeometryType geomType = static_cast<OGRwkbGeometryType>
182 ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
183 const bool isSpatial = geomType != wkbNone;
184 mGeometryWithZCheckBox->setEnabled( isSpatial );
185 mGeometryWithMCheckBox->setEnabled( isSpatial );
186 mGeometryColumnEdit->setEnabled( isSpatial );
187 mCheckBoxCreateSpatialIndex->setEnabled( isSpatial );
188 mCrsSelector->setEnabled( isSpatial );
189}
190
191void QgsNewGeoPackageLayerDialog::mTableNameEdit_textChanged( const QString &text )
192{
193 mTableNameEdited = !text.isEmpty();
194 if ( !text.isEmpty() && !mLayerIdentifierEdited )
195 {
196 mLayerIdentifierEdit->setText( text );
197 }
198}
199
200void QgsNewGeoPackageLayerDialog::mTableNameEdit_textEdited( const QString &text )
201{
202 // Remember if the user explicitly defined a name
203 mTableNameEdited = !text.isEmpty();
204}
205
206void QgsNewGeoPackageLayerDialog::mLayerIdentifierEdit_textEdited( const QString &text )
207{
208 // Remember if the user explicitly defined a name
209 mLayerIdentifierEdited = !text.isEmpty();
210}
211
212void QgsNewGeoPackageLayerDialog::checkOk()
213{
214 const bool ok = !mDatabase->filePath().isEmpty() &&
215 !mTableNameEdit->text().isEmpty() &&
216 mGeometryTypeBox->currentIndex() != -1;
217
218 mOkButton->setEnabled( ok );
219}
220
221void QgsNewGeoPackageLayerDialog::mAddAttributeButton_clicked()
222{
223 if ( !mFieldNameEdit->text().isEmpty() )
224 {
225 const QString myName = mFieldNameEdit->text();
226 const QString featureId = mFeatureIdColumnEdit->text().isEmpty() ? QStringLiteral( DEFAULT_OGR_FID_COLUMN_TITLE ) : mFeatureIdColumnEdit->text();
227 if ( myName.compare( featureId, Qt::CaseInsensitive ) == 0 )
228 {
229 QMessageBox::critical( this, tr( "Add Field" ), tr( "The field cannot have the same name as the feature identifier." ) );
230 return;
231 }
232
233 //use userrole to avoid translated type string
234 const QString myType = mFieldTypeBox->currentData( Qt::UserRole ).toString();
235 const QString length = mFieldLengthEdit->text();
236 mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << myName << myType << length ) );
237
238 checkOk();
239
240 mFieldNameEdit->clear();
241
242 if ( !mFieldNameEdit->hasFocus() )
243 {
244 mFieldNameEdit->setFocus();
245 }
246 }
247}
248
249void QgsNewGeoPackageLayerDialog::mRemoveAttributeButton_clicked()
250{
251 delete mAttributeView->currentItem();
252
253 checkOk();
254}
255
256void QgsNewGeoPackageLayerDialog::fieldNameChanged( const QString &name )
257{
258 mAddAttributeButton->setDisabled( name.isEmpty() || ! mAttributeView->findItems( name, Qt::MatchExactly ).isEmpty() );
259}
260
261void QgsNewGeoPackageLayerDialog::selectionChanged()
262{
263 mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().isEmpty() );
264 mButtonUp->setDisabled( mAttributeView->selectedItems().isEmpty() );
265 mButtonDown->setDisabled( mAttributeView->selectedItems().isEmpty() );
266}
267
268void QgsNewGeoPackageLayerDialog::buttonBox_accepted()
269{
270 if ( apply() )
271 accept();
272}
273
274void QgsNewGeoPackageLayerDialog::buttonBox_rejected()
275{
276 reject();
277}
278
279void QgsNewGeoPackageLayerDialog::moveFieldsUp()
280{
281 int currentRow = mAttributeView->currentIndex().row();
282 if ( currentRow == 0 )
283 return;
284
285 mAttributeView->insertTopLevelItem( currentRow - 1, mAttributeView->takeTopLevelItem( currentRow ) );
286 mAttributeView->setCurrentIndex( mAttributeView->model()->index( currentRow - 1, 0 ) );
287}
288
289void QgsNewGeoPackageLayerDialog::moveFieldsDown()
290{
291 int currentRow = mAttributeView->currentIndex().row();
292 if ( currentRow == mAttributeView->topLevelItemCount() - 1 )
293 return;
294
295 mAttributeView->insertTopLevelItem( currentRow + 1, mAttributeView->takeTopLevelItem( currentRow ) );
296 mAttributeView->setCurrentIndex( mAttributeView->model()->index( currentRow + 1, 0 ) );
297}
298
299bool QgsNewGeoPackageLayerDialog::apply()
300{
301 if ( !mFieldNameEdit->text().trimmed().isEmpty() )
302 {
303 const QString currentFieldName = mFieldNameEdit->text();
304 bool currentFound = false;
305 QTreeWidgetItemIterator it( mAttributeView );
306 while ( *it )
307 {
308 QTreeWidgetItem *item = *it;
309 if ( item->text( 0 ) == currentFieldName )
310 {
311 currentFound = true;
312 break;
313 }
314 ++it;
315 }
316
317 if ( !currentFound )
318 {
319 if ( QMessageBox::question( this, windowTitle(),
320 tr( "The field “%1” has not been added to the fields list. Are you sure you want to proceed and discard this field?" ).arg( currentFieldName ),
321 QMessageBox::Ok | QMessageBox::Cancel ) != QMessageBox::Ok )
322 {
323 return false;
324 }
325 }
326 }
327
328 QString fileName( mDatabase->filePath() );
329 if ( !fileName.endsWith( QLatin1String( ".gpkg" ), Qt::CaseInsensitive ) )
330 fileName += QLatin1String( ".gpkg" );
331
332 bool createNewDb = false;
333
334 if ( QFile::exists( fileName ) )
335 {
336 bool overwrite = false;
337
338 switch ( mBehavior )
339 {
340 case Prompt:
341 {
342 QMessageBox msgBox;
343 msgBox.setIcon( QMessageBox::Question );
344 msgBox.setWindowTitle( tr( "New GeoPackage Layer" ) );
345 msgBox.setText( tr( "The File already exists. Do you want to overwrite the existing file with a new database or add a new layer to it?" ) );
346 QPushButton *overwriteButton = msgBox.addButton( tr( "Overwrite" ), QMessageBox::ActionRole );
347 QPushButton *addNewLayerButton = msgBox.addButton( tr( "Add New Layer" ), QMessageBox::ActionRole );
348 msgBox.setStandardButtons( QMessageBox::Cancel );
349 msgBox.setDefaultButton( addNewLayerButton );
350 bool cancel = false;
351 if ( property( "hideDialogs" ).toBool() )
352 {
353 overwrite = property( "question_existing_db_answer_overwrite" ).toBool();
354 if ( !overwrite )
355 cancel = !property( "question_existing_db_answer_add_new_layer" ).toBool();
356 }
357 else
358 {
359 const int ret = msgBox.exec();
360 if ( ret == QMessageBox::Cancel )
361 cancel = true;
362 if ( msgBox.clickedButton() == overwriteButton )
363 overwrite = true;
364 }
365 if ( cancel )
366 {
367 return false;
368 }
369 break;
370 }
371
372 case Overwrite:
373 overwrite = true;
374 break;
375
376 case AddNewLayer:
377 overwrite = false;
378 break;
379 }
380
381 if ( overwrite )
382 {
383 QFile( fileName ).remove();
384 createNewDb = true;
385 }
386 }
387 else
388 {
389 createNewDb = true;
390 }
391
392 OGRSFDriverH hGpkgDriver = OGRGetDriverByName( "GPKG" );
393 if ( !hGpkgDriver )
394 {
395 if ( !property( "hideDialogs" ).toBool() )
396 QMessageBox::critical( this, tr( "New GeoPackage Layer" ),
397 tr( "Layer creation failed. GeoPackage driver not found." ) );
398 return false;
399 }
400
402 if ( createNewDb )
403 {
404 hDS.reset( OGR_Dr_CreateDataSource( hGpkgDriver, fileName.toUtf8().constData(), nullptr ) );
405 if ( !hDS )
406 {
407 const QString msg( tr( "Creation of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
408 if ( !property( "hideDialogs" ).toBool() )
409 QMessageBox::critical( this, tr( "New GeoPackage Layer" ), msg );
410 return false;
411 }
412 }
413 else
414 {
415 OGRSFDriverH hDriver = nullptr;
416 hDS.reset( OGROpen( fileName.toUtf8().constData(), true, &hDriver ) );
417 if ( !hDS )
418 {
419 const QString msg( tr( "Opening of database failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
420 if ( !property( "hideDialogs" ).toBool() )
421 QMessageBox::critical( this, tr( "New GeoPackage Layer" ), msg );
422 return false;
423 }
424 if ( hDriver != hGpkgDriver )
425 {
426 const QString msg( tr( "Opening of file succeeded, but this is not a GeoPackage database." ) );
427 if ( !property( "hideDialogs" ).toBool() )
428 QMessageBox::critical( this, tr( "New GeoPackage Layer" ), msg );
429 return false;
430 }
431 }
432
433 const QString tableName( mTableNameEdit->text() );
434
435 bool overwriteTable = false;
436 if ( OGR_DS_GetLayerByName( hDS.get(), tableName.toUtf8().constData() ) )
437 {
438 if ( property( "hideDialogs" ).toBool() )
439 {
440 overwriteTable = property( "question_existing_layer_answer_overwrite" ).toBool();
441 }
442 else if ( QMessageBox::question( this, tr( "New GeoPackage Layer" ),
443 tr( "A table with the same name already exists. Do you want to overwrite it?" ),
444 QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes )
445 {
446 overwriteTable = true;
447 }
448
449 if ( !overwriteTable )
450 {
451 return false;
452 }
453 }
454
455 const QString layerIdentifier( mLayerIdentifierEdit->text() );
456 const QString layerDescription( mLayerDescriptionEdit->text() );
457
458 OGRwkbGeometryType wkbType = static_cast<OGRwkbGeometryType>
459 ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
460
461 // z-coordinate & m-value.
462 if ( mGeometryWithZCheckBox->isChecked() )
463 wkbType = OGR_GT_SetZ( wkbType );
464
465 if ( mGeometryWithMCheckBox->isChecked() )
466 wkbType = OGR_GT_SetM( wkbType );
467
468 OGRSpatialReferenceH hSRS = nullptr;
469 // consider spatial reference system of the layer
470 const QgsCoordinateReferenceSystem srs = mCrsSelector->crs();
471 if ( wkbType != wkbNone && srs.isValid() )
472 {
474 }
475
476 // Set options
477 char **options = nullptr;
478
479 if ( overwriteTable )
480 options = CSLSetNameValue( options, "OVERWRITE", "YES" );
481 if ( !layerIdentifier.isEmpty() )
482 options = CSLSetNameValue( options, "IDENTIFIER", layerIdentifier.toUtf8().constData() );
483 if ( !layerDescription.isEmpty() )
484 options = CSLSetNameValue( options, "DESCRIPTION", layerDescription.toUtf8().constData() );
485
486 const QString featureId( mFeatureIdColumnEdit->text() );
487 if ( !featureId.isEmpty() )
488 options = CSLSetNameValue( options, "FID", featureId.toUtf8().constData() );
489
490 const QString geometryColumn( mGeometryColumnEdit->text() );
491 if ( wkbType != wkbNone && !geometryColumn.isEmpty() )
492 options = CSLSetNameValue( options, "GEOMETRY_COLUMN", geometryColumn.toUtf8().constData() );
493
494 if ( wkbType != wkbNone )
495 options = CSLSetNameValue( options, "SPATIAL_INDEX", mCheckBoxCreateSpatialIndex->isChecked() ? "YES" : "NO" );
496
497 OGRLayerH hLayer = OGR_DS_CreateLayer( hDS.get(), tableName.toUtf8().constData(), hSRS, wkbType, options );
498 CSLDestroy( options );
499 if ( hSRS )
500 OSRRelease( hSRS );
501 if ( !hLayer )
502 {
503 const QString msg( tr( "Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
504 if ( !property( "hideDialogs" ).toBool() )
505 QMessageBox::critical( this, tr( "New GeoPackage Layer" ), msg );
506 return false;
507 }
508
509 QTreeWidgetItemIterator it( mAttributeView );
510 while ( *it )
511 {
512 const QString fieldName( ( *it )->text( 0 ) );
513 const QString fieldType( ( *it )->text( 1 ) );
514 const QString fieldWidth( ( *it )->text( 2 ) );
515
516 OGRFieldType ogrType( OFTString );
517 OGRFieldSubType ogrSubType = OFSTNone;
518 if ( fieldType == QLatin1String( "text" ) )
519 ogrType = OFTString;
520 else if ( fieldType == QLatin1String( "integer" ) )
521 ogrType = OFTInteger;
522 else if ( fieldType == QLatin1String( "integer64" ) )
523 ogrType = OFTInteger64;
524 else if ( fieldType == QLatin1String( "real" ) )
525 ogrType = OFTReal;
526 else if ( fieldType == QLatin1String( "date" ) )
527 ogrType = OFTDate;
528 else if ( fieldType == QLatin1String( "datetime" ) )
529 ogrType = OFTDateTime;
530 else if ( fieldType == QLatin1String( "bool" ) )
531 {
532 ogrType = OFTInteger;
533 ogrSubType = OFSTBoolean;
534 }
535 else if ( fieldType == QLatin1String( "binary" ) )
536 ogrType = OFTBinary;
537 else if ( fieldType == QLatin1String( "json" ) )
538 {
539 ogrType = OFTString;
540 ogrSubType = OFSTJSON;
541 }
542
543 const int ogrWidth = fieldWidth.toInt();
544
545 const gdal::ogr_field_def_unique_ptr fld( OGR_Fld_Create( fieldName.toUtf8().constData(), ogrType ) );
546 if ( ogrSubType != OFSTNone )
547 OGR_Fld_SetSubType( fld.get(), ogrSubType );
548
549 if ( ogrType != OFTBinary )
550 OGR_Fld_SetWidth( fld.get(), ogrWidth );
551
552 if ( OGR_L_CreateField( hLayer, fld.get(), true ) != OGRERR_NONE )
553 {
554 if ( !property( "hideDialogs" ).toBool() )
555 {
556 QMessageBox::critical( this, tr( "New GeoPackage Layer" ),
557 tr( "Creation of field %1 failed (OGR error: %2)" )
558 .arg( fieldName, QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
559 }
560 return false;
561 }
562
563 ++it;
564 }
565
566 // In GDAL >= 2.0, the driver implements a deferred creation strategy, so
567 // issue a command that will force table creation
568 CPLErrorReset();
569 OGR_L_ResetReading( hLayer );
570 if ( CPLGetLastErrorType() != CE_None )
571 {
572 const QString msg( tr( "Creation of layer failed (OGR error: %1)" ).arg( QString::fromUtf8( CPLGetLastErrorMsg() ) ) );
573 if ( !property( "hideDialogs" ).toBool() )
574 QMessageBox::critical( this, tr( "New GeoPackage Layer" ), msg );
575 return false;
576 }
577 hDS.reset();
578
579 const QString uri( QStringLiteral( "%1|layername=%2" ).arg( fileName, tableName ) );
580 const QString userVisiblelayerName( layerIdentifier.isEmpty() ? tableName : layerIdentifier );
582 std::unique_ptr< QgsVectorLayer > layer = std::make_unique< QgsVectorLayer >( uri, userVisiblelayerName, QStringLiteral( "ogr" ), layerOptions );
583 if ( layer->isValid() )
584 {
585 if ( mAddToProject )
586 {
587 // register this layer with the central layers registry
588 QList<QgsMapLayer *> myList;
589 myList << layer.release();
590 //addMapLayers returns a list of all successfully added layers
591 //so we compare that to our original list.
592 if ( myList == QgsProject::instance()->addMapLayers( myList ) )
593 return true;
594 }
595 else
596 {
597 return true;
598 }
599 }
600 else
601 {
602 if ( !property( "hideDialogs" ).toBool() )
603 QMessageBox::critical( this, tr( "New GeoPackage Layer" ), tr( "%1 is an invalid layer and cannot be loaded." ).arg( tableName ) );
604 }
605
606 return false;
607}
608
610{
611 mBehavior = behavior;
612}
613
615{
616 mAddToProject = addToProject;
617}
618
619void QgsNewGeoPackageLayerDialog::showHelp()
620{
621 QgsHelp::openHelp( QStringLiteral( "managing_data_source/create_layers.html#creating-a-new-geopackage-layer" ) );
622}
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:256
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
static QIcon iconForFieldType(QMetaType::Type type, QMetaType::Type subType=QMetaType::Type::UnknownType, const QString &typeString=QString())
Returns an icon corresponding to a field type.
@ SaveFile
Select a single new or pre-existing file.
void fileChanged(const QString &path)
Emitted whenever the current file or directory path is changed.
static void enableAutoGeometryRestore(QWidget *widget, const QString &key=QString())
Register the widget to allow its position to be automatically saved and restored when open and closed...
Definition qgsgui.cpp:209
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition qgshelp.cpp:39
static QIcon iconForWkbType(Qgis::WkbType type)
Returns the icon for a vector layer whose geometry type is provided.
OverwriteBehavior
Behavior to use when an existing geopackage already exists.
@ AddNewLayer
Keep existing contents and add new layer.
@ Overwrite
Overwrite whole geopackage.
void setAddToProject(bool addToProject)
Sets whether a newly created layer should automatically be added to the current project.
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the crs value for the new layer in the dialog.
void lockDatabasePath()
Sets the database path widgets to a locked and read-only mode.
QgsNewGeoPackageLayerDialog(QWidget *parent=nullptr, Qt::WindowFlags fl=QgsGuiUtils::ModalDialogFlags)
Constructor.
void setOverwriteBehavior(OverwriteBehavior behavior)
Sets the behavior to use when a path to an existing geopackage file is used.
static Qgis::WkbType ogrGeometryTypeToQgsWkbType(OGRwkbGeometryType ogrGeomType)
Converts a OGRwkbGeometryType to QgsWkbTypes::Type.
static OGRSpatialReferenceH crsToOGRSpatialReference(const QgsCoordinateReferenceSystem &crs)
Returns a OGRSpatialReferenceH corresponding to the specified crs object.
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsCoordinateTransformContext transformContext
Definition qgsproject.h:113
A model containing registered connection names for a specific data provider.
This class is a composition of two QSettings instances:
Definition qgssettings.h:64
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
static QString typeToDisplayString(QMetaType::Type type, QMetaType::Type subType=QMetaType::Type::UnknownType)
Returns a user-friendly translated string representing a QVariant type.
static QString translatedDisplayString(Qgis::WkbType type)
Returns a translated display string type for a WKB type, e.g., the geometry name used in WKT geometry...
std::unique_ptr< std::remove_pointer< OGRDataSourceH >::type, OGRDataSourceDeleter > ogr_datasource_unique_ptr
Scoped OGR data source.
std::unique_ptr< std::remove_pointer< OGRFieldDefnH >::type, OGRFldDeleter > ogr_field_def_unique_ptr
Scoped OGR field definition.
void * OGRSpatialReferenceH
#define DEFAULT_OGR_FID_COLUMN_TITLE
const QgsCoordinateReferenceSystem & crs
Setting options for loading vector layers.