Ejemplo n.º 1
0
void QgsAttributeTableModel::loadAttributes()
{
  if ( !mLayer )
  {
    return;
  }

  bool ins = false, rm = false;

  QgsAttributeList attributes;
  for ( QgsFieldMap::const_iterator it = mLayer->pendingFields().constBegin(); it != mLayer->pendingFields().end(); it++ )
  {
    switch ( mLayer->editType( it.key() ) )
    {
      case QgsVectorLayer::Hidden:
        continue;

      case QgsVectorLayer::ValueMap:
        mValueMaps.insert( it.key(), &mLayer->valueMap( it.key() ) );
        break;

      default:
        break;
    }

    attributes << it.key();
  }

  if ( mFieldCount < attributes.size() )
  {
    ins = true;
    beginInsertColumns( QModelIndex(), mFieldCount, attributes.size() - 1 );
  }
  else if ( attributes.size() < mFieldCount )
  {
    rm = true;
    beginRemoveColumns( QModelIndex(), attributes.size(), mFieldCount - 1 );
  }

  mFieldCount = attributes.size();
  mAttributes = attributes;
  mValueMaps.clear();

  if ( ins )
  {
    endInsertColumns();
  }
  else if ( rm )
  {
    endRemoveColumns();
  }
}
Ejemplo n.º 2
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;
}
void QgsVectorLayerProperties::loadRows()
{
  const QgsFieldMap &fields = layer->pendingFields();

  tblAttributes->clear();

  tblAttributes->setColumnCount( 8 );
  tblAttributes->setRowCount( fields.size() );
  tblAttributes->setHorizontalHeaderItem( 0, new QTableWidgetItem( tr( "id" ) ) );
  tblAttributes->setHorizontalHeaderItem( 1, new QTableWidgetItem( tr( "name" ) ) );
  tblAttributes->setHorizontalHeaderItem( 2, new QTableWidgetItem( tr( "type" ) ) );
  tblAttributes->setHorizontalHeaderItem( 3, new QTableWidgetItem( tr( "length" ) ) );
  tblAttributes->setHorizontalHeaderItem( 4, new QTableWidgetItem( tr( "precision" ) ) );
  tblAttributes->setHorizontalHeaderItem( 5, new QTableWidgetItem( tr( "comment" ) ) );
  tblAttributes->setHorizontalHeaderItem( 6, new QTableWidgetItem( tr( "edit widget" ) ) );
  tblAttributes->setHorizontalHeaderItem( 7, new QTableWidgetItem( tr( "values" ) ) );

  tblAttributes->setSelectionBehavior( QAbstractItemView::SelectRows );
  tblAttributes->setSelectionMode( QAbstractItemView::MultiSelection );

  int row = 0;
  for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); it++, row++ )
    setRow( row, it.key(), it.value() );

  tblAttributes->resizeColumnsToContents();
}
Ejemplo n.º 4
0
void QgsVectorLayerProperties::loadRows()
{
  QObject::disconnect( tblAttributes, SIGNAL( cellChanged( int, int ) ), this, SLOT( on_tblAttributes_cellChanged( int, int ) ) );
  const QgsFieldMap &fields = layer->pendingFields();

  tblAttributes->clear();

  tblAttributes->setColumnCount( attrColCount );
  tblAttributes->setRowCount( fields.size() );
  tblAttributes->setHorizontalHeaderItem( attrIdCol, new QTableWidgetItem( tr( "Id" ) ) );
  tblAttributes->setHorizontalHeaderItem( attrNameCol, new QTableWidgetItem( tr( "Name" ) ) );
  tblAttributes->setHorizontalHeaderItem( attrTypeCol, new QTableWidgetItem( tr( "Type" ) ) );
  tblAttributes->setHorizontalHeaderItem( attrLengthCol, new QTableWidgetItem( tr( "Length" ) ) );
  tblAttributes->setHorizontalHeaderItem( attrPrecCol, new QTableWidgetItem( tr( "Precision" ) ) );
  tblAttributes->setHorizontalHeaderItem( attrCommentCol, new QTableWidgetItem( tr( "Comment" ) ) );
  tblAttributes->setHorizontalHeaderItem( attrEditTypeCol, new QTableWidgetItem( tr( "Edit widget" ) ) );
  tblAttributes->setHorizontalHeaderItem( attrAliasCol, new QTableWidgetItem( tr( "Alias" ) ) );

  tblAttributes->horizontalHeader()->setResizeMode( 1, QHeaderView::Stretch );
  tblAttributes->horizontalHeader()->setResizeMode( 7, QHeaderView::Stretch );
  tblAttributes->setSelectionBehavior( QAbstractItemView::SelectRows );
  tblAttributes->setSelectionMode( QAbstractItemView::ExtendedSelection );
  tblAttributes->verticalHeader()->hide();

  int row = 0;
  for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); it++, row++ )
    setRow( row, it.key(), it.value() );

  tblAttributes->resizeColumnsToContents();
  QObject::connect( tblAttributes, SIGNAL( cellChanged( int, int ) ), this, SLOT( on_tblAttributes_cellChanged( int, int ) ) );
}
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 );
      }
    }
  }
}
Ejemplo n.º 6
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;
}
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;
}
Ejemplo n.º 8
0
int QgsLabelDialog::fieldIndexFromName( QString name )
{
  const QgsFieldMap& fields = mLabel->fields();
  for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
  {
    if ( it->name() == name )
      return it.key();
  }
  return -1;
}
Ejemplo n.º 9
0
void QgsLabelingGui::populateDataDefinedCombos( QgsPalLayerSettings& s )
{
  QList<QComboBox*> comboList;
  comboList << mSizeAttributeComboBox;
  comboList << mColorAttributeComboBox;
  comboList << mBoldAttributeComboBox;
  comboList << mItalicAttributeComboBox;
  comboList << mUnderlineAttributeComboBox;
  comboList << mStrikeoutAttributeComboBox;
  comboList << mFontFamilyAttributeComboBox;
  comboList << mBufferSizeAttributeComboBox;
  comboList << mBufferColorAttributeComboBox;
  comboList << mXCoordinateComboBox;
  comboList << mYCoordinateComboBox;
  comboList << mHorizontalAlignmentComboBox;
  comboList << mVerticalAlignmentComboBox;
  comboList << mLabelDistanceComboBox;
  comboList << mRotationComboBox;

  QList<QComboBox*>::iterator comboIt = comboList.begin();
  for ( ; comboIt != comboList.end(); ++comboIt )
  {
    ( *comboIt )->addItem( "", QVariant() );
  }

  const QgsFieldMap& fields = mLayer->dataProvider()->fields();
  for ( QgsFieldMap::const_iterator it = fields.constBegin(); it != fields.constEnd(); it++ )
  {
    for ( comboIt = comboList.begin(); comboIt != comboList.end(); ++comboIt )
    {
      ( *comboIt )->addItem( it.value().name(), it.key() );
    }

  }

  //set current combo boxes to already existing indices
  setCurrentComboValue( mSizeAttributeComboBox, s, QgsPalLayerSettings::Size );
  setCurrentComboValue( mColorAttributeComboBox, s, QgsPalLayerSettings::Color );
  setCurrentComboValue( mBoldAttributeComboBox, s, QgsPalLayerSettings::Bold );
  setCurrentComboValue( mItalicAttributeComboBox, s, QgsPalLayerSettings::Italic );
  setCurrentComboValue( mUnderlineAttributeComboBox, s, QgsPalLayerSettings::Underline );
  setCurrentComboValue( mStrikeoutAttributeComboBox, s, QgsPalLayerSettings::Strikeout );
  setCurrentComboValue( mFontFamilyAttributeComboBox, s, QgsPalLayerSettings::Family );
  setCurrentComboValue( mBufferSizeAttributeComboBox, s , QgsPalLayerSettings::BufferSize );
  setCurrentComboValue( mBufferColorAttributeComboBox, s, QgsPalLayerSettings::BufferColor );
  setCurrentComboValue( mXCoordinateComboBox, s, QgsPalLayerSettings::PositionX );
  setCurrentComboValue( mYCoordinateComboBox, s, QgsPalLayerSettings::PositionY );
  setCurrentComboValue( mHorizontalAlignmentComboBox, s, QgsPalLayerSettings::Hali );
  setCurrentComboValue( mVerticalAlignmentComboBox, s, QgsPalLayerSettings::Vali );
  setCurrentComboValue( mLabelDistanceComboBox, s, QgsPalLayerSettings::LabelDistance );
  setCurrentComboValue( mRotationComboBox, s, QgsPalLayerSettings::Rotation );
}
Ejemplo n.º 10
0
void SaQueryBuilder::populateFields()
{
  for ( QgsFieldMap::const_iterator it = mLayer->pendingFields().begin(); it != mLayer->pendingFields().end(); it++ )
  {
    QStandardItem *myItem = new QStandardItem( it->name() );
    myItem->setData( it.key() );
    myItem->setEditable( false );
    mModelFields->insertRow( mModelFields->rowCount(), myItem );
  }

  // All fields get ... setup
  setupLstFieldsModel();
}
Ejemplo n.º 11
0
int QgsVectorDataProvider::fieldNameIndex( const QString& fieldName ) const
{
  const QgsFieldMap &theFields = fields();

  for ( QgsFieldMap::const_iterator it = theFields.constBegin(); it != theFields.constEnd(); ++it )
  {
    if ( QString::compare( it->name(), fieldName, Qt::CaseInsensitive ) == 0 )
    {
      return it.key();
    }
  }
  return -1;
}
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() );
        }
    }
}
Ejemplo n.º 13
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 );
  }
}
Ejemplo n.º 14
0
void QgsSearchQueryBuilder::populateFields()
{
  if ( !mLayer )
    return;

  QgsDebugMsg( "entering." );
  QRegExp reQuote( "[A-Za-z_][A-Za-z0-9_]*" );
  const QgsFieldMap& fields = mLayer->pendingFields();
  for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
  {
    QString fieldName = it->name();
    mFieldMap[fieldName] = it.key();
    if ( !reQuote.exactMatch( fieldName ) ) // quote if necessary
      fieldName = QgsExpression::quotedColumnRef( fieldName );
    QStandardItem *myItem = new QStandardItem( fieldName );
    myItem->setEditable( false );
    mModelFields->insertRow( mModelFields->rowCount(), myItem );
  }
}
Ejemplo n.º 15
0
int QgsSymbol::readFieldName( QDomNode &synode, QString name, const QgsVectorLayer &vl )
{
  QDomNode node = synode.namedItem( name + "name" );

  if ( !node.isNull() )
  {
    const QgsFieldMap &fields = vl.pendingFields();
    QString name = node.toElement().text();

    for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); it++ )
      if ( it->name() == name )
        return it.key();

    return -1;
  }

  node = synode.namedItem( name );

  return node.isNull() ? -1 : node.toElement().text().toInt();
}
QgsUniqueValueDialog::QgsUniqueValueDialog( QgsVectorLayer* vl ): QDialog(), mVectorLayer( vl ), sydialog( vl, true )
{
  setupUi( this );
  setOrientation( Qt::Vertical );

  //find out the fields of mVectorLayer
  if ( mVectorLayer )
  {
    //we cannot use unique values for not-commited fields because QgsVectorLayer has no 'unique values' method...
    QgsVectorDataProvider* provider = mVectorLayer->dataProvider();
    if ( provider )
    {
      const QgsFieldMap & fields = provider->fields();
      QString str;

      for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
      {
        str = ( *it ).name();
        str = mVectorLayer->attributeDisplayName( it.key() );
        mClassificationComboBox->addItem( str, it.key() );
      }
    }
  }


  mClassListWidget->setSelectionMode( QAbstractItemView::ExtendedSelection );
  mClassListWidget->setEditTriggers( QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed | QAbstractItemView::AnyKeyPressed );
  mClassListWidget->setSortingEnabled( true );

  if ( mVectorLayer )
  {
    const QgsUniqueValueRenderer* renderer = dynamic_cast<const QgsUniqueValueRenderer *>( mVectorLayer->renderer() );

    if ( renderer )
    {
      mClassListWidget->clear();
      QString field = mVectorLayer->attributeDisplayName( renderer->classificationField() );
      mOldClassificationAttribute = field;
      mClassificationComboBox->setCurrentIndex( mClassificationComboBox->findText( field ) );

      const QList<QgsSymbol*> list = renderer->symbols();
      //fill the items of the renderer into mValues
      for ( QList<QgsSymbol*>::const_iterator iter = list.begin(); iter != list.end(); ++iter )
      {
        QgsSymbol* symbol = *iter;
        QString symbolvalue = symbol->lowerValue();
        QgsSymbol* sym = new QgsSymbol( mVectorLayer->geometryType(), symbol->lowerValue(), symbol->upperValue(), symbol->label() );
        sym->setPen( symbol->pen() );
        sym->setCustomTexture( symbol->customTexture() );
        sym->setBrush( symbol->brush() );
        sym->setNamedPointSymbol( symbol->pointSymbolName() );
        sym->setPointSize( symbol->pointSize() );
        sym->setPointSizeUnits( symbol->pointSizeUnits() );
        sym->setScaleClassificationField( symbol->scaleClassificationField() );
        sym->setRotationClassificationField( symbol->rotationClassificationField() );
        mValues.insert( symbolvalue, sym );

        QListWidgetItem *item = new QListWidgetItem( symbolvalue );
        mClassListWidget->addItem( item );
        updateEntryIcon( symbol, item );
        item->setFlags( Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled );
        item->setData( Qt::UserRole, symbol->lowerValue() );
        item->setToolTip( symbol->label() );
      }
    }
  }

  mDeletePushButton->setEnabled( false );

  connect( mClassifyButton, SIGNAL( clicked() ), this, SLOT( changeClassificationAttribute() ) );
  connect( mAddButton, SIGNAL( clicked() ), this, SLOT( addClass() ) );
  connect( mDeletePushButton, SIGNAL( clicked() ), this, SLOT( deleteSelectedClasses() ) );
  connect( mRandomizeColors, SIGNAL( clicked() ), this, SLOT( randomizeColors() ) );
  connect( mResetColors, SIGNAL( clicked() ), this, SLOT( resetColors() ) );
  connect( mClassListWidget, SIGNAL( itemSelectionChanged() ), this, SLOT( selectionChanged() ) );
  connect( mCommonPropertyLock, SIGNAL( clicked() ), this, SLOT( selectionChanged() ) );
  connect( mClassListWidget, SIGNAL( itemChanged( QListWidgetItem * ) ), this, SLOT( itemChanged( QListWidgetItem * ) ) );
  connect( &sydialog, SIGNAL( settingsChanged() ), this, SLOT( applySymbologyChanges() ) );
  mSymbolWidgetStack->addWidget( &sydialog );
  mSymbolWidgetStack->setCurrentWidget( &sydialog );
}
Ejemplo n.º 17
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();
}
void QgsMergeAttributesDialog::createTableWidgetContents()
{
  //get information about attributes from vector layer
  if ( !mVectorLayer )
  {
    return;
  }

  //combo box row, attributes titles, feature values and current merge results
  mTableWidget->setRowCount( mFeatureList.size() + 2 );

  //create combo boxes and insert attribute names
  const QgsFieldMap& fieldMap = mVectorLayer->pendingFields();

  int col = 0;
  for ( QgsFieldMap::const_iterator fieldIt = fieldMap.constBegin();
        fieldIt != fieldMap.constEnd();
        ++fieldIt )
  {
    if ( mVectorLayer->editType( fieldIt.key() ) == QgsVectorLayer::Hidden ||
         mVectorLayer->editType( fieldIt.key() ) == QgsVectorLayer::Immutable )
      continue;

    mTableWidget->setColumnCount( col + 1 );

    mTableWidget->setCellWidget( 0, col, createMergeComboBox( fieldIt->type() ) );

    QTableWidgetItem *item = new QTableWidgetItem( fieldIt.value().name() );
    item->setData( Qt::UserRole, fieldIt.key() );
    mTableWidget->setHorizontalHeaderItem( col++, item );
  }

  //insert the attribute values
  QStringList verticalHeaderLabels; //the id column is in the
  verticalHeaderLabels << tr( "Id" );

  for ( int i = 0; i < mFeatureList.size(); ++i )
  {
    verticalHeaderLabels << QString::number( mFeatureList[i].id() );

    const QgsAttributeMap &attrs = mFeatureList[i].attributeMap();

    for ( int j = 0; j < mTableWidget->columnCount(); j++ )
    {
      int idx = mTableWidget->horizontalHeaderItem( j )->data( Qt::UserRole ).toInt();

      QTableWidgetItem* attributeValItem = new QTableWidgetItem( attrs[idx].toString() );
      attributeValItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable );
      mTableWidget->setItem( i + 1, j, attributeValItem );
      mTableWidget->setCellWidget( i + 1, j, QgsAttributeEditor::createAttributeEditor( mTableWidget, NULL, mVectorLayer, idx, attrs[idx] ) );
    }
  }

  //merge
  verticalHeaderLabels << tr( "Merge" );
  mTableWidget->setVerticalHeaderLabels( verticalHeaderLabels );

  //insert currently merged values
  for ( int i = 0; i < mTableWidget->columnCount(); ++i )
  {
    refreshMergedValue( i );
  }
}
Ejemplo n.º 19
0
void QgsSingleSymbolDialog::refreshMarkers()
{
  QgsMarkerListModel *m = new QgsMarkerListModel( lstSymbols );
  lstSymbols->setModel( m );

  connect( lstSymbols->selectionModel(), SIGNAL( currentChanged( const QModelIndex &, const QModelIndex & ) ),
           this, SLOT( symbolChanged( const QModelIndex &, const QModelIndex & ) ) );

  // Find out the numerical fields of mVectorLayer, and populate the ComboBoxes
  QgsVectorDataProvider *provider = mVectorLayer->dataProvider();
  if ( provider )
  {
    const QgsFieldMap & fields = provider->fields();
    QString str;

    mRotationClassificationComboBox->addItem( DO_NOT_USE_STR, -1 );
    mScaleClassificationComboBox->addItem( DO_NOT_USE_STR, -1 );
    mSymbolComboBox->addItem( DO_NOT_USE_STR, -1 );
    for ( QgsFieldMap::const_iterator it = fields.begin();
          it != fields.end();
          ++it )
    {
      QVariant::Type type = ( *it ).type();
      if ( type == QVariant::Int || type == QVariant::Double )
      {
        mRotationClassificationComboBox->addItem( it->name(), it.key() );
        mScaleClassificationComboBox->addItem( it->name(), it.key() );
      }
      else if ( type == QVariant::String )
      {
        mSymbolComboBox->addItem( it->name(), it.key() );
      }
    }
  }
  else
  {
    QgsDebugMsg( "Warning, data provider is null" );
    return;
  }
  //
  //set outline / line style
  //
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "SolidLine" ) ), "", "SolidLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "NoPen" ) ), tr( "None" ), "NoPen" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DashLine" ) ), "", "DashLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DotLine" ) ), "", "DotLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DashDotLine" ) ), "" , "DashDotLine" );
  cboOutlineStyle->addItem( QIcon( QgsSymbologyUtils::char2LinePixmap( "DashDotDotLine" ) ), "", "DashDotDotLine" );

  //
  //set pattern icons and state
  //
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "SolidPattern" ) ), "", "SolidPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "NoBrush" ) ), tr( "None" ), "NoBrush" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "HorPattern" ) ), "", "HorPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "VerPattern" ) ), "", "VerPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "CrossPattern" ) ), "", "CrossPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "BDiagPattern" ) ), "", "BDiagPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "FDiagPattern" ) ), "", "FDiagPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "DiagCrossPattern" ) ), "", "DiagCrossPattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense1Pattern" ) ), "", "Dense1Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense2Pattern" ) ), "", "Dense2Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense3Pattern" ) ), "", "Dense3Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense4Pattern" ) ), "", "Dense4Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense5Pattern" ) ), "", "Dense5Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense6Pattern" ) ), "", "Dense6Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "Dense7Pattern" ) ), "", "Dense7Pattern" );
  cboFillStyle->addItem( QIcon( QgsSymbologyUtils::char2PatternPixmap( "TexturePattern" ) ), tr( "Texture" ), "TexturePattern" );

  if ( mVectorLayer && mVectorLayer->geometryType() != QGis::Point )
  {
    mGroupPoint->setVisible( false );
    mGroupPoint->setEnabled( false );
    mGroupDrawingByField->setVisible( false );
    mGroupDrawingByField->setEnabled( false );
  }

  if ( mDisabled )
  {
    unset();
  }
  else
  {
    if ( mVectorLayer )
    {
      const QgsSingleSymbolRenderer *renderer = dynamic_cast<const QgsSingleSymbolRenderer *>( mVectorLayer->renderer() );

      if ( renderer )
      {
        // Set from the existing renderer
        set( renderer->symbols().first() );
      }
      else
      {
        // Take values from an example instance
        QgsSingleSymbolRenderer exampleRenderer = QgsSingleSymbolRenderer( mVectorLayer->geometryType() );
        set( exampleRenderer.symbols().first() );
      }
    }
    else
    {
      QgsDebugMsg( "Warning, layer is a null pointer" );
    }
  }

  lstSymbols->blockSignals( false );
}
Ejemplo n.º 20
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();
}
Ejemplo n.º 21
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;
}
Ejemplo n.º 22
0
QDomDocument QgsWFSServer::describeFeatureType()
{
  QgsDebugMsg( "Entering." );
  QDomDocument doc;
  //xsd:schema
  QDomElement schemaElement = doc.createElement( "schema"/*xsd:schema*/ );
  schemaElement.setAttribute( "xmlns", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" );
  schemaElement.setAttribute( "xmlns:ogc", "http://www.opengis.net/ogc" );
  schemaElement.setAttribute( "xmlns:gml", "http://www.opengis.net/gml" );
  schemaElement.setAttribute( "xmlns:qgs", "http://www.qgis.org/gml" );
  schemaElement.setAttribute( "targetNamespace", "http://www.qgis.org/gml" );
  doc.appendChild( schemaElement );

  //xsd:import
  QDomElement importElement = doc.createElement( "import"/*xsd:import*/ );
  importElement.setAttribute( "namespace", "http://www.opengis.net/gml" );
  importElement.setAttribute( "schemaLocation", "http://schemas.opengis.net/gml/2.1.2/feature.xsd" );
  schemaElement.appendChild( importElement );

  //read TYPENAME
  QString typeName;
  QMap<QString, QString>::const_iterator type_name_it = mParameterMap.find( "TYPENAME" );
  if ( type_name_it != mParameterMap.end() )
  {
    typeName = type_name_it.value();
  }
  else
  {
    return doc;
  }

  QStringList wfsLayersId = mConfigParser->wfsLayers();
  QMap< QString, QMap< int, QString > > aliasInfo = mConfigParser->layerAliasInfo();
  QMap< QString, QSet<QString> > hiddenAttributes = mConfigParser->hiddenAttributes();

  QList<QgsMapLayer*> layerList;
  QgsMapLayer* currentLayer = 0;

  layerList = mConfigParser->mapLayerFromStyle( typeName, "" );
  currentLayer = layerList.at( 0 );

  QgsVectorLayer* layer = dynamic_cast<QgsVectorLayer*>( currentLayer );
  if ( layer && wfsLayersId.contains( layer->id() ) )
  {
    //is there alias info for this vector layer?
    QMap< int, QString > layerAliasInfo;
    QMap< QString, QMap< int, QString > >::const_iterator aliasIt = aliasInfo.find( currentLayer->id() );
    if ( aliasIt != aliasInfo.constEnd() )
    {
      layerAliasInfo = aliasIt.value();
    }

    //hidden attributes for this layer
    QSet<QString> layerHiddenAttributes;
    QMap< QString, QSet<QString> >::const_iterator hiddenIt = hiddenAttributes.find( currentLayer->id() );
    if ( hiddenIt != hiddenAttributes.constEnd() )
    {
      layerHiddenAttributes = hiddenIt.value();
    }

    //do a select with searchRect and go through all the features
    QgsVectorDataProvider* provider = layer->dataProvider();
    if ( !provider )
    {
      return doc;
    }

    typeName = typeName.replace( QString( " " ), QString( "_" ) );

    //xsd:element
    QDomElement elementElem = doc.createElement( "element"/*xsd:element*/ );
    elementElem.setAttribute( "name", typeName );
    elementElem.setAttribute( "type", "qgs:" + typeName + "Type" );
    elementElem.setAttribute( "substitutionGroup", "gml:_Feature" );
    schemaElement.appendChild( elementElem );

    //xsd:complexType
    QDomElement complexTypeElem = doc.createElement( "complexType"/*xsd:complexType*/ );
    complexTypeElem.setAttribute( "name", typeName + "Type" );
    schemaElement.appendChild( complexTypeElem );

    //xsd:complexType
    QDomElement complexContentElem = doc.createElement( "complexContent"/*xsd:complexContent*/ );
    complexTypeElem.appendChild( complexContentElem );

    //xsd:extension
    QDomElement extensionElem = doc.createElement( "extension"/*xsd:extension*/ );
    extensionElem.setAttribute( "base", "gml:AbstractFeatureType" );
    complexContentElem.appendChild( extensionElem );

    //xsd:sequence
    QDomElement sequenceElem = doc.createElement( "sequence"/*xsd:sequence*/ );
    extensionElem.appendChild( sequenceElem );

    //xsd:element
    QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
    geomElem.setAttribute( "name", "geometry" );
    geomElem.setAttribute( "type", "gml:GeometryPropertyType" );
    geomElem.setAttribute( "minOccurs", "0" );
    geomElem.setAttribute( "maxOccurs", "1" );
    sequenceElem.appendChild( geomElem );

    const QgsFieldMap& fields = provider->fields();
    for ( QgsFieldMap::const_iterator it = fields.begin(); it != fields.end(); ++it )
    {

      QString attributeName = it.value().name();
      //skip attribute if it has edit type 'hidden'
      if ( layerHiddenAttributes.contains( attributeName ) )
      {
        continue;
      }

      //xsd:element
      QDomElement geomElem = doc.createElement( "element"/*xsd:element*/ );
      geomElem.setAttribute( "name", attributeName );
      if ( it.value().type() == 2 )
        geomElem.setAttribute( "type", "integer" );
      else if ( it.value().type() == 6 )
        geomElem.setAttribute( "type", "double" );
      else
        geomElem.setAttribute( "type", "string" );

      sequenceElem.appendChild( geomElem );

      //check if the attribute name should be replaced with an alias
      QMap<int, QString>::const_iterator aliasIt = layerAliasInfo.find( it.key() );
      if ( aliasIt != layerAliasInfo.constEnd() )
      {
        geomElem.setAttribute( "alias", aliasIt.value() );
      }

    }
  }

  return doc;
}
Ejemplo n.º 23
0
void QgsVectorDataProvider::fillMinMaxCache()
{
  if ( !mCacheMinMaxDirty )
    return;

  const QgsFieldMap& flds = fields();
  for ( QgsFieldMap::const_iterator it = flds.begin(); it != flds.end(); ++it )
  {
    if ( it->type() == QVariant::Int )
    {
      mCacheMinValues[it.key()] = QVariant( INT_MAX );
      mCacheMaxValues[it.key()] = QVariant( INT_MIN );
    }
    else if ( it->type() == QVariant::Double )
    {
      mCacheMinValues[it.key()] = QVariant( DBL_MAX );
      mCacheMaxValues[it.key()] = QVariant( -DBL_MAX );
    }
    else
    {
      mCacheMinValues[it.key()] = QVariant();
      mCacheMaxValues[it.key()] = QVariant();
    }
  }

  QgsFeature f;
  QgsAttributeList keys = mCacheMinValues.keys();
  select( keys, QgsRectangle(), false );

  while ( nextFeature( f ) )
  {
    QgsAttributeMap attrMap = f.attributeMap();
    for ( QgsAttributeList::const_iterator it = keys.begin(); it != keys.end(); ++it )
    {
      const QVariant& varValue = attrMap[*it];

      if ( flds[*it].type() == QVariant::Int )
      {
        int value = varValue.toInt();
        if ( value < mCacheMinValues[*it].toInt() )
          mCacheMinValues[*it] = value;
        if ( value > mCacheMaxValues[*it].toInt() )
          mCacheMaxValues[*it] = value;
      }
      else if ( flds[*it].type() == QVariant::Double )
      {
        double value = varValue.toDouble();
        if ( value < mCacheMinValues[*it].toDouble() )
          mCacheMinValues[*it] = value;
        if ( value > mCacheMaxValues[*it].toDouble() )
          mCacheMaxValues[*it] = value;
      }
      else
      {
        QString value = varValue.toString();
        if ( mCacheMinValues[*it].isNull() || value < mCacheMinValues[*it].toString() )
        {
          mCacheMinValues[*it] = value;
        }
        if ( mCacheMaxValues[*it].isNull() || value > mCacheMaxValues[*it].toString() )
        {
          mCacheMaxValues[*it] = value;
        }
      }
    }
  }

  mCacheMinMaxDirty = false;
}