QGIS API Documentation  3.2.0-Bonn (bc43194)
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 
29 #include <QPushButton>
30 #include <QComboBox>
31 #include <QLibrary>
32 #include <QFileDialog>
33 
34 
35 QgsNewVectorLayerDialog::QgsNewVectorLayerDialog( QWidget *parent, Qt::WindowFlags fl )
36  : QDialog( parent, fl )
37 {
38  setupUi( this );
39 
40  connect( mAddAttributeButton, &QToolButton::clicked, this, &QgsNewVectorLayerDialog::mAddAttributeButton_clicked );
41  connect( mRemoveAttributeButton, &QToolButton::clicked, this, &QgsNewVectorLayerDialog::mRemoveAttributeButton_clicked );
42  connect( mFileFormatComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsNewVectorLayerDialog::mFileFormatComboBox_currentIndexChanged );
43  connect( mTypeBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsNewVectorLayerDialog::mTypeBox_currentIndexChanged );
44  connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsNewVectorLayerDialog::showHelp );
45 
46  QgsSettings settings;
47  restoreGeometry( settings.value( QStringLiteral( "Windows/NewVectorLayer/geometry" ) ).toByteArray() );
48 
49  mAddAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionNewAttribute.svg" ) ) );
50  mRemoveAttributeButton->setIcon( QgsApplication::getThemeIcon( QStringLiteral( "/mActionDeleteAttribute.svg" ) ) );
51 
52  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldText.svg" ) ), tr( "Text data" ), "String" );
53  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldInteger.svg" ) ), tr( "Whole number" ), "Integer" );
54  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldFloat.svg" ) ), tr( "Decimal number" ), "Real" );
55  mTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconFieldDate.svg" ) ), tr( "Date" ), "Date" );
56 
57  mWidth->setValidator( new QIntValidator( 1, 255, this ) );
58  mPrecision->setValidator( new QIntValidator( 0, 15, this ) );
59 
60  mGeometryTypeBox->addItem( QgsApplication::getThemeIcon( QStringLiteral( "/mIconPointLayer.svg" ) ), tr( "Point" ), QgsWkbTypes::Point );
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" ) << QLatin1String( "" ) ) );
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->setDialogTitle( tr( "Save Layer As" ) );
108  mFileName->setDefaultRoot( settings.value( QStringLiteral( "UI/lastVectorFileFilterDir" ), QDir::homePath() ).toString() );
109  connect( mFileName, &QgsFileWidget::fileChanged, this, [ = ]
110  {
111  QgsSettings settings;
112  QFileInfo tmplFileInfo( mFileName->filePath() );
113  settings.setValue( QStringLiteral( "UI/lastVectorFileFilterDir" ), tmplFileInfo.absolutePath() );
114  checkOk();
115  } );
116 }
117 
119 {
120  QgsSettings settings;
121  settings.setValue( QStringLiteral( "Windows/NewVectorLayer/geometry" ), saveGeometry() );
122 }
123 
124 void QgsNewVectorLayerDialog::mFileFormatComboBox_currentIndexChanged( int index )
125 {
126  Q_UNUSED( index );
127  if ( mFileFormatComboBox->currentText() == tr( "ESRI Shapefile" ) )
128  mNameEdit->setMaxLength( 10 );
129  else
130  mNameEdit->setMaxLength( 32767 );
131 }
132 
133 void QgsNewVectorLayerDialog::mTypeBox_currentIndexChanged( int index )
134 {
135  // FIXME: sync with providers/ogr/qgsogrprovider.cpp
136  switch ( index )
137  {
138  case 0: // Text data
139  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 255 )
140  mWidth->setText( QStringLiteral( "80" ) );
141  mPrecision->setEnabled( false );
142  mWidth->setValidator( new QIntValidator( 1, 255, this ) );
143  break;
144 
145  case 1: // Whole number
146  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 10 )
147  mWidth->setText( QStringLiteral( "10" ) );
148  mPrecision->setEnabled( false );
149  mWidth->setValidator( new QIntValidator( 1, 10, this ) );
150  break;
151 
152  case 2: // Decimal number
153  if ( mWidth->text().toInt() < 1 || mWidth->text().toInt() > 20 )
154  mWidth->setText( QStringLiteral( "20" ) );
155  mPrecision->setEnabled( true );
156  mWidth->setValidator( new QIntValidator( 1, 20, this ) );
157  break;
158 
159  default:
160  QgsDebugMsg( "unexpected index" );
161  break;
162  }
163 }
164 
166 {
168  wkbType = static_cast<QgsWkbTypes::Type>
169  ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );
170 
171  if ( mGeometryWithZCheckBox->isChecked() )
172  wkbType = QgsWkbTypes::addZ( wkbType );
173 
174  if ( mGeometryWithMCheckBox->isChecked() )
175  wkbType = QgsWkbTypes::addM( wkbType );
176 
177  return wkbType;
178 }
179 
181 {
182  return mCrsSelector->crs();
183 }
184 
186 {
187  mCrsSelector->setCrs( crs );
188 }
189 
190 void QgsNewVectorLayerDialog::mAddAttributeButton_clicked()
191 {
192  QString myName = mNameEdit->text();
193  QString myWidth = mWidth->text();
194  QString myPrecision = mPrecision->isEnabled() ? mPrecision->text() : QLatin1String( "" );
195  //use userrole to avoid translated type string
196  QString myType = mTypeBox->currentData( Qt::UserRole ).toString();
197  mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << myName << myType << myWidth << myPrecision ) );
198  checkOk();
199  mNameEdit->clear();
200 }
201 
202 void QgsNewVectorLayerDialog::mRemoveAttributeButton_clicked()
203 {
204  delete mAttributeView->currentItem();
205  checkOk();
206 }
207 
208 void QgsNewVectorLayerDialog::attributes( QList< QPair<QString, QString> > &at ) const
209 {
210  QTreeWidgetItemIterator it( mAttributeView );
211  while ( *it )
212  {
213  QTreeWidgetItem *item = *it;
214  QString type = QStringLiteral( "%1;%2;%3" ).arg( item->text( 1 ), item->text( 2 ), item->text( 3 ) );
215  at.push_back( qMakePair( item->text( 0 ), type ) );
216  QgsDebugMsg( QString( "appending %1//%2" ).arg( item->text( 0 ), type ) );
217  ++it;
218  }
219 }
220 
222 {
223  //use userrole to avoid translated type string
224  QString myType = mFileFormatComboBox->currentData( Qt::UserRole ).toString();
225  return myType;
226 }
227 
229 {
230  return mFileEncoding->currentText();
231 }
232 
233 void QgsNewVectorLayerDialog::nameChanged( const QString &name )
234 {
235  mAddAttributeButton->setDisabled( name.isEmpty() || !mAttributeView->findItems( name, Qt::MatchExactly ).isEmpty() );
236 }
237 
238 void QgsNewVectorLayerDialog::selectionChanged()
239 {
240  mRemoveAttributeButton->setDisabled( mAttributeView->selectedItems().isEmpty() );
241 }
242 
244 {
245  return mFileName->filePath();
246 }
247 
248 void QgsNewVectorLayerDialog::checkOk()
249 {
250  bool ok = ( !mFileName->filePath().isEmpty() && mAttributeView->topLevelItemCount() > 0 );
251  mOkButton->setEnabled( ok );
252 }
253 
254 // this is static
255 QString QgsNewVectorLayerDialog::runAndCreateLayer( QWidget *parent, QString *pEnc, const QgsCoordinateReferenceSystem &crs )
256 {
257  QgsNewVectorLayerDialog geomDialog( parent );
258  geomDialog.setCrs( crs );
259  if ( geomDialog.exec() == QDialog::Rejected )
260  {
261  return QLatin1String( "" );
262  }
263 
264  QgsWkbTypes::Type geometrytype = geomDialog.selectedType();
265  QString fileformat = geomDialog.selectedFileFormat();
266  QString enc = geomDialog.selectedFileEncoding();
267  QgsDebugMsg( QString( "New file format will be: %1" ).arg( fileformat ) );
268 
269  QList< QPair<QString, QString> > attributes;
270  geomDialog.attributes( attributes );
271 
272  QgsSettings settings;
273  QString fileName = geomDialog.filename();
274  if ( fileformat == QLatin1String( "ESRI Shapefile" ) && !fileName.endsWith( QLatin1String( ".shp" ), Qt::CaseInsensitive ) )
275  fileName += QLatin1String( ".shp" );
276 
277  settings.setValue( QStringLiteral( "UI/lastVectorFileFilterDir" ), QFileInfo( fileName ).absolutePath() );
278  settings.setValue( QStringLiteral( "UI/encoding" ), enc );
279 
280  //try to create the new layer with OGRProvider instead of QgsVectorFileWriter
282  QString ogrlib = pReg->library( QStringLiteral( "ogr" ) );
283  // load the data provider
284  QLibrary *myLib = new QLibrary( ogrlib );
285  bool loaded = myLib->load();
286  if ( loaded )
287  {
288  QgsDebugMsg( "ogr provider loaded" );
289 
290  typedef bool ( *createEmptyDataSourceProc )( const QString &, const QString &, const QString &, QgsWkbTypes::Type,
291  const QList< QPair<QString, QString> > &, const QgsCoordinateReferenceSystem & );
292  createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( myLib->resolve( "createEmptyDataSource" ) );
293  if ( createEmptyDataSource )
294  {
295  if ( geometrytype != QgsWkbTypes::Unknown )
296  {
297  QgsCoordinateReferenceSystem srs = geomDialog.crs();
298  if ( !createEmptyDataSource( fileName, fileformat, enc, geometrytype, attributes, srs ) )
299  {
300  return QString();
301  }
302  }
303  else
304  {
305  QgsDebugMsg( "geometry type not recognised" );
306  return QString();
307  }
308  }
309  else
310  {
311  QgsDebugMsg( "Resolving newEmptyDataSource(...) failed" );
312  return QString();
313  }
314  }
315 
316  if ( pEnc )
317  *pEnc = enc;
318 
319  return fileName;
320 }
321 
322 void QgsNewVectorLayerDialog::showHelp()
323 {
324  QgsHelp::openHelp( QStringLiteral( "managing_data_source/create_layers.html#creating-a-new-shapefile-layer" ) );
325 }
QString selectedFileEncoding() const
Returns the file format for storage.
void fileChanged(const QString &)
emitted as soon as the current file or directory is changed
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
QString library(const QString &providerKey) const
Returns path for the library of the provider.
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.
void saveGeometry(QWidget *widget, const QString &keyName)
Save the wigget geometry into settings.
bool restoreGeometry(QWidget *widget, const QString &keyName)
Restore the wigget geometry from settings.
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:67
static QgsProviderRegistry * instance(const QString &pluginPath=QString())
Means of accessing canonical single instance.
static Type addM(Type type)
Adds the m dimension to a WKB type and returns the new type.
Definition: qgswkbtypes.h:889
QString filename() const
Returns the name for the new layer.
static Type addZ(Type type)
Adds the z dimension to a WKB type and returns the new type.
Definition: qgswkbtypes.h:864
#define cast_to_fptr(f)
Definition: qgis.h:170
static QString runAndCreateLayer(QWidget *parent=nullptr, QString *enc=nullptr, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem())
Runs the dialog and creates a layer matching the dialog parameters.
void setCrs(const QgsCoordinateReferenceSystem &crs)
Sets the crs value for the new layer in the dialog.
A registry / canonical manager of data providers.
QgsNewVectorLayerDialog(QWidget *parent=nullptr, Qt::WindowFlags fl=QgsGuiUtils::ModalDialogFlags)
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 multiple files.
Definition: qgsfilewidget.h:68
static void openHelp(const QString &key)
Opens help topic for the given help key using default system web browser.
Definition: qgshelp.cpp:35
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.