当前位置: 首页>>代码示例>>C++>>正文


C++ QgsVectorLayer::isValid方法代码示例

本文整理汇总了C++中QgsVectorLayer::isValid方法的典型用法代码示例。如果您正苦于以下问题:C++ QgsVectorLayer::isValid方法的具体用法?C++ QgsVectorLayer::isValid怎么用?C++ QgsVectorLayer::isValid使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QgsVectorLayer的用法示例。


在下文中一共展示了QgsVectorLayer::isValid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: vectorLayerFromSentVDS

QgsVectorLayer* QgsSentDataSourceBuilder::vectorLayerFromSentVDS( const QDomElement& sentVDSElem, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove ) const
{
  if ( sentVDSElem.attribute( "format" ) == "GML" )
  {
    QTemporaryFile* tmpFile = new QTemporaryFile();
    if ( tmpFile->open() )
    {
      filesToRemove.push_back( tmpFile ); //make sure the temporary file gets deleted after each request
      QTextStream tempFileStream( tmpFile );
      sentVDSElem.save( tempFileStream, 4 );
      tmpFile->close();
    }
    else
    {
      return 0;
    }

    QgsVectorLayer* theVectorLayer = new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), "WFS" );
    if ( !theVectorLayer || !theVectorLayer->isValid() )
    {
      QgsMSDebugMsg( "invalid maplayer" );
      return 0;
    }
    QgsMSDebugMsg( "returning maplayer" );

    layersToRemove.push_back( theVectorLayer ); //make sure the layer gets deleted after each request

    if ( !theVectorLayer || !theVectorLayer->isValid() )
    {
      return 0;
    }
    return theVectorLayer;
  }
  return 0;
}
开发者ID:RealworldSystems,项目名称:Quantum-GIS,代码行数:35,代码来源:qgssentdatasourcebuilder.cpp

示例2: setSql

void SaSourceSelect::setSql( const QModelIndex &index )
{
  if ( !index.parent().isValid() )
  {
    SaDebugMsg( "schema item found" );
    return;
  }

  QgsVectorLayer *vlayer = new QgsVectorLayer( layerURI( mProxyModel.mapToSource( index ) ), "querybuilder", "sqlanywhere" );

  if ( !vlayer->isValid() )
  {
    delete vlayer;
    return;
  }

  // create a query builder object
  SaQueryBuilder *qb = new SaQueryBuilder( vlayer, this );
  if ( qb->exec() )
  {
    mTableModel.setSql( mProxyModel.mapToSource( index ), qb->sql() );
  }

  delete qb;
  delete vlayer;
}
开发者ID:aaronr,项目名称:Quantum-GIS,代码行数:26,代码来源:sasourceselect.cpp

示例3: fromLayer

void TestQgsHistogram::fromLayer()
{
  QgsHistogram h;

  QVERIFY( !h.setValues( 0, QString() ) );

  QgsVectorLayer *layer = new QgsVectorLayer( QStringLiteral( "Point?field=col1:real" ), QStringLiteral( "layer" ), QStringLiteral( "memory" ) );
  QVERIFY( layer->isValid() );
  QgsFeatureList features;
  for ( int i = 1; i <= 10; ++i )
  {
    QgsFeature f( layer->dataProvider()->fields(), i );
    f.setAttribute( QStringLiteral( "col1" ), i );
    features << f;
  }
  layer->dataProvider()->addFeatures( features );

  QVERIFY( !h.setValues( layer, QString() ) );
  QVERIFY( h.setValues( layer, QString( "col1" ) ) );
  QList<int>counts = h.counts( 5 );
  QList<int> expected;
  expected << 2 << 2 << 2 << 2 << 2;
  QCOMPARE( counts, expected );

  delete layer;
}
开发者ID:exlimit,项目名称:QGIS,代码行数:26,代码来源:testqgshistogram.cpp

示例4: vectorLayerFromRemoteVDS

