コード例 #1
0
void QgsExpressionSelectionDialog::on_mActionSelectIntersect_triggered()
{
  const QgsFeatureIds &oldSelection = mLayer->selectedFeaturesIds();
  QgsFeatureIds newSelection;

  QgsExpression* expression = new QgsExpression( mExpressionBuilder->expressionText() );

  QgsExpressionContext context;
  context << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope()
  << QgsExpressionContextUtils::layerScope( mLayer );

  expression->prepare( &context );

  QgsFeature feat;
  Q_FOREACH ( const QgsFeatureId fid, oldSelection )
  {
    QgsFeatureIterator features = mLayer->getFeatures( QgsFeatureRequest().setFilterFid( fid ) );

    if ( features.nextFeature( feat ) )
    {
      context.setFeature( feat );
      if ( expression->evaluate( &context ).toBool() )
      {
        newSelection << feat.id();
      }
    }
    else
    {
      Q_ASSERT( false );
    }

    features.close();
  }
コード例 #2
0
QString QgsRelationReferenceFieldFormatter::representValue( QgsVectorLayer* layer, int fieldIndex, const QVariantMap& config, const QVariant& cache, const QVariant& value ) const
{
  Q_UNUSED( cache );

  // Some sanity checks
  if ( !config.contains( QStringLiteral( "Relation" ) ) )
  {
    QgsMessageLog::logMessage( "Missing Relation in configuration" );
    return value.toString();
  }
  QgsRelation relation = QgsProject::instance()->relationManager()->relation( config[QStringLiteral( "Relation" )].toString() );
  if ( !relation.isValid() )
  {
    QgsMessageLog::logMessage( "Invalid relation" );
    return value.toString();
  }
  QgsVectorLayer* referencingLayer = relation.referencingLayer();
  if ( layer != referencingLayer )
  {
    QgsMessageLog::logMessage( "representValue() with inconsistent layer parameter w.r.t relation referencingLayer" );
    return value.toString();
  }
  int referencingFieldIdx = referencingLayer->fields().lookupField( relation.fieldPairs().at( 0 ).first );
  if ( referencingFieldIdx != fieldIndex )
  {
    QgsMessageLog::logMessage( "representValue() with inconsistent fieldIndex parameter w.r.t relation referencingFieldIdx" );
    return value.toString();
  }
  QgsVectorLayer* referencedLayer = relation.referencedLayer();
  if ( !referencedLayer )
  {
    QgsMessageLog::logMessage( "Cannot find referenced layer" );
    return value.toString();
  }

  // Attributes from the referencing layer
  QgsAttributes attrs = QgsAttributes( layer->fields().count() );
  // Set the value on the foreign key field of the referencing record
  attrs[ referencingFieldIdx ] = value;

  QgsFeatureRequest request = relation.getReferencedFeatureRequest( attrs );
  QgsFeature feature;
  referencedLayer->getFeatures( request ).nextFeature( feature );
  if ( !feature.isValid() )
    return value.toString();

  QgsExpression expr( referencedLayer->displayExpression() );
  QgsExpressionContext context;
  context << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope()
  << QgsExpressionContextUtils::layerScope( referencedLayer );
  context.setFeature( feature );
  QString title = expr.evaluate( &context ).toString();
  if ( expr.hasEvalError() )
  {
    int referencedFieldIdx = referencedLayer->fields().lookupField( relation.fieldPairs().at( 0 ).second );
    title = feature.attribute( referencedFieldIdx ).toString();
  }
  return title;
}
コード例 #3
0
QgsExpressionContext QgsGraduatedSymbolRendererWidget::createExpressionContext() const
{
  QgsExpressionContext expContext;
  expContext << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope( QgsProject::instance() )
  << QgsExpressionContextUtils::atlasScope( nullptr );

  if ( mContext.mapCanvas() )
  {
    expContext << QgsExpressionContextUtils::mapSettingsScope( mContext.mapCanvas()->mapSettings() )
    << new QgsExpressionContextScope( mContext.mapCanvas()->expressionContextScope() );
  }
  else
  {
    expContext << QgsExpressionContextUtils::mapSettingsScope( QgsMapSettings() );
  }

  if ( vectorLayer() )
    expContext << QgsExpressionContextUtils::layerScope( vectorLayer() );

  // additional scopes
  Q_FOREACH ( const QgsExpressionContextScope& scope, mContext.additionalExpressionContextScopes() )
  {
    expContext.appendScope( new QgsExpressionContextScope( scope ) );
  }

  return expContext;
}
コード例 #4
0
ファイル: qgstextdiagram.cpp プロジェクト: AM7000000/QGIS
QSizeF QgsTextDiagram::diagramSize( const QgsFeature& feature, const QgsRenderContext& c, const QgsDiagramSettings& s, const QgsDiagramInterpolationSettings& is )
{
  QgsExpressionContext expressionContext = c.expressionContext();
  expressionContext.setFeature( feature );
  if ( feature.fields() )
    expressionContext.setFields( *feature.fields() );

  QVariant attrVal;
  if ( is.classificationAttributeIsExpression )
  {
    QgsExpression* expression = getExpression( is.classificationAttributeExpression, expressionContext );
    attrVal = expression->evaluate( &expressionContext );
  }
  else
  {
    attrVal = feature.attributes().at( is.classificationAttribute );
  }

  bool ok = false;
  double val = attrVal.toDouble( &ok );
  if ( !ok )
  {
    return QSizeF(); //zero size if attribute is missing
  }

  return sizeForValue( val, s, is );
}
コード例 #5
0
QgsRenderContext QgsPointMarkerItem::renderContext( QPainter* painter )
{
  QgsExpressionContext context;
  context << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope()
  << QgsExpressionContextUtils::atlasScope( nullptr );
  if ( mMapCanvas )
  {
    context << QgsExpressionContextUtils::mapSettingsScope( mMapCanvas->mapSettings() )
    << new QgsExpressionContextScope( mMapCanvas->expressionContextScope() );
  }
  else
  {
    context << QgsExpressionContextUtils::mapSettingsScope( QgsMapSettings() );
  }
  //context << QgsExpressionContextUtils::layerScope( mLayer );
  context.setFeature( mFeature );

  //setup render context
  QgsMapSettings ms = mMapCanvas->mapSettings();
  ms.setExpressionContext( context );
  QgsRenderContext rc = QgsRenderContext::fromMapSettings( ms );
  rc.setPainter( painter );

  return rc;
}
コード例 #6
0
void QgsRelationReferenceWidget::setForeignKey( const QVariant& value )
{
  if ( !value.isValid() || value.isNull() )
  {
    deleteForeignKey();
    return;
  }

  if ( !mReferencedLayer )
    return;

  QgsAttributes attrs = QgsAttributes( mReferencingLayer->fields().count() );
  attrs[mFkeyFieldIdx] = value;

  QgsFeatureRequest request = mRelation.getReferencedFeatureRequest( attrs );

  mReferencedLayer->getFeatures( request ).nextFeature( mFeature );

  if ( !mFeature.isValid() )
  {
    deleteForeignKey();
    return;
  }

  mForeignKey = mFeature.attribute( mFkeyFieldIdx );

  if ( mReadOnlySelector )
  {
    QgsExpression expr( mReferencedLayer->displayExpression() );
    QgsExpressionContext context;
    context << QgsExpressionContextUtils::globalScope()
    << QgsExpressionContextUtils::projectScope()
    << QgsExpressionContextUtils::layerScope( mReferencedLayer );
    context.setFeature( mFeature );
    QString title = expr.evaluate( &context ).toString();
    if ( expr.hasEvalError() )
    {
      title = mFeature.attribute( mFkeyFieldIdx ).toString();
    }
    mLineEdit->setText( title );
  }
  else
  {
    int i = mComboBox->findData( mFeature.id(), QgsAttributeTableModel::FeatureIdRole );
    if ( i == -1 && mAllowNull )
    {
      mComboBox->setCurrentIndex( 0 );
    }
    else
    {
      mComboBox->setCurrentIndex( i );
    }
  }

  mRemoveFKButton->setEnabled( mIsEditable );
  highlightFeature( mFeature );
  updateAttributeEditorFrame( mFeature );
  emit foreignKeyChanged( foreignKey() );
}
コード例 #7
0
void QgsEditorWidgetWrapper::updateConstraint( const QgsFeature &ft )
{
  bool toEmit( false );
  QString errStr( tr( "predicate is True" ) );
  QString expression = layer()->editFormConfig().constraintExpression( mFieldIdx );
  QString description;
  QVariant value = ft.attribute( mFieldIdx );

  if ( ! expression.isEmpty() )
  {
    description = layer()->editFormConfig().constraintDescription( mFieldIdx );

    QgsExpressionContext context = layer()->createExpressionContext();
    context.setFeature( ft );

    QgsExpression expr( expression );

    mValidConstraint = expr.evaluate( &context ).toBool();

    if ( expr.hasParserError() )
      errStr = expr.parserErrorString();
    else if ( expr.hasEvalError() )
      errStr = expr.evalErrorString();
    else if ( ! mValidConstraint )
      errStr = tr( "predicate is False" );

    toEmit = true;
  }
  else
    mValidConstraint = true;

  if ( layer()->editFormConfig().notNull( mFieldIdx ) )
  {
    if ( !expression.isEmpty() )
    {
      QString fieldName = ft.fields().field( mFieldIdx ).name();
      expression = "( " + expression + " ) AND ( " + fieldName + " IS NOT NULL)";
      description = "( " + description + " ) AND NotNull";
    }
    else
    {
      description = QStringLiteral( "NotNull" );
      expression = QStringLiteral( "NotNull" );
    }

    mValidConstraint = mValidConstraint && !value.isNull();

    if ( value.isNull() )
      errStr = tr( "predicate is False" );

    toEmit = true;
  }

  if ( toEmit )
  {
    updateConstraintWidgetStatus( mValidConstraint );
    emit constraintStatusChanged( expression, description, errStr, mValidConstraint );
  }
}
コード例 #8
0
QgsExpressionContext* QgsAggregateCalculator::createContext() const
{
  QgsExpressionContext* context = new QgsExpressionContext();
  context->appendScope( QgsExpressionContextUtils::globalScope() );
  context->appendScope( QgsExpressionContextUtils::projectScope() );
  context->appendScope( QgsExpressionContextUtils::layerScope( mLayer ) );
  return context;
}
コード例 #9
0
ファイル: qgslayout.cpp プロジェクト: NathanW2/QGIS
QgsExpressionContext QgsLayout::createExpressionContext() const
{
  QgsExpressionContext context = QgsExpressionContext();
  context.appendScope( QgsExpressionContextUtils::globalScope() );
  context.appendScope( QgsExpressionContextUtils::projectScope( mProject ) );
  context.appendScope( QgsExpressionContextUtils::layoutScope( this ) );
  return context;
}
コード例 #10
0
QString QgsAttributeAction::expandAction( QString action, QgsFeature &feat, const QMap<QString, QVariant> *substitutionMap )
{
  // This function currently replaces each expression between [% and %]
  // in the action with the result of its evaluation on the feature
  // passed as argument.

  // Additional substitutions can be passed through the substitutionMap
  // parameter

  QString expr_action;

  int index = 0;
  while ( index < action.size() )
  {
    QRegExp rx = QRegExp( "\\[%([^\\]]+)%\\]" );

    int pos = rx.indexIn( action, index );
    if ( pos < 0 )
      break;

    int start = index;
    index = pos + rx.matchedLength();

    QString to_replace = rx.cap( 1 ).trimmed();
    QgsDebugMsg( "Found expression: " + to_replace );

    if ( substitutionMap && substitutionMap->contains( to_replace ) )
    {
      expr_action += action.mid( start, pos - start ) + substitutionMap->value( to_replace ).toString();
      continue;
    }

    QgsExpression exp( to_replace );
    if ( exp.hasParserError() )
    {
      QgsDebugMsg( "Expression parser error: " + exp.parserErrorString() );
      expr_action += action.mid( start, index - start );
      continue;
    }

    QgsExpressionContext context = createExpressionContext();
    context.setFeature( feat );

    QVariant result = exp.evaluate( &context );
    if ( exp.hasEvalError() )
    {
      QgsDebugMsg( "Expression parser eval error: " + exp.evalErrorString() );
      expr_action += action.mid( start, index - start );
      continue;
    }

    QgsDebugMsg( "Expression result is: " + result.toString() );
    expr_action += action.mid( start, pos - start ) + result.toString();
  }

  expr_action += action.mid( index );
  return expr_action;
}
コード例 #11
0
// This method tests the number of records that would be returned
long QgsSearchQueryBuilder::countRecords( const QString& searchString )
{
  QgsExpression search( searchString );
  if ( search.hasParserError() )
  {
    QMessageBox::critical( this, tr( "Search string parsing error" ), search.parserErrorString() );
    return -1;
  }

  if ( !mLayer )
    return -1;

  bool fetchGeom = search.needsGeometry();

  int count = 0;
  QgsFeature feat;

  QgsExpressionContext context;
  context << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope()
  << QgsExpressionContextUtils::layerScope( mLayer );

  if ( !search.prepare( &context ) )
  {
    QMessageBox::critical( this, tr( "Evaluation error" ), search.evalErrorString() );
    return -1;
  }

  QApplication::setOverrideCursor( Qt::WaitCursor );

  QgsFeatureIterator fit = mLayer->getFeatures( QgsFeatureRequest().setFlags( fetchGeom ? QgsFeatureRequest::NoFlags : QgsFeatureRequest::NoGeometry ) );

  while ( fit.nextFeature( feat ) )
  {
    context.setFeature( feat );
    QVariant value = search.evaluate( &context );
    if ( value.toInt() != 0 )
    {
      count++;
    }

    // check if there were errors during evaulating
    if ( search.hasEvalError() )
      break;
  }

  QApplication::restoreOverrideCursor();

  if ( search.hasEvalError() )
  {
    QMessageBox::critical( this, tr( "Error during search" ), search.evalErrorString() );
    return -1;
  }

  return count;
}
コード例 #12
0
void QgsLayoutItemPropertiesWidget::updateVariables()
{
  if ( !mItem )
    return;

  QgsExpressionContext context = mItem->createExpressionContext();
  mVariableEditor->setContext( &context );
  int editableIndex = context.indexOfScope( tr( "Layout Item" ) );
  if ( editableIndex >= 0 )
    mVariableEditor->setEditableScopeIndex( editableIndex );
}
コード例 #13
0
QgsExpressionContext *QgsComposerAttributeTableV2::createExpressionContext() const
{
  QgsExpressionContext* context = QgsComposerTableV2::createExpressionContext();

  if ( mSource == LayerAttributes )
  {
    context->appendScope( QgsExpressionContextUtils::layerScope( mVectorLayer ) );
  }

  return context;
}
コード例 #14
0
QgsExpressionContext QgsComposerColumnSourceDelegate::createExpressionContext() const
{
  if ( !mComposerObject )
  {
    return QgsExpressionContext();
  }

  QgsExpressionContext expContext = mComposerObject->createExpressionContext();
  expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), 1, true ) );
  expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) );
  return expContext;
}
コード例 #15
0
ファイル: qgscomposerframe.cpp プロジェクト: V17nika/QGIS
QgsExpressionContext QgsComposerFrame::createExpressionContext() const
{
  if ( !mMultiFrame )
    return QgsComposerItem::createExpressionContext();

  //start with multiframe's context
  QgsExpressionContext context = mMultiFrame->createExpressionContext();
  //add frame's individual context
  context.appendScope( QgsExpressionContextUtils::composerItemScope( this ) );

  return context;
}
コード例 #16
0
void QgsCodeEditorExpression::setExpressionContext( const QgsExpressionContext &context )
{
  mVariables.clear();

  const QStringList variableNames = context.filteredVariableNames();
  for ( const QString &var : variableNames )
  {
    mVariables << '@' + var;
  }

  mContextFunctions = context.functionNames();

  mFunctions.clear();

  const int count = QgsExpression::functionCount();
  for ( int i = 0; i < count; i++ )
  {
    QgsExpressionFunction *func = QgsExpression::Functions()[i];
    if ( func->isDeprecated() ) // don't show deprecated functions
      continue;
    if ( func->isContextual() )
    {
      //don't show contextual functions by default - it's up the the QgsExpressionContext
      //object to provide them if supported
      continue;
    }

    QString signature = func->name();
    if ( !signature.startsWith( '$' ) )
    {
      signature += '(';

      QStringList paramNames;
      const auto &parameters = func->parameters();
      for ( const auto &param : parameters )
      {
        paramNames << param.name();
      }

      // No named parameters but there should be parameteres? Show an ellipsis at least
      if ( parameters.isEmpty() && func->params() )
        signature += QChar( 0x2026 );

      signature += paramNames.join( ", " );

      signature += ')';
    }
    mFunctions << signature;
  }

  updateApis();
}
コード例 #17
0
QVariantMap QgsProcessingFeatureBasedAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
  prepareSource( parameters, context );
  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest,
                                          outputFields( mSource->fields() ),
                                          outputWkbType( mSource->wkbType() ),
                                          outputCrs( mSource->sourceCrs() ),
                                          sinkFlags() ) );
  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  // prepare expression context for feature iteration
  QgsExpressionContext prevContext = context.expressionContext();
  QgsExpressionContext algContext = prevContext;

  algContext.appendScopes( createExpressionContext( parameters, context, mSource.get() ).takeScopes() );
  context.setExpressionContext( algContext );

  long count = mSource->featureCount();

  QgsFeature f;
  QgsFeatureIterator it = mSource->getFeatures( request(), sourceFlags() );

  double step = count > 0 ? 100.0 / count : 1;
  int current = 0;
  while ( it.nextFeature( f ) )
  {
    if ( feedback->isCanceled() )
    {
      break;
    }

    context.expressionContext().setFeature( f );
    const QgsFeatureList transformed = processFeature( f, context, feedback );
    for ( QgsFeature transformedFeature : transformed )
      sink->addFeature( transformedFeature, QgsFeatureSink::FastInsert );

    feedback->setProgress( current * step );
    current++;
  }

  mSource.reset();

  // probably not necessary - context's aren't usually recycled, but can't hurt
  context.setExpressionContext( prevContext );

  QVariantMap outputs;
  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
  return outputs;
}
コード例 #18
0
ファイル: qgslayout.cpp プロジェクト: exlimit/QGIS
QgsExpressionContext QgsLayout::createExpressionContext() const
{
  QgsExpressionContext context = QgsExpressionContext();
  context.appendScope( QgsExpressionContextUtils::globalScope() );
  context.appendScope( QgsExpressionContextUtils::projectScope( mProject ) );
  context.appendScope( QgsExpressionContextUtils::layoutScope( this ) );
#if 0 //TODO
  if ( mAtlasComposition.enabled() )
  {
    context.appendScope( QgsExpressionContextUtils::atlasScope( &mAtlasComposition ) );
  }
#endif
  return context;
}
コード例 #19
0
ファイル: qgscomposerobject.cpp プロジェクト: AM7000000/QGIS
QgsExpressionContext* QgsComposerObject::createExpressionContext() const
{
  QgsExpressionContext* context = nullptr;
  if ( mComposition )
  {
    context = mComposition->createExpressionContext();
  }
  else
  {
    context = new QgsExpressionContext();
    context->appendScope( QgsExpressionContextUtils::globalScope() );
    context->appendScope( QgsExpressionContextUtils::projectScope() );
  }
  return context;
}
コード例 #20
0
QgsExpressionContext QgsProcessingAlgorithm::createExpressionContext( const QVariantMap &parameters,
    QgsProcessingContext &context ) const
{
  // start with context's expression context
  QgsExpressionContext c = context.expressionContext();
  if ( c.scopeCount() == 0 )
  {
    //empty scope, populate with initial scopes
    c << QgsExpressionContextUtils::globalScope()
      << QgsExpressionContextUtils::projectScope( context.project() );
  }

  c << QgsExpressionContextUtils::processingAlgorithmScope( this, parameters, context );
  return c;
}
コード例 #21
0
QgsExpressionContext QgsAttributeTableDialog::createExpressionContext() const
{
  QgsExpressionContext expContext;
  expContext << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope();

  if ( mLayer )
    expContext << QgsExpressionContextUtils::layerScope( mLayer );

  expContext.lastScope()->addVariable( QgsExpressionContextScope::StaticVariable( QStringLiteral( "row_number" ), 1, true ) );

  expContext.setHighlightedVariables( QStringList() << QStringLiteral( "row_number" ) );

  return expContext;
}
コード例 #22
0
ファイル: qgsqmlwidgetwrapper.cpp プロジェクト: alexbruy/QGIS
void QgsQmlWidgetWrapper::setQmlContext( )
{
  if ( !mWidget )
    return;

  QgsAttributeEditorContext attributecontext = context();
  QgsExpressionContext expressionContext = layer()->createExpressionContext();
  expressionContext << QgsExpressionContextUtils::formScope( mFeature, attributecontext.attributeFormModeString() );
  expressionContext.setFeature( mFeature );

  QmlExpression *qmlExpression = new QmlExpression();
  qmlExpression->setExpressionContext( expressionContext );

  mWidget->rootContext()->setContextProperty( "expression", qmlExpression );
}
コード例 #23
0
QgsExpressionContext QgsAttributeTableDialog::createExpressionContext() const
{
  QgsExpressionContext expContext;
  expContext << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope();

  if ( mLayer )
    expContext << QgsExpressionContextUtils::layerScope( mLayer );

  expContext.lastScope()->setVariable( "row_number", 1 );

  expContext.setHighlightedVariables( QStringList() << "row_number" );

  return expContext;
}
コード例 #24
0
QgsExpressionContext QgsAttributeActionPropertiesDialog::createExpressionContext() const
{
  QgsExpressionContext context = mLayer->createExpressionContext();

  Q_FOREACH ( QCheckBox* cb, mActionScopeCheckBoxes )
  {
    if ( cb->isChecked() )
    {
      QgsActionScope actionScope = QgsApplication::actionScopeRegistry()->actionScope( cb->property( "ActionScopeName" ).toString() );
      context.appendScope( new QgsExpressionContextScope( actionScope.expressionContextScope() ) );
    }
  }

  return context;
}
コード例 #25
0
static QgsExpressionContext _getExpressionContext( const void* context )
{
  QgsExpressionContext expContext;
  expContext << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope();

  const QgsVectorLayer* layer = ( const QgsVectorLayer* ) context;
  if ( layer )
    expContext << QgsExpressionContextUtils::layerScope( layer );

  expContext.lastScope()->setVariable( "row_number", 1 );

  expContext.setHighlightedVariables( QStringList() << "row_number" );

  return expContext;
}
コード例 #26
0
QgsExpressionContext QgsPointDisplacementRendererWidget::createExpressionContext() const
{
  QgsExpressionContext context;
  if ( mContext.expressionContext() )
    context = *mContext.expressionContext();
  else
    context.appendScopes( mContext.globalProjectAtlasMapLayerScopes( mLayer ) );
  QgsExpressionContextScope scope;
  scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "", true ) );
  scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0, true ) );
  QList< QgsExpressionContextScope > scopes = mContext.additionalExpressionContextScopes();
  scopes << scope;
  Q_FOREACH ( const QgsExpressionContextScope &s, scopes )
  {
    context << new QgsExpressionContextScope( s );
  }
