Esempio n. 1
0
// Slot called when the menu item is triggered
void SqlAnywhere::addSqlAnywhereLayer()
{
  QgsMapCanvas *mMapCanvas = mQGisIface->mapCanvas();
  if ( mMapCanvas && mMapCanvas->isDrawing() )
  {
    return;
  }

  // show the data source dialog
  SaSourceSelect *dbs = new SaSourceSelect( mQGisIface->mainWindow() );

  mMapCanvas->freeze();

  if ( dbs->exec() )
  {
    // add files to the map canvas
    QStringList tables = dbs->selectedTables();
    SaDebugMsg( "Selected tables:\n" + tables.join( "\n" ) + "\n\n" );

    QApplication::setOverrideCursor( Qt::WaitCursor );

    // retrieve database connection string
    QString connectionInfo = dbs->connectionInfo();

    // create a new map layer for each selected table and register it
    for ( QStringList::Iterator it = tables.begin() ; it != tables.end() ; it++ )
    {
      // create the layer
      SaDebugMsg( "Creating layer " + *it );
      SaLayer *layer = new SaLayer( connectionInfo + " " + *it, *it );
      if ( layer->isValid() )
      {
        // set initial layer name to table name
        SaDebugMsg( "Beautifying layer name.  old: " + layer->name() );

        QgsDataSourceURI layerUri = QgsDataSourceURI( *it );
        QString newName = QString( "%1 (%2)" )
                          .arg( layerUri.table() )
                          .arg( layerUri.geometryColumn() );
        if ( QgsMapLayerRegistry::instance()->mapLayers().contains( newName ) )
        {
          newName = QString( "%1.%2 (%3)" )
                    .arg( layerUri.schema() )
                    .arg( layerUri.table() )
                    .arg( layerUri.geometryColumn() );

          if ( QgsMapLayerRegistry::instance()->mapLayers().contains( newName ) )
          {
            // give up and revert to original name
            newName = layer->name();
          }
        }
        layer->setLayerName( newName );
        SaDebugMsg( "Beautifying layer name.  new: " + layer->name() );

        // register this layer with the central layers registry
        QgsMapLayerRegistry::instance()->addMapLayer(( QgsVectorLayer* )layer );
      }
      else
      {
        SaDebugMsg(( *it ) + " is an invalid layer - not loaded" );
        QMessageBox::critical( mQGisIface->mainWindow(), tr( "Invalid Layer" ), tr( "%1 is an invalid layer and cannot be loaded." ).arg( *it ) );
        delete layer;
      }
    }

    QApplication::restoreOverrideCursor();

    (( QMainWindow * ) mQGisIface->mainWindow() )->statusBar()->showMessage( mMapCanvas->extent().toString( 2 ) );
  }

  delete dbs;

  // update UI
  qApp->processEvents();

  // draw the map
  mMapCanvas->freeze( false );
  mMapCanvas->refresh();

} // SqlAnywhere::addSqlAnywhereLayer()