QGIS API Documentation  3.10.0-A Coruña (6c816b4204)
qgsnewvectorlayerdialog.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsnewvectorlayerdialog.cpp - description
3  -------------------
4  begin : October 2004
5  copyright : (C) 2004 by Marco Hugentobler
6  email : [email protected]
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
19 #include "qgsapplication.h"
20 #include "qgsfilewidget.h"
21 #include "qgis.h"
22 #include "qgslogger.h"
24 #include "qgsproviderregistry.h"
25 #include "qgsvectordataprovider.h"
26 #include "qgsvectorfilewriter.h"
27 #include "qgssettings.h"
28 #include "qgsogrprovider.h"
29 #include "qgsgui.h"
30 
31 #include <QPushButton>
32 #include <QComboBox>
33 #include <QFileDialog>
34 #include <QMessageBox>
35 
36 QgsNewVectorLayerDialog::QgsNewVectorLayerDialog( QWidget *parent, Qt::WindowFlags fl )
37  : QDialog( parent, fl )
38 {
39  setupUi( this );
41 
42  connect( mAddAttributeButton, &QToolButton::clicked, this, &QgsNewVectorLayerDialog::mAddAttributeButton_clicked );
43  connect( mRemoveAttributeButton, &QToolButton::clicked, this, &QgsNewVectorLayerDialog::mRemoveAttributeButton_clicked );
44  connect( mFileFormatComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsNewVectorLayerDialog::mFileFormatComboBox_currentIndexChanged );
45  connect( mTypeBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsNewVectorLayerDialog::mTypeBox_currentIndexChanged );
46  connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsNewVectorLayerDialog::showHelp );
47 
48  mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) );
49  mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) );
50 
51  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldText.svg" ) ), tr( "Text data" ), "String" );
52  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldInteger.svg" ) ), tr( "Whole number" ), "Integer" );
53  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldFloat.svg" ) ), tr( "Decimal number" ), "Real" );
54  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldDate.svg" ) ), tr( "Date" ), "Date" );
55 
56  mWidth->setValidator( new QIntValidator( 1, 255, this ) );
57  mPrecision->setValidator( new QIntValidator( 0, 15, this ) );
58 
59  mGeometryTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPointLayer.svg" ) ), tr( "Point" ), QgsWkbTypes::Point );
60  mGeometryTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPointLayer.svg" ) ), tr( "MultiPoint" ), QgsWkbTypes::MultiPoint );
61  mGeometryTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconLineLayer.svg" ) ), tr( "Line" ), QgsWkbTypes::LineString );
62  mGeometryTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPolygonLayer.svg" ) ), tr( "Polygon" ), QgsWkbTypes::Polygon );
63 
64  mOkButton = buttonBox->button( QDialogButtonBox::Ok );
65  mOkButton->setEnabled( false );
66 
67  mFileFormatComboBox->addItem( tr( "ESRI Shapefile" ), "ESRI Shapefile" );
68 #if 0
69  // Disabled until provider properly supports editing the created file formats
70  // When enabling this, adapt the window-title of the dialog and the title of all actions showing this dialog.
71  mFileFormatComboBox->addItem( tr( "Comma Separated Value" ), "Comma Separated Value" );
72  mFileFormatComboBox->addItem( tr( "GML" ), "GML" );
73  mFileFormatComboBox->addItem( tr( "Mapinfo File" ), "Mapinfo File" );
74 #endif
75  if ( mFileFormatComboBox->count() == 1 )
76  {
77  mFileFormatComboBox->setVisible( false );
78  mFileFormatLabel->setVisible( false );
79  }
80 
81  mFileFormatComboBox->setCurrentIndex( 0 );
82 
83  mFileEncoding->addItems( QgsVectorDataProvider::availableEncodings() );
84 
85  // Use default encoding if none supplied
86  QString enc = QgsSettings().value( QStringLiteral( "/UI/encoding" ), "System" ).toString();
87 
88  // The specified decoding is added if not existing already, and then set current.
89  // This should select it.
90  int encindex = mFileEncoding->findText( enc );
91  if ( encindex < 0 )
92  {
93  mFileEncoding->insertItem( 0, enc );
94  encindex = 0;
95  }
96  mFileEncoding->setCurrentIndex( encindex );
97 
98  mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << QStringLiteral( "id" ) << QStringLiteral( "Integer" ) << QStringLiteral( "10" ) << QString() ) );
99  connect( mNameEdit, &QLineEdit::textChanged, this, &QgsNewVectorLayerDialog::nameChanged );
100  connect( mAttributeView, &QTreeWidget::itemSelectionChanged, this, &QgsNewVectorLayerDialog::selectionChanged );
101 
102  mAddAttributeButton->setEnabled( false );
103  mRemoveAttributeButton->setEnabled( false );
104 
105  mFileName->setStorageMode( QgsFileWidget::SaveFile );
106  mFileName->setFilter( QgsVectorFileWriter::filterForDriver( mFileFormatComboBox->currentData( Qt::UserRole ).toString() ) );
107  mFileName->setConfirmOverwrite( false );
108  mFileName->setDialogTitle( tr( "Save Layer As" ) );
109  QgsSettings settings;
110  mFileName->setDefaultRoot( settings.value( QStringLiteral( "UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() );
111  connect( mFileName, &QgsFileWidget::fileChanged, this, [ = ]
112  {
113  QgsSettings settings;
114  QFileInfo tmplFileInfo( mFileName->filePath() );
115  settings.setValue( QStringLiteral( "UI/lastVectorFileFilterDir" ), tmplFileInfo.absolutePath() );
116  checkOk();
117  } );
118 }
119 
120 void QgsNewVectorLayerDialog::mFileFormatComboBox_currentIndexChanged( int index )
121 {
122  Q_UNUSED( index )
123  if ( mFileFormatComboBox->currentText() == tr( "ESRI Shapefile" ) )
124  mNameEdit->setMaxLength( 10 );
125  else
126  mNameEdit->setMaxLength( 32767 );
127 }
128 
129 void QgsNewVectorLayerDialog::mTypeBox_currentIndexChanged( int index )
130 {
131  // FIXME: sync with providers/ogr/qgsogrprovider.cpp
132  switch ( index )
133  {
134  case 0: // Text data
135  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 255 )
136  mWidth->setText( QStringLiteral( "80" ) );
137  mPrecision->setEnabled( false );
138  mWidth->setValidator( new QIntValidator( 1, 255, this ) );
139  break;
140 
141  case 1: // Whole number
142  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 10 )
143  mWidth->setText( QStringLiteral( "10" ) );
144  mPrecision->setEnabled( false );
145  mWidth->setValidator( new QIntValidator( 1, 10, this ) );
146  break;
147 
148  case 2: // Decimal number
149  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 20 )
150  mWidth->setText( QStringLiteral( "20" ) );
151  mPrecision->setEnabled( true );
152  mWidth->setValidator( new QIntValidator( 1, 20, this ) );
153  break;
154 
155  default:
156  QgsDebugMsg( QStringLiteral( "unexpected index" ) );
157  break;
158  }
159 }
160 
162 {
164  wkbType = static_cast<QgsWkbTypes::Type>
165  ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
166 
167  if ( mGeometryWithZRadioButton->isChecked() )
168  wkbType = QgsWkbTypes::addZ( wkbType );
169 
170  if ( mGeometryWithMRadioButton->isChecked() )
171  wkbType = QgsWkbTypes::addM( wkbType );
172 
173  return wkbType;
174 }
175 
177 {
178  return mCrsSelector->crs();
179 }
180 
182 {
183  mCrsSelector->setCrs( crs );
184 }
185 
186 void QgsNewVectorLayerDialog::mAddAttributeButton_clicked()
187 {
188  QString myName = mNameEdit->text();
189  QString myWidth = mWidth->text();
190  QString myPrecision = mPrecision->isEnabled() ? mPrecision->text() : QString();
191  //use userrole to avoid translated type string
192  QString myType = mTypeBox->currentData( Qt::UserRole ).toString();
193  mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << myName << myType << myWidth << myPrecision ) );
194  checkOk();
195  mNameEdit->clear();
196 }
197 
198 void QgsNewVectorLayerDialog::mRemoveAttributeButton_clicked()
199 {
200  delete mAttributeView->currentItem();
201  checkOk();
202 }
203 
204 void QgsNewVectorLayerDialog::attributes( QList< QPair<QString, QString> > &at ) const
205 {
206  QTreeWidgetItemIterator it( mAttributeView );
207  while ( *it )
208  {
209  QTreeWidgetItem *item = *it;
210  QString type = QStringLiteral( "%1;%2;%3" ).arg( item->text( 1 ), item->text( 2 ), item->text( 3 ) );
211  at.push_back( qMakePair( item->text( 0 ), type ) );
212  QgsDebugMsg( QStringLiteral( "appending %1//%2" ).arg( item->text( 0 ), type ) );
213  ++it;
214  }
215 }
216 
218 {
219  //use userrole to avoid translated type string
220  QString myType = mFileFormatComboBox->currentData( Qt::UserRole ).toString();
221  return myType;
222 }
223 
225 {
226  return mFileEncoding->currentText();
227 }
228 
229 void QgsNewVectorLayerDialog::nameChanged( const QString &name )
230 {
231  mAddAttributeButton->setDisabled( name.isEmpty() || !mAttributeView->findItems( name, Qt::MatchExactly ).isEmpty() );
232 }
233 
234 void QgsNewVectorLayerDialog::selectionChanged()
235 {
236  mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().isEmpty() );
237 }
238 
240 {
241  return mFileName->filePath();
242 }
243 
245 {
246  mFileName->setFilePath( filename );
247 }
248 
249 void QgsNewVectorLayerDialog::checkOk()
250 {
251  bool ok = ( !mFileName->filePath().isEmpty() && mAttributeView->topLevelItemCount() > 0 );
252  mOkButton->setEnabled( ok );
253 }
254 
255 // this is static
256 QString QgsNewVectorLayerDialog::runAndCreateLayer( QWidget *parent, QString *pEnc, const QgsCoordinateReferenceSystem &crs, const QString &initialPath )
257 {
258  QString error;
259  QString res = execAndCreateLayer( error, parent, initialPath, pEnc, crs );
260  if ( res.isEmpty() && error.isEmpty() )
261  res = QString( "" ); // maintain gross earlier API compatibility
262  return res;
263 }
264 
265 QString QgsNewVectorLayerDialog::execAndCreateLayer( QString &errorMessage, QWidget *parent, const QString &initialPath, QString *encoding, const QgsCoordinateReferenceSystem &crs )
266 {
267  errorMessage.clear();
268  QgsNewVectorLayerDialog geomDialog( parent );
269  geomDialog.setCrs( crs );
270  if ( !initialPath.isEmpty() )
271  geomDialog.setFilename( initialPath );
272  if ( geomDialog.exec() == QDialog::Rejected )
273  {
274  return QString();
275  }
276 
277  if ( QFile::exists( geomDialog.filename() ) && QMessageBox::warning( parent, tr( "New ShapeFile Layer" ), tr( "The layer already exists. Are you sure you want to overwrite the existing file?" ),
278  QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel ) != QMessageBox::Yes )
279  return QString();
280 
281  QgsWkbTypes::Type geometrytype = geomDialog.selectedType();
282  QString fileformat = geomDialog.selectedFileFormat();
283  QString enc = geomDialog.selectedFileEncoding();
284  QgsDebugMsg( QStringLiteral( "New file format will be: %1" ).arg( fileformat ) );
285 
286  QList< QPair<QString, QString> > attributes;
287  geomDialog.attributes( attributes );
288 
289  QgsSettings settings;
290  QString fileName = geomDialog.filename();
291  if ( fileformat == QLatin1String( "ESRI Shapefile" ) && !fileName.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) )
292  fileName += QLatin1String( ".shp" );
293 
294  settings.setValue( QStringLiteral( "UI/lastVectorFileFilterDir" ), QFileInfo( fileName ).absolutePath() );
295  settings.setValue( QStringLiteral( "UI/encoding" ), enc );
296 
297  //try to create the new layer with OGRProvider instead of QgsVectorFileWriter
298  QString createError;
299  if ( geometrytype != QgsWkbTypes::Unknown )
300  {
301  QgsCoordinateReferenceSystem srs = geomDialog.crs();
302  bool success = QgsOgrProviderUtils::createEmptyDataSource( fileName, fileformat, enc, geometrytype, attributes, srs, errorMessage );
303  if ( !success )
304  {
305  return QString();
306  }
307  }
308  else
309  {
310  errorMessage = QObject::tr( "Geometry type not recognised" );
311  QgsDebugMsg( errorMessage );
312  return QString();
313  }
314 
315  if ( encoding )
316  *encoding = enc;
317 
318  return fileName;
319 }
320 
321 void QgsNewVectorLayerDialog::showHelp()
322 {
323  QgsHelp::openHelp( QStringLiteral( "managing_data_source/create_layers.html#creating-a-new-shapefile-layer" ) );
324 }
QString selectedFileEncoding() const
Returns the file format for storage.
QString selectedFileFormat() const
Returns the file format for storage.
This class is a composition of two QSettings instances:
Definition: qgssettings.h:58
QVariant value(const QString &key, const QVariant &defaultValue=QVariant(), Section section=NoSection) const
Returns the value for setting key.
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
static QIcon getThemeIcon(const QString &name)
Helper to get a theme icon.
void attributes(QList< QPair< QString, QString > > &at) const
Appends the chosen attribute names and types to at.
static QgsGui * instance()
Returns a pointer to the singleton instance.
Definition: qgsgui.cpp:61
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:68
static Type addM(Type type)
Adds the m dimension to a WKB type and returns the new type.
Definition: qgswkbtypes.h:1038
QString filename() const
Returns the name for the new layer.
void fileChanged(const QString &path)
Emitted whenever the current file or directory path is changed.
void setFilename(const QString &filename)
Sets the initial file name to show in the dialog.
static Type addZ(Type type)
Adds the z dimension to a WKB type and returns the new type.
Definition: qgswkbtypes.h:1013
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the crs value for the new layer in the dialog.
static QString execAndCreateLayer(QString &errorMessage, QWidget *parent=nullptr, const QString &initialPath=QString(), QString *encoding=nullptr, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem())
Runs the dialog and creates a layer matching the dialog parameters.
QgsNewVectorLayerDialog(QWidget *parent=nullptr, Qt::WindowFlags fl=QgsGuiUtils::ModalDialogFlags)
New dialog constructor.
void setValue(const QString &key, const QVariant &value, QgsSettings::Section section=QgsSettings::NoSection)
Sets the value of setting key to value.
QgsCoordinateReferenceSystem crs() const
Returns the selected CRS for the new layer.
This class represents a coordinate reference system (CRS).
Select a single new or pre-existing file.
Definition: qgsfilewidget.h:68
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:127
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition: qgshelp.cpp:36
static Q_DECL_DEPRECATED QString runAndCreateLayer(QWidget *parent=nullptr, QString *enc=nullptr, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), const QString &initialPath=QString())
Runs the dialog and creates a layer matching the dialog parameters.
QgsWkbTypes::Type selectedType() const
Returns the selected geometry type.
static QString filterForDriver(const QString &driverName)
Creates a filter for an OGR driver key.
static QStringList availableEncodings()
Returns a list of available encodings.