コード例 #27
0
QgsExpressionContext QgsAtlasComposition::createExpressionContext()
{
  QgsExpressionContext expressionContext;
  expressionContext << QgsExpressionContextUtils::globalScope()
  << QgsExpressionContextUtils::projectScope();
  if ( mComposition )
    expressionContext << QgsExpressionContextUtils::compositionScope( mComposition );

  expressionContext.appendScope( QgsExpressionContextUtils::atlasScope( this ) );
  if ( mCoverageLayer )
    expressionContext.lastScope()->setFields( mCoverageLayer->fields() );
  if ( mComposition && mComposition->atlasMode() != QgsComposition::AtlasOff )
    expressionContext.lastScope()->setFeature( mCurrentFeature );

  return expressionContext;
}
コード例 #28
0
QSizeF QgsHistogramDiagram::diagramSize( const QgsFeature& feature, const QgsRenderContext& c, const QgsDiagramSettings& s, const QgsDiagramInterpolationSettings& is )
{
  QSizeF size;
  if ( feature.attributes().isEmpty() )
  {
    return size; //zero size if no attributes
  }

  if ( qgsDoubleNear( is.upperValue, is.lowerValue ) )
    return size; // invalid value range => zero size

  double maxValue = 0;

  QgsExpressionContext expressionContext = c.expressionContext();
  expressionContext.setFeature( feature );
  if ( !feature.fields().isEmpty() )
    expressionContext.setFields( feature.fields() );

  Q_FOREACH ( const QString& cat, s.categoryAttributes )
  {
    QgsExpression* expression = getExpression( cat, expressionContext );
    maxValue = qMax( expression->evaluate( &expressionContext ).toDouble(), maxValue );
  }

  // Scale, if extension is smaller than the specified minimum
  if ( maxValue < s.minimumSize )
  {
    maxValue = s.minimumSize;
  }

  switch ( s.diagramOrientation )
  {
    case QgsDiagramSettings::Up:
    case QgsDiagramSettings::Down:
      mScaleFactor = (( is.upperSize.width() - is.lowerSize.height() ) / ( is.upperValue - is.lowerValue ) );
      size.scale( s.barWidth * s.categoryAttributes.size(), maxValue * mScaleFactor, Qt::IgnoreAspectRatio );
      break;

    case QgsDiagramSettings::Right:
    case QgsDiagramSettings::Left:
      mScaleFactor = (( is.upperSize.width() - is.lowerSize.width() ) / ( is.upperValue - is.lowerValue ) );
      size.scale( maxValue * mScaleFactor, s.barWidth * s.categoryAttributes.size(), Qt::IgnoreAspectRatio );
      break;
  }

  return size;
}
コード例 #29
0
void QgsAttributeTypeDialog::defaultExpressionChanged()
{
  QString expression = mExpressionWidget->expression();
  if ( expression.isEmpty() )
  {
    mDefaultPreviewLabel->setText( QString() );
    return;
  }

  QgsExpressionContext context = mLayer->createExpressionContext();

  if ( !mPreviewFeature.isValid() )
  {
    // get first feature
    QgsFeatureIterator it = mLayer->getFeatures( QgsFeatureRequest().setLimit( 1 ) );
    it.nextFeature( mPreviewFeature );
  }

  context.setFeature( mPreviewFeature );

  QgsExpression exp = QgsExpression( expression );
  exp.prepare( &context );

  if ( exp.hasParserError() )
  {
    mDefaultPreviewLabel->setText( "<i>" + exp.parserErrorString() + "</i>" );
    return;
  }

  QVariant val = exp.evaluate( &context );
  if ( exp.hasEvalError() )
  {
    mDefaultPreviewLabel->setText( "<i>" + exp.evalErrorString() + "</i>" );
    return;
  }

  QString previewText = val.toString();

  QgsEditorWidgetFactory *factory = QgsEditorWidgetRegistry::instance()->factory( editorWidgetType() );
  if ( factory )
  {
    previewText = factory->representValue( mLayer, mFieldIdx, editorWidgetConfig(), QVariant(), val );
  }

  mDefaultPreviewLabel->setText( "<i>" + previewText + "</i>" );
}
コード例 #30
0
QgsExpressionContext QgsLayoutAtlas::createExpressionContext()
{
  QgsExpressionContext expressionContext;
  expressionContext << QgsExpressionContextUtils::globalScope();
  if ( mLayout )
    expressionContext << QgsExpressionContextUtils::projectScope( mLayout->project() )
                      << QgsExpressionContextUtils::layoutScope( mLayout );

  expressionContext.appendScope( QgsExpressionContextUtils::atlasScope( this ) );

  if ( mCoverageLayer )
    expressionContext.lastScope()->setFields( mCoverageLayer->fields() );

  if ( mLayout && mEnabled )
    expressionContext.lastScope()->setFeature( mCurrentFeature );

  return expressionContext;
}