QgsVectorLayer* QgsRemoteDataSourceBuilder::vectorLayerFromRemoteVDS( const QDomElement& remoteVDSElem, const QString& layerName, QList<QTemporaryFile*>& filesToRemove, QList<QgsMapLayer*>& layersToRemove, bool allowCaching ) const
{
  QString providerString;
  QString formatString = remoteVDSElem.attribute( "format" );
  if ( formatString.compare( "gml", Qt::CaseInsensitive ) == 0 )
  {
    providerString = "WFS";
  }
  else
  {
    providerString = formatString;
  }

  //load file with QgsHttpTransaction
  QByteArray fileContents;
  QString uri = remoteVDSElem.text();

  QgsVectorLayer* vl = 0;

  if ( loadData( uri, fileContents ) != 0 )
  {
    return 0;
  }

  //store content into temporary file
  QTemporaryFile* tmpFile = new QTemporaryFile();
  if ( tmpFile->open() )
  {
    tmpFile->write( fileContents );
    tmpFile->flush();
  }
  else
  {
    delete tmpFile;
    return 0;
  }

  //create vector layer

  //SOS has a special datasource key...
  if ( formatString.compare( "SOS", Qt::CaseInsensitive ) == 0 )
  {
    QString url = "url=" + tmpFile->fileName() + " method=FILE xml=";
    vl =  new QgsVectorLayer( url, layerNameFromUri( tmpFile->fileName() ), providerString );
  }
  else
  {
    vl =  new QgsVectorLayer( tmpFile->fileName(), layerNameFromUri( tmpFile->fileName() ), providerString );
  }

  if ( !( vl->isValid() ) )
  {
    QgsMapServerLogger::instance()->printMessage( "vl is not valid" );
  }

  layersToRemove.push_back( vl );
  filesToRemove.push_back( tmpFile );
  return vl;
}
开发者ID:RealworldSystems,项目名称:Quantum-GIS,代码行数:59,代码来源:qgsremotedatasourcebuilder.cpp

示例5: exportErrorsDo

bool QgsGeometryCheckerResultTab::exportErrorsDo( const QString& file )
{
  QList< QPair<QString, QString> > attributes;
  attributes.append( qMakePair( QString( "FeatureID" ), QString( "String;10;" ) ) );
  attributes.append( qMakePair( QString( "ErrorDesc" ), QString( "String;80;" ) ) );

  QLibrary ogrLib( QgsProviderRegistry::instance()->library( "ogr" ) );
  if ( !ogrLib.load() )
  {
    return false;
  }
  typedef bool ( *createEmptyDataSourceProc )( const QString&, const QString&, const QString&, QGis::WkbType, const QList< QPair<QString, QString> >&, const QgsCoordinateReferenceSystem * );
  createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( ogrLib.resolve( "createEmptyDataSource" ) );
  if ( !createEmptyDataSource )
  {
    return false;
  }
  if ( !createEmptyDataSource( file, "ESRI Shapefile", mFeaturePool->getLayer()->dataProvider()->encoding(), QGis::WKBPoint, attributes, &mFeaturePool->getLayer()->crs() ) )
  {
    return false;
  }
  QgsVectorLayer* layer = new QgsVectorLayer( file, QFileInfo( file ).baseName(), "ogr" );
  if ( !layer->isValid() )
  {
    delete layer;
    return false;
  }

  int fieldFeatureId = layer->fieldNameIndex( "FeatureID" );
  int fieldErrDesc = layer->fieldNameIndex( "ErrorDesc" );
  for ( int row = 0, nRows = ui.tableWidgetErrors->rowCount(); row < nRows; ++row )
  {
    QgsGeometryCheckError* error = ui.tableWidgetErrors->item( row, 0 )->data( Qt::UserRole ).value<QgsGeometryCheckError*>();

    QgsFeature f( layer->pendingFields() );
    f.setAttribute( fieldFeatureId, error->featureId() );
    f.setAttribute( fieldErrDesc, error->description() );
    f.setGeometry( new QgsGeometry( error->location().clone() ) );
    layer->dataProvider()->addFeatures( QgsFeatureList() << f );
  }

  // Remove existing layer with same uri
  QStringList toRemove;
  foreach ( QgsMapLayer* maplayer, QgsMapLayerRegistry::instance()->mapLayers() )
  {
    if ( dynamic_cast<QgsVectorLayer*>( maplayer ) &&
         static_cast<QgsVectorLayer*>( maplayer )->dataProvider()->dataSourceUri() == layer->dataProvider()->dataSourceUri() )
    {
      toRemove.append( maplayer->id() );
    }
  }
  if ( !toRemove.isEmpty() )
  {
    QgsMapLayerRegistry::instance()->removeMapLayers( toRemove );
  }

  QgsMapLayerRegistry::instance()->addMapLayers( QList<QgsMapLayer*>() << layer );
  return true;
}
开发者ID:spatialthoughts,项目名称:QGIS,代码行数:59,代码来源:qgsgeometrycheckerresulttab.cpp

