Пример #1
0
bool QgsZonalStatisticsDialog::prefixIsValid( const QString& prefix ) const
{
  QgsVectorLayer* vl = polygonLayer();
  if ( !vl )
  {
    return false;
  }
  QgsVectorDataProvider* dp = vl->dataProvider();
  if ( !dp )
  {
    return false;
  }

  QgsFieldMap providerFieldMap = dp->fields();
  QgsFieldMap::const_iterator it = providerFieldMap.constBegin();
  QString currentFieldName;

  for ( ; it != providerFieldMap.constEnd(); ++it )
  {
    currentFieldName = it.value().name();
    if ( currentFieldName == ( prefix + "mean" ) || currentFieldName == ( prefix + "sum" ) || currentFieldName == ( prefix + "count" ) )
    {
      return false;
    }
  }
  return true;
}
Пример #2
0
int QgsLegendModel::addVectorLayerItems( QStandardItem* layerItem, QgsVectorLayer* vlayer )
{
  if ( !layerItem || !vlayer )
  {
    return 1;
  }

  int opacity = vlayer->getTransparency();

  const QgsRenderer* vectorRenderer = vlayer->renderer();
  if ( !vectorRenderer )
  {
    return 3;
  }

  //text field that describes classification attribute?
  QSettings settings;
  if ( settings.value( "/qgis/showLegendClassifiers", false ).toBool() )
  {
    QgsFieldMap layerFields = vlayer->pendingFields();
    QgsAttributeList attributes = vectorRenderer->classificationAttributes();
    QgsAttributeList::const_iterator att_it = attributes.constBegin();
    for ( ; att_it != attributes.constEnd(); ++att_it )
    {
      QgsFieldMap::const_iterator fieldIt = layerFields.find( *att_it );
      if ( fieldIt != layerFields.constEnd() )
      {
        QString attributeName = vlayer->attributeDisplayName( fieldIt.key() );
        QStandardItem* attributeItem = new QStandardItem( attributeName );
        attributeItem->setData( QgsLegendModel::ClassificationItem, Qt::UserRole + 1 ); //first user data stores the item type
        attributeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
        layerItem->setChild( layerItem->rowCount(), 0, attributeItem );
      }
    }
  }

  const QList<QgsSymbol*> vectorSymbols = vectorRenderer->symbols();
  QList<QgsSymbol*>::const_iterator symbolIt = vectorSymbols.constBegin();

  for ( ; symbolIt != vectorSymbols.constEnd(); ++symbolIt )
  {
    if ( !( *symbolIt ) )
    {
      continue;
    }

    QStandardItem* currentSymbolItem = itemFromSymbol( *symbolIt, opacity, vlayer->id() );
    if ( !currentSymbolItem )
    {
      continue;
    }

    layerItem->setChild( layerItem->rowCount(), 0, currentSymbolItem );

  }

  return 0;
}
Пример #3
0
void QgsAttributeTableDialog::columnBoxInit()
{
  QgsFieldMap fieldMap = mLayer->pendingFields();
  QgsFieldMap::Iterator it = fieldMap.begin();

  for ( ; it != fieldMap.end(); ++it )
    if ( mLayer->editType( it.key() ) != QgsVectorLayer::Hidden )
      mColumnBox->addItem( it.value().name() );

  mColumnBox->setCurrentIndex( mColumnBox->findText( mLayer->displayField() ) );
}
Пример #4
0
int QgsAttributeTableDialog::columnBoxColumnId()
{
  QgsFieldMap fieldMap = mLayer->pendingFields();
  QgsFieldMap::Iterator it = fieldMap.begin();

  for ( ; it != fieldMap.end(); ++it )
    if ( it.value().name() == mColumnBox->currentText() )
      return it.key();

  return 0;
}
Пример #5
0
int OptVectorLayer::addFeatureWithDefaultValue( OptFeature& f )
{
//{zhangliye2715:api}
  if ( !isEditable() )
  {
    startEditing();
  }

  // add the fields to the QgsFeature
  QgsVectorDataProvider* provider = dataProvider();
  const QgsFieldMap fields = provider->fields();

  for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
  {
    f.addAttribute( it.key(), provider->defaultValue( it.key() ) );
  }

  int id = -1;
  id = OptVectorLayer::addFeature( f );
  if ( id != -1 )
  {
    //add points to other features to keep topology up-to-date
    int topologicalEditing = QgsProject::instance()->readNumEntry( "Digitizing", "/TopologicalEditing", 0 );

    if( topologicalEditing )
    {
      addTopologicalPoints( f.geometry() );
    }
  }
  else
  {
    return -1;
  }

  //vlayer->setModified(true);
  //commit or rollBack the change
  if ( isModified() )
  {
    commitChanges();
  }
  else
  {
    rollBack();
    return -1;
  }

  //make the layer still editable for the next adding operation
  startEditing();

  return id;
}
QgsDelAttrDialog::QgsDelAttrDialog( const QgsVectorLayer* vl ): QDialog()
{
    setupUi( this );
    if ( vl )
    {
        listBox2->clear();
        const QgsFieldMap layerAttributes = vl->pendingFields();
        QgsFieldMap::const_iterator attIt = layerAttributes.constBegin();
        for ( ; attIt != layerAttributes.constEnd(); ++attIt )
        {
            QListWidgetItem* item = new QListWidgetItem( attIt.value().name(), listBox2 );
            item->setData( Qt::UserRole, attIt.key() );
        }
    }
}
Пример #7
0
void QgsFieldCalculator::populateFields()
{
  if ( !mVectorLayer )
    return;

  const QgsFieldMap fieldMap = mVectorLayer->pendingFields();
  QgsFieldMap::const_iterator fieldIt = fieldMap.constBegin();
  for ( ; fieldIt != fieldMap.constEnd(); ++fieldIt )
  {

    QString fieldName = fieldIt.value().name();

    //insert into field list and field combo box
    mFieldMap.insert( fieldName, fieldIt.key() );
    mExistingFieldComboBox->addItem( fieldName );
  }
}
void QgsComposerAttributeTable::initializeAliasMap()
{
  mFieldAliasMap.clear();
  if ( mVectorLayer )
  {
    QgsFieldMap fieldMap = mVectorLayer->pendingFields();
    QgsFieldMap::const_iterator it = fieldMap.constBegin();
    for ( ; it != fieldMap.constEnd(); ++it )
    {
      QString currentAlias = mVectorLayer->attributeAlias( it.key() );
      if ( !currentAlias.isEmpty() )
      {
        mFieldAliasMap.insert( it.key(), currentAlias );
      }
    }
  }
}
QMap<int, QString> QgsComposerAttributeTable::getHeaderLabels() const
{
  QMap<int, QString> header;
  if ( mVectorLayer )
  {
    QgsFieldMap vectorFields = mVectorLayer->pendingFields();
    QgsFieldMap::const_iterator fieldIt = vectorFields.constBegin();
    for ( ; fieldIt != vectorFields.constEnd(); ++fieldIt )
    {
      if ( mDisplayAttributes.size() > 0 && !mDisplayAttributes.contains( fieldIt.key() ) )
      {
        continue;
      }
      header.insert( fieldIt.key(), attributeDisplayName( fieldIt.key(), fieldIt.value().name() ) );
    }
  }
  return header;
}
Пример #10
0
void QgsOverlayAnalyzer::combineFieldLists( QgsFieldMap& fieldListA, QgsFieldMap fieldListB )
{
  QList<QString> names;
  QMap<int, QgsField>::const_iterator j = fieldListA.constBegin();
  while ( j != fieldListA.constEnd() )
  {
    names.append( j.value().name() );
    ++j;
  }
  QMap<int, QgsField>::const_iterator i = fieldListB.constBegin();
  int count = 0;
  int fcount = fieldListA.size();
  QgsField field;
  while ( i != fieldListB.constEnd() )
  {
    field = i.value();
    while ( names.contains( field.name() ) )
    {
      QString name = field.name();
      name.append( "_" ).append( QString( count ) );
      field = QgsField( name, field.type() );
      ++count;
    }
    fieldListA.insert( fcount, field );
    count = 0;
    ++fcount;
    ++i;
  }
}
Пример #11
0
void QgsFieldCalculator::accept()
{
    if ( mVectorLayer && mVectorLayer->isEditable() )
    {
        QString calcString = mExpressionTextEdit->toPlainText();

        //create QgsExpression
        QgsExpression exp( calcString );
        if ( exp.hasParserError() )
        {
            //expression not valid
            QMessageBox::critical( 0, tr( "Syntax error" ), tr( QString( "Invalid expression syntax. The error message of the parser is: '" + exp.parserErrorString() + "'" ).toLocal8Bit().data() ) );
            return;
        }

        if ( ! exp.prepare( mVectorLayer->pendingFields() ) )
        {
            QMessageBox::critical( 0, tr( "Evaluation error" ), exp.evalErrorString() );
            return;
        }

        mVectorLayer->beginEditCommand( "Field calculator" );

        //update existing field
        if ( mUpdateExistingFieldCheckBox->checkState() == Qt::Checked )
        {
            QMap<QString, int>::const_iterator fieldIt = mFieldMap.find( mExistingFieldComboBox->currentText() );
            if ( fieldIt != mFieldMap.end() )
            {
                mAttributeId = fieldIt.value();
            }
        }
        //create new field
        else
        {
            //create new field
            QgsField newField( mOutputFieldNameLineEdit->text(),
                               ( QVariant::Type ) mOutputFieldTypeComboBox->itemData( mOutputFieldTypeComboBox->currentIndex(), Qt::UserRole ).toInt(),
                               mOutputFieldTypeComboBox->itemData( mOutputFieldTypeComboBox->currentIndex(), Qt::UserRole + 1 ).toString(),
                               mOuputFieldWidthSpinBox->value(),
                               mOutputFieldPrecisionSpinBox->value() );

            if ( !mVectorLayer->addAttribute( newField ) )
            {
                QMessageBox::critical( 0, tr( "Provider error" ), tr( "Could not add the new field to the provider." ) );
                mVectorLayer->destroyEditCommand();
                return;
            }

            //get index of the new field
            const QgsFieldMap fieldList = mVectorLayer->pendingFields();

            QgsFieldMap::const_iterator it = fieldList.constBegin();
            for ( ; it != fieldList.constEnd(); ++it )
            {
                if ( it.value().name() == mOutputFieldNameLineEdit->text() )
                {
                    mAttributeId = it.key();
                    break;
                }
            }
        }

        if ( mAttributeId == -1 )
        {
            mVectorLayer->destroyEditCommand();
            return;
        }

        //go through all the features and change the new attribute
        QgsFeature feature;
        bool calculationSuccess = true;
        QString error;

        bool onlySelected = ( mOnlyUpdateSelectedCheckBox->checkState() == Qt::Checked );
        QgsFeatureIds selectedIds = mVectorLayer->selectedFeaturesIds();

        // block layerModified signals (that would trigger table update)
        mVectorLayer->blockSignals( true );

        bool useGeometry = exp.needsGeometry();
        int rownum = 1;

        mVectorLayer->select( mVectorLayer->pendingAllAttributesList(), QgsRectangle(), useGeometry, false );
        while ( mVectorLayer->nextFeature( feature ) )
        {
            if ( onlySelected )
            {
                if ( !selectedIds.contains( feature.id() ) )
                {
                    continue;
                }
            }

            exp.setCurrentRowNumber( rownum );

            QVariant value = exp.evaluate( &feature );
            if ( exp.hasEvalError() )
            {
                calculationSuccess = false;
                error = exp.evalErrorString();
                break;
            }
            else
            {
                mVectorLayer->changeAttributeValue( feature.id(), mAttributeId, value, false );
            }

            rownum++;
        }

        // stop blocking layerModified signals and make sure that one layerModified signal is emitted
        mVectorLayer->blockSignals( false );
        mVectorLayer->setModified( true, false );

        if ( !calculationSuccess )
        {
            QMessageBox::critical( 0, tr( "Error" ), tr( "An error occured while evaluating the calculation string:\n%1" ).arg( error ) );
            mVectorLayer->destroyEditCommand();
            return;
        }

        mVectorLayer->endEditCommand();
    }
    QDialog::accept();
}
QgsPointDisplacementRendererWidget::QgsPointDisplacementRendererWidget( QgsVectorLayer* layer, QgsStyleV2* style, QgsFeatureRendererV2* renderer ): \
    QgsRendererV2Widget( layer, style ), mEmbeddedRendererWidget( 0 )
{
  if ( !layer )
  {
    return;
  }

  //the renderer only applies to point vector layers
  if ( layer->wkbType() != QGis::WKBPoint && layer->wkbType()  != QGis::WKBPoint25D )
  {
    //setup blank dialog
    mRenderer = 0;
    setupBlankUi( layer->name() );
    return;
  }
  setupUi( this );

  if ( renderer && renderer->type() == "pointDisplacement" )
  {
    mRenderer = dynamic_cast<QgsPointDisplacementRenderer*>( renderer->clone() );
  }
  else
  {
    mRenderer = new QgsPointDisplacementRenderer();
  }

  blockAllSignals( true );

  //insert attributes into combo box
  if ( layer )
  {
    const QgsFieldMap layerAttributes = layer->pendingFields();
    QgsFieldMap::const_iterator it = layerAttributes.constBegin();
    for ( ; it != layerAttributes.constEnd(); ++it )
    {
      mLabelFieldComboBox->addItem( it.value().name() );
    }
    mLabelFieldComboBox->addItem( tr( "None" ) );

    QString currentLabelAttribute = mRenderer->labelAttributeName();
    if ( !currentLabelAttribute.isEmpty() )
    {
      mLabelFieldComboBox->setCurrentIndex( mLabelFieldComboBox->findText( currentLabelAttribute ) );
    }
    else
    {
      mLabelFieldComboBox->setCurrentIndex( mLabelFieldComboBox->findText( tr( "None" ) ) );
    }
  }

  //insert possible renderer types
  QStringList rendererList = QgsRendererV2Registry::instance()->renderersList();
  QStringList::const_iterator it = rendererList.constBegin();
  for ( ; it != rendererList.constEnd(); ++it )
  {
    if ( *it != "pointDisplacement" )
    {
      QgsRendererV2AbstractMetadata* m = QgsRendererV2Registry::instance()->rendererMetadata( *it );
      mRendererComboBox->addItem( m->icon(), m->visibleName(), *it );
    }
  }

  mCircleWidthSpinBox->setValue( mRenderer->circleWidth() );
  mCircleColorButton->setColor( mRenderer->circleColor() );
  mLabelColorButton->setColor( mRenderer->labelColor() );
  mCircleModificationSpinBox->setValue( mRenderer->circleRadiusAddition() );
  mDistanceSpinBox->setValue( mRenderer->tolerance() );

  //scale dependent labelling
  mMaxScaleDenominatorEdit->setText( QString::number( mRenderer->maxLabelScaleDenominator() ) );
  mMaxScaleDenominatorEdit->setValidator( new QDoubleValidator( mMaxScaleDenominatorEdit ) );
  if ( mRenderer->maxLabelScaleDenominator() > 0 )
  {
    mScaleDependentLabelsCheckBox->setCheckState( Qt::Checked );
  }
  else
  {
    mScaleDependentLabelsCheckBox->setCheckState( Qt::Unchecked );
    mMaxScaleDenominatorEdit->setEnabled( false );
  }


  blockAllSignals( false );

  //set the appropriate renderer dialog
  if ( mRenderer && mRenderer->embeddedRenderer() )
  {
    QString rendererName = mRenderer->embeddedRenderer()->type();
    int rendererIndex = mRendererComboBox->findData( rendererName );
    if ( rendererIndex != -1 )
    {
      mRendererComboBox->setCurrentIndex( rendererIndex );
      on_mRendererComboBox_currentIndexChanged( rendererIndex );
    }
  }

  updateCenterIcon();
}
Пример #13
0
bool QgsGeometryAnalyzer::extent( QgsVectorLayer* layer,
                                  const QString& shapefileName,
                                  bool onlySelectedFeatures,
                                  QProgressDialog * )
{
  if ( !layer )
  {
    return false;
  }

  QgsVectorDataProvider* dp = layer->dataProvider();
  if ( !dp )
  {
    return false;
  }

  QGis::WkbType outputType = QGis::WKBPolygon;
  const QgsCoordinateReferenceSystem crs = layer->crs();

  QgsFieldMap fields;
  fields.insert( 0 , QgsField( QString( "MINX" ), QVariant::Double ) );
  fields.insert( 1 , QgsField( QString( "MINY" ), QVariant::Double ) );
  fields.insert( 2 , QgsField( QString( "MAXX" ), QVariant::Double ) );
  fields.insert( 3 , QgsField( QString( "MAXY" ), QVariant::Double ) );
  fields.insert( 4 , QgsField( QString( "CNTX" ), QVariant::Double ) );
  fields.insert( 5 , QgsField( QString( "CNTY" ), QVariant::Double ) );
  fields.insert( 6 , QgsField( QString( "AREA" ), QVariant::Double ) );
  fields.insert( 7 , QgsField( QString( "PERIM" ), QVariant::Double ) );
  fields.insert( 8 , QgsField( QString( "HEIGHT" ), QVariant::Double ) );
  fields.insert( 9 , QgsField( QString( "WIDTH" ), QVariant::Double ) );

  QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), fields, outputType, &crs );

  QgsRectangle rect;
  if ( onlySelectedFeatures )  // take only selection
  {
    rect = layer->boundingBoxOfSelected();
  }
  else
  {
    rect = layer->extent();
  }

  double minx = rect.xMinimum();
  double miny = rect.yMinimum();
  double maxx = rect.xMaximum();
  double maxy = rect.yMaximum();
  double height = rect.height();
  double width = rect.width();
  double cntx = minx + ( width / 2.0 );
  double cnty = miny + ( height / 2.0 );
  double area = width * height;
  double perim = ( 2 * width ) + ( 2 * height );

  QgsFeature feat;
  QgsAttributeMap map;
  map.insert( 0 , QVariant( minx ) );
  map.insert( 1 , QVariant( miny ) );
  map.insert( 2 , QVariant( maxx ) );
  map.insert( 3 , QVariant( maxy ) );
  map.insert( 4 , QVariant( cntx ) );
  map.insert( 5 , QVariant( cnty ) );
  map.insert( 6 , QVariant( area ) );
  map.insert( 7 , QVariant( perim ) );
  map.insert( 8 , QVariant( height ) );
  map.insert( 9 , QVariant( width ) );
  feat.setAttributeMap( map );
  feat.setGeometry( QgsGeometry::fromRect( rect ) );
  vWriter.addFeature( feat );
  return true;
}
Пример #14
0
void QgsClipboard::replaceWithCopyOf( const QgsFieldMap& fields, QgsFeatureList& features )
{

  // Replace the QGis clipboard.
  mFeatureClipboard = features;
  QgsDebugMsg( "replaced QGis clipboard." );

  // Replace the system clipboard.

  QStringList textLines;
  QStringList textFields;

  // first do the field names
  textFields += "wkt_geom";
  for ( QgsFieldMap::const_iterator fit = fields.begin(); fit != fields.end(); ++fit )
  {
    textFields += fit->name();
  }
  textLines += textFields.join( "\t" );
  textFields.clear();


  // then the field contents
  for ( QgsFeatureList::iterator it = features.begin(); it != features.end(); ++it )
  {
    QgsAttributeMap attributes = it->attributeMap();


    // TODO: Set up Paste Transformations to specify the order in which fields are added.

    if ( it->geometry() )
      textFields += it->geometry()->exportToWkt();
    else
    {
      QSettings settings;
      textFields += settings.value( "qgis/nullValue", "NULL" ).toString();
    }

    // QgsDebugMsg("about to traverse fields.");
    //
    for ( QgsAttributeMap::iterator it2 = attributes.begin(); it2 != attributes.end(); ++it2 )
    {
      // QgsDebugMsg(QString("inspecting field '%1'.").arg(it2->toString()));
      textFields += it2->toString();
    }

    textLines += textFields.join( "\t" );
    textFields.clear();
  }

  QString textCopy = textLines.join( "\n" );

  QClipboard *cb = QApplication::clipboard();

  // Copy text into the clipboard

  // With qgis running under Linux, but with a Windows based X
  // server (Xwin32), ::Selection was necessary to get the data into
  // the Windows clipboard (which seems contrary to the Qt
  // docs). With a Linux X server, ::Clipboard was required.
  // The simple solution was to put the text into both clipboards.

  // The ::Selection setText() below one may need placing inside so
  // #ifdef so that it doesn't get compiled under Windows.
  cb->setText( textCopy, QClipboard::Selection );
  cb->setText( textCopy, QClipboard::Clipboard );

  QgsDebugMsg( QString( "replaced system clipboard with: %1." ).arg( textCopy ) );
}
Пример #15
0
bool QgsGeometryAnalyzer::convexHull( QgsVectorLayer* layer, const QString& shapefileName,
                                      bool onlySelectedFeatures, int uniqueIdField, QProgressDialog* p )
{
  if ( !layer )
  {
    return false;
  }
  QgsVectorDataProvider* dp = layer->dataProvider();
  if ( !dp )
  {
    return false;
  }
  bool useField = false;
  if ( uniqueIdField == -1 )
  {
    uniqueIdField = 0;
  }
  else
  {
    useField = true;
  }
  QgsFieldMap fields;
  fields.insert( 0 , QgsField( QString( "UID" ), QVariant::String ) );
  fields.insert( 1 , QgsField( QString( "AREA" ), QVariant::Double ) );
  fields.insert( 2 , QgsField( QString( "PERIM" ), QVariant::Double ) );

  QGis::WkbType outputType = QGis::WKBPolygon;
  const QgsCoordinateReferenceSystem crs = layer->crs();

  QgsVectorFileWriter vWriter( shapefileName, dp->encoding(), fields, outputType, &crs );
  QgsFeature currentFeature;
  QgsGeometry* dissolveGeometry = 0; //dissolve geometry
  QMultiMap<QString, QgsFeatureId> map;

  if ( onlySelectedFeatures )
  {
    //use QgsVectorLayer::featureAtId
    const QgsFeatureIds selection = layer->selectedFeaturesIds();
    QgsFeatureIds::const_iterator it = selection.constBegin();
    for ( ; it != selection.constEnd(); ++it )
    {
#if 0
      if ( p )
      {
        p->setValue( processedFeatures );
      }
      if ( p && p->wasCanceled() )
      {
        // break; // it may be better to do something else here?
        return false;
      }
#endif
      if ( !layer->featureAtId( *it, currentFeature, true, true ) )
      {
        continue;
      }
      map.insert( currentFeature.attributeMap()[ uniqueIdField ].toString(), currentFeature.id() );
    }
  }
  else
  {
    layer->select( layer->pendingAllAttributesList(), QgsRectangle(), true, false );
    while ( layer->nextFeature( currentFeature ) )
    {
#if 0
      if ( p )
      {
        p->setValue( processedFeatures );
      }
      if ( p && p->wasCanceled() )
      {
        // break; // it may be better to do something else here?
        return false;
      }
#endif
      map.insert( currentFeature.attributeMap()[ uniqueIdField ].toString(), currentFeature.id() );
    }
  }

  QMultiMap<QString, QgsFeatureId>::const_iterator jt = map.constBegin();
  while ( jt != map.constEnd() )
  {
    QString currentKey = jt.key();
    int processedFeatures = 0;
    //take only selection
    if ( onlySelectedFeatures )
    {
      //use QgsVectorLayer::featureAtId
      const QgsFeatureIds selection = layer->selectedFeaturesIds();
      if ( p )
      {
        p->setMaximum( selection.size() );
      }
      processedFeatures = 0;
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( selection.contains( jt.value() ) )
        {
          if ( p )
          {
            p->setValue( processedFeatures );
          }
          if ( !layer->featureAtId( jt.value(), currentFeature, true, true ) )
          {
            continue;
          }
          convexFeature( currentFeature, processedFeatures, &dissolveGeometry );
          ++processedFeatures;
        }
        ++jt;
      }
      QList<double> values;
      if ( !dissolveGeometry )
      {
        QgsDebugMsg( "no dissolved geometry - should not happen" );
        return false;
      }
      dissolveGeometry = dissolveGeometry->convexHull();
      values = simpleMeasure( dissolveGeometry );
      QgsAttributeMap attributeMap;
      attributeMap.insert( 0 , QVariant( currentKey ) );
      attributeMap.insert( 1 , values[ 0 ] );
      attributeMap.insert( 2 , values[ 1 ] );
      QgsFeature dissolveFeature;
      dissolveFeature.setAttributeMap( attributeMap );
      dissolveFeature.setGeometry( dissolveGeometry );
      vWriter.addFeature( dissolveFeature );
    }
    //take all features
    else
    {
      int featureCount = layer->featureCount();
      if ( p )
      {
        p->setMaximum( featureCount );
      }
      processedFeatures = 0;
      while ( jt != map.constEnd() && ( jt.key() == currentKey || !useField ) )
      {
        if ( p )
        {
          p->setValue( processedFeatures );
        }

        if ( p && p->wasCanceled() )
        {
          break;
        }
        if ( !layer->featureAtId( jt.value(), currentFeature, true, true ) )
        {
          continue;
        }
        convexFeature( currentFeature, processedFeatures, &dissolveGeometry );
        ++processedFeatures;
        ++jt;
      }
      QList<double> values;
      // QgsGeometry* tmpGeometry = 0;
      if ( !dissolveGeometry )
      {
        QgsDebugMsg( "no dissolved geometry - should not happen" );
        return false;
      }
      dissolveGeometry = dissolveGeometry->convexHull();
      // values = simpleMeasure( tmpGeometry );
      values = simpleMeasure( dissolveGeometry );
      QgsAttributeMap attributeMap;
      attributeMap.insert( 0 , QVariant( currentKey ) );
      attributeMap.insert( 1 , QVariant( values[ 0 ] ) );
      attributeMap.insert( 2 , QVariant( values[ 1 ] ) );
      QgsFeature dissolveFeature;
      dissolveFeature.setAttributeMap( attributeMap );
      dissolveFeature.setGeometry( dissolveGeometry );
      vWriter.addFeature( dissolveFeature );
    }
  }
  return true;
}
Пример #16
0
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);
}
Пример #17
0
void QgsFieldCalculator::accept()
{

  // Set up QgsDistanceArea each time we (re-)calculate
  QgsDistanceArea myDa;

  myDa.setSourceCrs( mVectorLayer->crs().srsid() );
  myDa.setEllipsoidalMode( QgisApp::instance()->mapCanvas()->mapRenderer()->hasCrsTransformEnabled() );
  myDa.setEllipsoid( QgsProject::instance()->readEntry( "Measure", "/Ellipsoid", GEO_NONE ) );


  QString calcString = builder->expressionText();
  QgsExpression exp( calcString );

  if ( !mVectorLayer || !mVectorLayer->isEditable() )
    return;

  if ( ! exp.prepare( mVectorLayer->pendingFields() ) )
  {
    QMessageBox::critical( 0, tr( "Evaluation error" ), exp.evalErrorString() );
    return;
  }

  mVectorLayer->beginEditCommand( "Field calculator" );

  //update existing field
  if ( mUpdateExistingGroupBox->isChecked() || !mNewFieldGroupBox->isEnabled() )
  {
    QMap<QString, int>::const_iterator fieldIt = mFieldMap.find( mExistingFieldComboBox->currentText() );
    if ( fieldIt != mFieldMap.end() )
    {
      mAttributeId = fieldIt.value();
    }
  }
  else
  {
    //create new field
    QgsField newField( mOutputFieldNameLineEdit->text(),
                       ( QVariant::Type ) mOutputFieldTypeComboBox->itemData( mOutputFieldTypeComboBox->currentIndex(), Qt::UserRole ).toInt(),
                       mOutputFieldTypeComboBox->itemData( mOutputFieldTypeComboBox->currentIndex(), Qt::UserRole + 1 ).toString(),
                       mOutputFieldWidthSpinBox->value(),
                       mOutputFieldPrecisionSpinBox->value() );

    if ( !mVectorLayer->addAttribute( newField ) )
    {
      QMessageBox::critical( 0, tr( "Provider error" ), tr( "Could not add the new field to the provider." ) );
      mVectorLayer->destroyEditCommand();
      return;
    }

    //get index of the new field
    const QgsFieldMap fieldList = mVectorLayer->pendingFields();

    QgsFieldMap::const_iterator it = fieldList.constBegin();
    for ( ; it != fieldList.constEnd(); ++it )
    {
      if ( it.value().name() == mOutputFieldNameLineEdit->text() )
      {
        mAttributeId = it.key();
        break;
      }
    }
  }

  if ( mAttributeId == -1 )
  {
    mVectorLayer->destroyEditCommand();
    return;
  }

  //go through all the features and change the new attribute
  QgsFeature feature;
  bool calculationSuccess = true;
  QString error;

  bool onlySelected = mOnlyUpdateSelectedCheckBox->isChecked();
  QgsFeatureIds selectedIds = mVectorLayer->selectedFeaturesIds();

  // block layerModified signals (that would trigger table update)
  mVectorLayer->blockSignals( true );

  bool useGeometry = exp.needsGeometry();
  int rownum = 1;

  mVectorLayer->select( mVectorLayer->pendingAllAttributesList(), QgsRectangle(), useGeometry, false );
  while ( mVectorLayer->nextFeature( feature ) )
  {
    if ( onlySelected )
    {
      if ( !selectedIds.contains( feature.id() ) )
      {
        continue;
      }
    }

    exp.setCurrentRowNumber( rownum );
    exp.setGeomCalculator( myDa );

    QVariant value = exp.evaluate( &feature );
    if ( exp.hasEvalError() )
    {
      calculationSuccess = false;
      error = exp.evalErrorString();
      break;
    }
    else
    {
      mVectorLayer->changeAttributeValue( feature.id(), mAttributeId, value, false );
    }

    rownum++;
  }

  // stop blocking layerModified signals and make sure that one layerModified signal is emitted
  mVectorLayer->blockSignals( false );
  mVectorLayer->setModified( true, false );

  if ( !calculationSuccess )
  {
    QMessageBox::critical( 0, tr( "Error" ), tr( "An error occured while evaluating the calculation string:\n%1" ).arg( error ) );
    mVectorLayer->destroyEditCommand();
    return;
  }

  mVectorLayer->endEditCommand();
  QDialog::accept();
}
Пример #18
0
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;
      }
      QgsFieldMap theFieldMap = 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();
        QgsFieldMap::const_iterator field_it = theFieldMap.find( fieldNumber );
        if ( field_it != theFieldMap.constEnd() )
        {
          QDomText fieldName = mDom.createTextNode( field_it.value().name() );
          QDomNode nameNode = classificationFieldElem.firstChild();
          classificationFieldElem.replaceChild( fieldName, nameNode );
        }
      }

    }
  }
}
Пример #19
0
bool QgsFeatureAction::addFeature()
{
  if ( !mLayer || !mLayer->isEditable() )
    return false;

  QgsVectorDataProvider *provider = mLayer->dataProvider();

  QSettings settings;
  bool reuseLastValues = settings.value( "/qgis/digitizing/reuseLastValues", false ).toBool();
  QgsDebugMsg( QString( "reuseLastValues: %1" ).arg( reuseLastValues ) );

  // add the fields to the QgsFeature
  const QgsFieldMap fields = mLayer->pendingFields();
  for ( QgsFieldMap::const_iterator it = fields.constBegin(); it != fields.constEnd(); ++it )
  {
    if ( reuseLastValues && mLastUsedValues.contains( mLayer ) && mLastUsedValues[ mLayer ].contains( it.key() ) )
    {
      QgsDebugMsg( QString( "reusing %1 for %2" ).arg( mLastUsedValues[ mLayer ][ it.key()].toString() ).arg( it.key() ) );
      mFeature.addAttribute( it.key(), mLastUsedValues[ mLayer ][ it.key()] );
    }
    else
    {
      mFeature.addAttribute( it.key(), provider->defaultValue( it.key() ) );
    }
  }

  bool res = false;

  mLayer->beginEditCommand( text() );

  // show the dialog to enter attribute values
  bool isDisabledAttributeValuesDlg = settings.value( "/qgis/digitizing/disable_enter_attribute_values_dialog", false ).toBool();
  if ( isDisabledAttributeValuesDlg )
  {
    res = mLayer->addFeature( mFeature );
  }
  else
  {
    QgsAttributeMap origValues;
    if ( reuseLastValues )
      origValues = mFeature.attributeMap();

    QgsAttributeDialog *dialog = newDialog( false );
    if ( dialog->exec() )
    {
      if ( reuseLastValues )
      {
        for ( QgsFieldMap::const_iterator it = fields.constBegin(); it != fields.constEnd(); ++it )
        {
          const QgsAttributeMap &newValues = mFeature.attributeMap();
          if ( newValues.contains( it.key() )
               && origValues.contains( it.key() )
               && origValues[ it.key()] != newValues[ it.key()] )
          {
            QgsDebugMsg( QString( "saving %1 for %2" ).arg( mLastUsedValues[ mLayer ][ it.key()].toString() ).arg( it.key() ) );
            mLastUsedValues[ mLayer ][ it.key()] = newValues[ it.key()];
          }
        }
      }

      res = mLayer->addFeature( mFeature );
    }
    else
    {
      QgsDebugMsg( "Adding feature to layer failed" );
      res = false;
    }
  }

  if ( res )
    mLayer->endEditCommand();
  else
    mLayer->destroyEditCommand();

  return res;
}