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