示例6: onOK

void QgsOSMExportDialog::onOK()
{
  if ( !openDatabase() )
    return;

  QgsOSMDatabase::ExportType type;
  if ( radPoints->isChecked() )
    type = QgsOSMDatabase::Point;
  else if ( radPolylines->isChecked() )
    type = QgsOSMDatabase::Polyline;
  else
    type = QgsOSMDatabase::Polygon;

  buttonBox->setEnabled( false );
  QApplication::setOverrideCursor( Qt::WaitCursor );

  QStringList tagKeys;
  QStringList notNullTagKeys;

  for ( int i = 0; i < mTagsModel->rowCount(); ++i )
  {
    QStandardItem* item = mTagsModel->item( i, 0 );
    if ( item->checkState() == Qt::Checked )
      tagKeys << item->text();

    QStandardItem* item2 = mTagsModel->item( i, 2 );
    if ( item2->checkState() == Qt::Checked )
      notNullTagKeys << item->text();
  }

  bool res = mDatabase->exportSpatiaLite( type, editLayerName->text(), tagKeys, notNullTagKeys );

  // load the layer into canvas if that was requested
  if ( chkLoadWhenFinished->isChecked() )
  {
    QgsDataSourceUri uri;
    uri.setDatabase( editDbFileName->text() );
    uri.setDataSource( QString(), editLayerName->text(), "geometry" );
    QgsVectorLayer* vlayer = new QgsVectorLayer( uri.uri(), editLayerName->text(), "spatialite" );
    if ( vlayer->isValid() )
      QgsMapLayerRegistry::instance()->addMapLayer( vlayer );
  }

  QApplication::restoreOverrideCursor();
  buttonBox->setEnabled( true );

  if ( res )
  {
    QMessageBox::information( this, tr( "OpenStreetMap export" ), tr( "Export has been successful." ) );
  }
  else
  {
    QMessageBox::critical( this, tr( "OpenStreetMap export" ), tr( "Failed to export OSM data:\n%1" ).arg( mDatabase->errorString() ) );
  }

  mDatabase->close();
}
开发者ID:NyakudyaA,项目名称:QGIS,代码行数:57,代码来源:qgsosmexportdialog.cpp

示例7: make_layer

static QgsVectorLayer* make_layer( const QStringList& wkts )
{
  QgsVectorLayer* vl = new QgsVectorLayer( "LineString", "x", "memory" );
  Q_ASSERT( vl->isValid() );

  vl->startEditing();
  Q_FOREACH ( const QString& wkt, wkts )
  {
    QgsFeature f( make_feature( wkt ) );
    vl->addFeature( f, false );
  }
开发者ID:af3dgce,项目名称:QGIS,代码行数:11,代码来源:testqgstracer.cpp

示例8: main

int main(int argc, char ** argv) 
{
  // Start the Application
  QgsApplication app(argc, argv, true);

  QString myPluginsDir        = "/home/timlinux/apps/lib/qgis";
  QString myLayerPath         = "/home/timlinux/gisdata/brazil/BR_Cidades/";
  QString myLayerBaseName     = "Brasil_Cap";
  QString myProviderName      = "ogr";
  // Instantiate Provider Registry
  QgsProviderRegistry::instance(myPluginsDir);
  // create a maplayer instance
  QgsVectorLayer * mypLayer = 
      new QgsVectorLayer(myLayerPath, myLayerBaseName, myProviderName);
  QgsSingleSymbolRenderer *mypRenderer = new QgsSingleSymbolRenderer(mypLayer->geometryType());
  QList <QgsMapCanvasLayer> myLayerSet;
  mypLayer->setRenderer(mypRenderer);
  if (mypLayer->isValid())
  {
    qDebug("Layer is valid");
  }
  else
  {
    qDebug("Layer is NOT valid");
  }

  // Add the Vector Layer to the Layer Registry
  QgsMapLayerRegistry::instance()->addMapLayer(mypLayer, TRUE);
  // Add the Layer to the Layer Set
  myLayerSet.append(QgsMapCanvasLayer(mypLayer, TRUE));

  // Create the Map Canvas
  QgsMapCanvas * mypMapCanvas = new QgsMapCanvas(0, 0);
  mypMapCanvas->setExtent(mypLayer->extent());
  mypMapCanvas->enableAntiAliasing(true);
  mypMapCanvas->setCanvasColor(QColor(255, 255, 255));
  mypMapCanvas->freeze(false);
  // Set the Map Canvas Layer Set
  mypMapCanvas->setLayerSet(myLayerSet);
  mypMapCanvas->setVisible(true);
  mypMapCanvas->refresh();

  // Start the Application Event Loop
  return app.exec();
}
开发者ID:ChowZenki,项目名称:QGIS-Code-Examples,代码行数:45,代码来源:main.cpp

示例9: qgis_QgsVectorLayer_open

int qgis_QgsVectorLayer_open(void)
{
	QString path = YAP_AtomName(YAP_AtomOfTerm(YAP_ARG1));
	QString basename = YAP_AtomName(YAP_AtomOfTerm(YAP_ARG2));
	QString provider = YAP_AtomName(YAP_AtomOfTerm(YAP_ARG3));
	YAP_Term out;

	QgsVectorLayer *layer =
		  new QgsVectorLayer(path, basename, provider);

	if (layer->isValid())
	{
		cerr << "Layer Type: " << layer->geometryType() << endl;
		cerr << "Feature Count: " << layer->featureCount() << endl;
		return TRUE;
	}
	else
	{
		delete layer;
		return FALSE;
	}
}
开发者ID:davidvaz,项目名称:yap-qgis,代码行数:22,代码来源:qgis_yap.cpp

示例10: apply


//.........这里部分代码省略.........
    if ( property( "hideDialogs" ).toBool() )
    {
      overwriteTable = property( "question_existing_layer_answer_overwrite" ).toBool();
    }
    else if ( QMessageBox::question( this, tr( "Existing layer" ),
                                     tr( "A table with the same name already exists. Do you want to overwrite it?" ),
                                     QMessageBox::Yes | QMessageBox::No, QMessageBox::No ) == QMessageBox::Yes )
    {
      overwriteTable = true;
    }

    if ( !overwriteTable )
    {
      return false;
    }
  }

  QString layerIdentifier( mLayerIdentifierEdit->text() );
  QString layerDescription( mLayerDescriptionEdit->text() );

  OGRwkbGeometryType wkbType = static_cast<OGRwkbGeometryType>
                               ( mGeometryTypeBox->currentData( Qt::UserRole ).toInt() );

  // z-coordinate & m-value.
  if ( mGeometryWithZCheckBox->isChecked() )
    wkbType = OGR_GT_SetZ( wkbType );

  if ( mGeometryWithMCheckBox->isChecked() )
    wkbType = OGR_GT_SetM( wkbType );

  OGRSpatialReferenceH hSRS = nullptr;
  // consider spatial reference system of the layer
  QgsCoordinateReferenceSystem srs = mCrsSelector->crs();
  if ( wkbType != wkbNone && srs.isValid() )
  {
    QString srsWkt = srs.toWkt();
    hSRS = OSRNewSpatialReference( srsWkt.toLocal8Bit().data() );
  }

  // Set options
  char **options = nullptr;

  if ( overwriteTable )
    options = CSLSetNameValue( options, "OVERWRITE", "YES" );
  if ( !layerIdentifier.isEmpty() )
    options = CSLSetNameValue( options, "IDENTIFIER", layerIdentifier.toUtf8().constData() );
  if ( !layerDescription.isEmpty() )
    options = CSLSetNameValue( options, "DESCRIPTION", layerDescription.toUtf8().constData() );

  QString featureId( mFeatureIdColumnEdit->text() );
  if ( !featureId.isEmpty() )
    options = CSLSetNameValue( options, "FID", featureId.toUtf8().constData() );

  QString geometryColumn( mGeometryColumnEdit->text() );
  if ( wkbType != wkbNone && !geometryColumn.isEmpty() )
    options = CSLSetNameValue( options, "GEOMETRY_COLUMN", geometryColumn.toUtf8().constData() );

  if ( wkbType != wkbNone )
    options = CSLSetNameValue( options, "SPATIAL_INDEX", mCheckBoxCreateSpatialIndex->isChecked() ? "YES" : "NO" );

  OGRLayerH hLayer = OGR_DS_CreateLayer( hDS.get(), tableName.toUtf8().constData(), hSRS, wkbType, options );
  CSLDestroy( options );
  if ( hSRS )
    OSRRelease( hSRS );
  if ( !hLayer )
  {
开发者ID:cz172638,项目名称:QGIS,代码行数:67,代码来源:qgsnewgeopackagelayerdialog.cpp

示例11: setItem

void QgsBrowserLayerProperties::setItem( QgsDataItem* item )
{
  QgsLayerItem *layerItem = qobject_cast<QgsLayerItem*>( item );
  if ( !layerItem )
    return;

  mNoticeLabel->clear();

  QgsMapLayer::LayerType type = layerItem->mapLayerType();
  QString layerMetadata = tr( "Error" );
  QgsCoordinateReferenceSystem layerCrs;

  // temporarily override /Projections/defaultBehaviour to avoid dialog prompt
  QSettings settings;
  QString defaultProjectionOption = settings.value( "/Projections/defaultBehaviour", "prompt" ).toString();
  if ( settings.value( "/Projections/defaultBehaviour", "prompt" ).toString() == "prompt" )
  {
    settings.setValue( "/Projections/defaultBehaviour", "useProject" );
  }

  // find root item
  // we need to create a temporary layer to get metadata
  // we could use a provider but the metadata is not as complete and "pretty"  and this is easier
  QgsDebugMsg( QString( "creating temporary layer using path %1" ).arg( layerItem->path() ) );
  if ( type == QgsMapLayer::RasterLayer )
  {
    QgsDebugMsg( "creating raster layer" );
    // should copy code from addLayer() to split uri ?
    QgsRasterLayer* layer = new QgsRasterLayer( layerItem->uri(), layerItem->uri(), layerItem->providerKey() );
    if ( layer )
    {
      if ( layer->isValid() )
      {
        layerCrs = layer->crs();
        layerMetadata = layer->metadata();
      }
      delete layer;
    }
  }
  else if ( type == QgsMapLayer::VectorLayer )
  {
    QgsDebugMsg( "creating vector layer" );
    QgsVectorLayer* layer = new QgsVectorLayer( layerItem->uri(), layerItem->name(), layerItem->providerKey() );
    if ( layer )
    {
      if ( layer->isValid() )
      {
        layerCrs = layer->crs();
        layerMetadata = layer->metadata();
      }
      delete layer;
    }
  }
  else if ( type == QgsMapLayer::PluginLayer )
  {
    // TODO: support display of properties for plugin layers
    return;
  }

  // restore /Projections/defaultBehaviour
  if ( defaultProjectionOption == "prompt" )
  {
    settings.setValue( "/Projections/defaultBehaviour", defaultProjectionOption );
  }

  mNameLabel->setText( layerItem->name() );
  mUriLabel->setText( layerItem->uri() );
  mProviderLabel->setText( layerItem->providerKey() );
  QString myStyle = QgsApplication::reportStyleSheet();
  mMetadataTextBrowser->document()->setDefaultStyleSheet( myStyle );
  mMetadataTextBrowser->setHtml( layerMetadata );

  // report if layer was set to to project crs without prompt (may give a false positive)
  if ( defaultProjectionOption == "prompt" )
  {
    QgsCoordinateReferenceSystem defaultCrs =
      QgisApp::instance()->mapCanvas()->mapSettings().destinationCrs();
    if ( layerCrs == defaultCrs )
      mNoticeLabel->setText( "NOTICE: Layer srs set from project (" + defaultCrs.authid() + ')' );
  }

  if ( mNoticeLabel->text().isEmpty() )
  {
    mNoticeLabel->hide();
  }
}
开发者ID:Wen2012,项目名称:QGIS,代码行数:86,代码来源:qgsbrowserdockwidget.cpp

示例12: apply

bool QgsNewSpatialiteLayerDialog::apply()
{
    // Build up the sql statement for creating the table
    QString sql = QString( "create table %1(" ).arg( quotedIdentifier( leLayerName->text() ) );
    QString delim = "";

    if ( checkBoxPrimaryKey->isChecked() )
    {
        sql += "pkuid integer primary key autoincrement,";
    }

    QTreeWidgetItemIterator it( mAttributeView );
    while ( *it )
    {
        sql += delim + QString( "%1 %2" ).arg( quotedIdentifier(( *it )->text( 0 ) ) ).arg(( *it )->text( 1 ) );

        delim = ",";

        ++it;
    }

    // complete the create table statement
    sql += ")";

    QgsDebugMsg( QString( "Creating table in database %1" ).arg( mDatabaseComboBox->currentText() ) );

    QgsDebugMsg( sql ); // OK

    QString sqlAddGeom = QString( "select AddGeometryColumn(%1,%2,%3,%4,2)" )
                         .arg( quotedValue( leLayerName->text() ) )
                         .arg( quotedValue( leGeometryColumn->text() ) )
                         .arg( mCrsId.split( ':' ).value( 1, "0" ).toInt() )
                         .arg( quotedValue( selectedType() ) );
    QgsDebugMsg( sqlAddGeom ); // OK

    QString sqlCreateIndex = QString( "select CreateSpatialIndex(%1,%2)" )
                             .arg( quotedValue( leLayerName->text() ) )
                             .arg( quotedValue( leGeometryColumn->text() ) );
    QgsDebugMsg( sqlCreateIndex ); // OK

    sqlite3 *db;
    int rc = QgsSLConnect::sqlite3_open( mDatabaseComboBox->currentText().toUtf8(), &db );
    if ( rc != SQLITE_OK )
    {
        QMessageBox::warning( this,
                              tr( "SpatiaLite Database" ),
                              tr( "Unable to open the database: %1" ).arg( mDatabaseComboBox->currentText() ) );
    }
    else
    {
        char * errmsg;
        rc = sqlite3_exec( db, sql.toUtf8(), NULL, NULL, &errmsg );
        if ( rc != SQLITE_OK )
        {
            QMessageBox::warning( this,
                                  tr( "Error Creating SpatiaLite Table" ),
                                  tr( "Failed to create the SpatiaLite table %1. The database returned:\n%2" ).arg( leLayerName->text() ).arg( errmsg ) );
            sqlite3_free( errmsg );
        }
        else
        {
            // create the geometry column and the spatial index
            rc = sqlite3_exec( db, sqlAddGeom.toUtf8(), NULL, NULL, &errmsg );
            if ( rc != SQLITE_OK )
            {
                QMessageBox::warning( this,
                                      tr( "Error Creating Geometry Column" ),
                                      tr( "Failed to create the geometry column. The database returned:\n%1" ).arg( errmsg ) );
                sqlite3_free( errmsg );
            }
            else
            {
                // create the spatial index
                rc = sqlite3_exec( db, sqlCreateIndex.toUtf8(), NULL, NULL, &errmsg );
                if ( rc != SQLITE_OK )
                {
                    QMessageBox::warning( this,
                                          tr( "Error Creating Spatial Index" ),
                                          tr( "Failed to create the spatial index. The database returned:\n%1" ).arg( errmsg ) );
                    sqlite3_free( errmsg );
                }

                QgsVectorLayer *layer = new QgsVectorLayer( QString( "dbname='%1' table='%2'(%3) sql=" )
                        .arg( mDatabaseComboBox->currentText() )
                        .arg( leLayerName->text() )
                        .arg( leGeometryColumn->text() ), leLayerName->text(), "spatialite" );
                if ( layer->isValid() )
                {
                    // register this layer with the central layers registry
                    QList<QgsMapLayer *> myList;
                    myList << layer;
                    //addMapLayers returns a list of all successfully added layers
                    //so we compare that to our original list.
                    if ( myList == QgsMapLayerRegistry::instance()->addMapLayers( myList ) )
                        return true;
                }
                else
                {
                    QgsDebugMsg( leLayerName->text() + " is an invalid layer - not loaded" );
                    QMessageBox::critical( this, tr( "Invalid Layer" ), tr( "%1 is an invalid layer and cannot be loaded." ).arg( leLayerName->text() ) );
//.........这里部分代码省略.........
开发者ID:dionhouston,项目名称:QGIS,代码行数:101,代码来源:qgsnewspatialitelayerdialog.cpp

示例13: addLayer

void MainWindow::addLayer()
{
  QString myLayerPath         = "../data";
  QString myLayerBaseName     = "test";
  QString myProviderName      = "ogr";
  
  QgsVectorLayer * mypLayer = new QgsVectorLayer(myLayerPath, myLayerBaseName, myProviderName);

  if (mypLayer->isValid())
  {
    qDebug("Layer is valid");
  }
  else
  {
    qDebug("Layer is NOT valid");
    return;
  }
  
  //set up a renderer for the layer
  QgsSingleSymbolRenderer *mypRenderer = new QgsSingleSymbolRenderer(mypLayer->geometryType());
  QList<QgsMapCanvasLayer> myLayerSet;
  mypLayer->setRenderer(mypRenderer);
  
  //
  //set up labelling for the layer
  //

  //get the label instance associated with the layer
  QgsLabel * mypLabel;
  mypLabel = mypLayer->label();
  //and the label attributes associated with the label
  QgsLabelAttributes * mypLabelAttributes;
  mypLabelAttributes = mypLabel->layerAttributes();
  //note in QGIS 1.4 and up you should use mypLabel->labelAttributes rather

  //get the field list associated with the layer
  //we'll print the names out to console for diagnostic purposes
  QgsFieldMap myFields = mypLayer->dataProvider()->fields();
  for (unsigned int i = 0; i < myFields.size(); i++ )
  {
    qDebug("Field Name: " +  QString(myFields[i].name()).toLocal8Bit() );
  }
  //just use the last field's name in the fields list as the label field! 
  qDebug("set label field to " + QString(myFields[myFields.size()-1].name()).toLocal8Bit());
  mypLabel->setLabelField( QgsLabel::Text,  myFields.size()-1);
  //set the colour of the label text
  mypLabelAttributes->setColor(Qt::black);
  //create a 'halo' effect around each label so it
  //can still be read on dark backgrounds
  mypLabelAttributes->setBufferEnabled(true);
  mypLabelAttributes->setBufferColor(Qt::yellow);
  int myType = QgsLabelAttributes::PointUnits;
  mypLabelAttributes->setBufferSize(1,myType);
  
  /*
   * Here are a bunch of other things you can set based on values on a database field
   * the second parameter in each case would be the field name from which the 
   * attribute can be retrieved.
  mypLabel->setLabelField( QgsLabel::Family, "fontFamily" );
  mypLabel->setLabelField( QgsLabel::Bold,  "fontIsBold" );
  mypLabel->setLabelField( QgsLabel::Italic, "fontIsItalic"  );
  mypLabel->setLabelField( QgsLabel::Underline, "fontIsUnderlined"  );
  mypLabel->setLabelField( QgsLabel::Size, "fontSize" );
  mypLabel->setLabelField( QgsLabel::BufferSize,"fontBufferSize" );
  mypLabel->setLabelField( QgsLabel::XCoordinate, "labelX" );
  mypLabel->setLabelField( QgsLabel::YCoordinate, "labelY");
  mypLabel->setLabelField( QgsLabel::XOffset, "labelXOffset");
  mypLabel->setLabelField( QgsLabel::YOffset, "labelYOffset");
  mypLabel->setLabelField( QgsLabel::Alignment, "labelAlignment" );
  mypLabel->setLabelField( QgsLabel::Angle, "labelAngle");
  */
  
  //lastly we enable labelling!
  mypLayer->enableLabels(true);
  
  // Add the Vector Layer to the Layer Registry
  QgsMapLayerRegistry::instance()->addMapLayer(mypLayer, TRUE);

  // Add the Layer to the Layer Set
  myLayerSet.append(QgsMapCanvasLayer( mypLayer ) );
  // set teh canvas to the extent of our layer
  mpMapCanvas->setExtent(mypLayer->extent());
  // Set the Map Canvas Layer Set
  mpMapCanvas->setLayerSet(myLayerSet);
}
开发者ID:ChowZenki,项目名称:QGIS-Code-Examples,代码行数:85,代码来源:mainwindow.cpp

示例14: handleDrop

bool QgsPGConnectionItem::handleDrop( const QMimeData *data, const QString &toSchema )
{
  if ( !QgsMimeDataUtils::isUriList( data ) )
    return false;

  // TODO: probably should show a GUI with settings etc
  QgsDataSourceUri uri = QgsPostgresConn::connUri( mName );

  QStringList importResults;
  bool hasError = false;

  QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data );
  const auto constLst = lst;
  for ( const QgsMimeDataUtils::Uri &u : constLst )
  {
    // open the source layer
    bool owner;
    QString error;
    QgsVectorLayer *srcLayer = u.vectorLayer( owner, error );
    if ( !srcLayer )
    {
      importResults.append( tr( "%1: %2" ).arg( u.name, error ) );
      hasError = true;
      continue;
    }

    if ( srcLayer->isValid() )
    {
      uri.setDataSource( QString(), u.name,  srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? QStringLiteral( "geom" ) : QString() );
      QgsDebugMsg( "URI " + uri.uri( false ) );

      if ( !toSchema.isNull() )
      {
        uri.setSchema( toSchema );
      }

      QVariantMap options;
      options.insert( QStringLiteral( "forceSinglePartGeometryType" ), true );
      std::unique_ptr< QgsVectorLayerExporterTask > exportTask( new QgsVectorLayerExporterTask( srcLayer, uri.uri( false ), QStringLiteral( "postgres" ), srcLayer->crs(), options, owner ) );

      // when export is successful:
      connect( exportTask.get(), &QgsVectorLayerExporterTask::exportComplete, this, [ = ]()
      {
        // this is gross - TODO - find a way to get access to messageBar from data items
        QMessageBox::information( nullptr, tr( "Import to PostGIS database" ), tr( "Import was successful." ) );
        refreshSchema( toSchema );
      } );

      // when an error occurs:
      connect( exportTask.get(), &QgsVectorLayerExporterTask::errorOccurred, this, [ = ]( int error, const QString & errorMessage )
      {
        if ( error != QgsVectorLayerExporter::ErrUserCanceled )
        {
          QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
          output->setTitle( tr( "Import to PostGIS database" ) );
          output->setMessage( tr( "Failed to import some layers!\n\n" ) + errorMessage, QgsMessageOutput::MessageText );
          output->showMessage();
        }
        refreshSchema( toSchema );
      } );

      QgsApplication::taskManager()->addTask( exportTask.release() );
    }
    else
    {
      importResults.append( tr( "%1: Not a valid layer!" ).arg( u.name ) );
      hasError = true;
    }
  }

  if ( hasError )
  {
    QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
    output->setTitle( tr( "Import to PostGIS database" ) );
    output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText );
    output->showMessage();
  }

  return true;
}
开发者ID:alexbruy,项目名称:QGIS,代码行数:80,代码来源:qgspostgresdataitems.cpp

示例15: QgsVectorLayer

void QgsProjectFileTransform::transform0110to1000()
{
  if ( ! mDom.isNull() )
  {
    QDomNodeList layerList = mDom.elementsByTagName( "maplayer" );
    for ( int i = 0; i < layerList.size(); ++i )
    {
      QDomElement layerElem = layerList.at( i ).toElement();
      QString typeString = layerElem.attribute( "type" );
      if ( typeString != "vector" )
      {
        continue;
      }

      //datasource
      QDomNode dataSourceNode = layerElem.namedItem( "datasource" );
      if ( dataSourceNode.isNull() )
      {
        return;
      }
      QString dataSource = dataSourceNode.toElement().text();

      //provider key
      QDomNode providerNode = layerElem.namedItem( "provider" );
      if ( providerNode.isNull() )
      {
        return;
      }
      QString providerKey = providerNode.toElement().text();

      //create the layer to get the provider for int->fieldName conversion
      QgsVectorLayer* theLayer = new QgsVectorLayer( dataSource, "", providerKey, false );
      if ( !theLayer->isValid() )
      {
        delete theLayer;
        return;
      }

      QgsVectorDataProvider* theProvider = theLayer->dataProvider();
      if ( !theProvider )
      {
        return;
      }
      QgsFields theFields = theProvider->fields();

      //read classificationfield
      QDomNodeList classificationFieldList = layerElem.elementsByTagName( "classificationfield" );
      for ( int j = 0; j < classificationFieldList.size(); ++j )
      {
        QDomElement classificationFieldElem = classificationFieldList.at( j ).toElement();
        int fieldNumber = classificationFieldElem.text().toInt();
        if ( fieldNumber >= 0 && fieldNumber < theFields.count() )
        {
          QDomText fieldName = mDom.createTextNode( theFields[fieldNumber].name() );
          QDomNode nameNode = classificationFieldElem.firstChild();
          classificationFieldElem.replaceChild( fieldName, nameNode );
        }
      }

    }
  }
}
开发者ID:L-Infantini,项目名称:Quantum-GIS,代码行数:62,代码来源:qgsprojectfiletransform.cpp


注:本文中的QgsVectorLayer::isValid方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。