本文整理汇总了C++中QgsVectorLayer::crs方法的典型用法代码示例。如果您正苦于以下问题:C++ QgsVectorLayer::crs方法的具体用法?C++ QgsVectorLayer::crs怎么用?C++ QgsVectorLayer::crs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QgsVectorLayer
的用法示例。
在下文中一共展示了QgsVectorLayer::crs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: refreshExpressionContext
void QgsComposerLabel::refreshExpressionContext()
{
if ( !mComposition )
return;
QgsVectorLayer *layer = nullptr;
if ( mComposition->atlasComposition().enabled() )
{
layer = mComposition->atlasComposition().coverageLayer();
}
//setup distance area conversion
if ( layer )
{
mDistanceArea->setSourceCrs( layer->crs() );
}
else
{
//set to composition's reference map's crs
QgsComposerMap *referenceMap = mComposition->referenceMap();
if ( referenceMap )
mDistanceArea->setSourceCrs( referenceMap->crs() );
}
mDistanceArea->setEllipsoid( mComposition->project()->ellipsoid() );
contentChanged();
update();
}
示例2: estimateRadius
/*
* Estimate a good default radius for the heatmap, based on the
* bounding box size of the layer
*/
double HeatmapGui::estimateRadius()
{
QgsVectorLayer *inputLayer = inputVectorLayer();
// No input layer? Default to radius of 100
if ( !inputLayer )
return 100;
// Find max dimension of layer bounding box
QgsRectangle mExtent = inputLayer->extent();
double maxExtent = max( mExtent.width(), mExtent.height() );
// Return max dimension divided by 30. This is fairly arbitrary
// but approximately corresponds to the default value chosen by ArcMap
// TODO - a better solution is to let the data define the radius
// choice by setting the radius equal to the average Nearest
// Neighbour Index for the closest n points
double estimate = maxExtent / 30;
if ( mBufferUnitCombo->currentIndex() == HeatmapGui::LayerUnits )
{
// layer units selected, so convert estimate from map units
QgsCoordinateReferenceSystem layerCrs = inputLayer->crs();
estimate /= mapUnitsOf( 1, layerCrs );
}
// Make estimate pretty by rounding off to first digit only (eg 356->300, 0.567->0.5)
double tens = pow( 10, floor( log10( estimate ) ) );
return floor( estimate / tens + 0.5 ) * tens;
}
示例3: exportPath
void RgShortestPathWidget::exportPath()
{
RgExportDlg dlg( this );
if ( !dlg.exec() )
return;
QgsVectorLayer *vl = dlg.mapLayer();
if ( vl == NULL )
return;
QgsPoint p1, p2;
QgsGraph *path = getPath( p1, p2 );
if ( path == NULL )
return;
QgsCoordinateTransform ct( mPlugin->iface()->mapCanvas()->mapSettings().destinationCrs(),
vl->crs() );
int startVertexIdx = path->findVertex( p1 );
int stopVertexIdx = path->findVertex( p2 );
double time = 0.0;
double cost = 0.0;
Unit timeUnit = Unit::byName( mPlugin->timeUnitName() );
Unit distanceUnit = Unit::byName( mPlugin->distanceUnitName() );
QgsPolyline p;
while ( startVertexIdx != stopVertexIdx )
{
if ( stopVertexIdx < 0 )
break;
QgsGraphArcIdList l = path->vertex( stopVertexIdx ).inArc();
if ( l.empty() )
break;
const QgsGraphArc& e = path->arc( l.front() );
cost += e.property( 0 ).toDouble();
time += e.property( 1 ).toDouble();
p.push_front( ct.transform( path->vertex( e.inVertex() ).point() ) );
stopVertexIdx = e.outVertex();
}
p.push_front( ct.transform( p1 ) );
QgsFeature f;
f.initAttributes( vl->pendingFields().count() );
f.setGeometry( QgsGeometry::fromPolyline( p ) );
f.setAttribute( 0, cost / distanceUnit.multipler() );
f.setAttribute( 1, time / timeUnit.multipler() );
QgsFeatureList features;
features << f;
vl->dataProvider()->addFeatures( features );
vl->updateExtents();
mPlugin->iface()->mapCanvas()->update();
delete path;
}
示例4: fetchLayerPoint
int QgsMapToolCapture::fetchLayerPoint( const QgsPointLocator::Match &match, QgsPoint &layerPoint )
{
QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( mCanvas->currentLayer() );
QgsVectorLayer *sourceLayer = match.layer();
if ( match.isValid() && match.hasVertex() && sourceLayer &&
( sourceLayer->crs() == vlayer->crs() ) )
{
QgsFeature f;
QgsFeatureRequest request;
request.setFilterFid( match.featureId() );
bool fetched = match.layer()->getFeatures( request ).nextFeature( f );
if ( fetched )
{
QgsVertexId vId;
if ( !f.geometry().vertexIdFromVertexNr( match.vertexIndex(), vId ) )
return 2;
layerPoint = f.geometry().constGet()->vertexAt( vId );
// ZM support depends on the target layer
if ( !QgsWkbTypes::hasZ( vlayer->wkbType() ) )
{
layerPoint.dropZValue();
}
if ( !QgsWkbTypes::hasM( vlayer->wkbType() ) )
{
layerPoint.dropMValue();
}
return 0;
}
else
{
return 2;
}
}
else
{
return 1;
}
}
示例5: updateBBox
void HeatmapGui::updateBBox()
{
// Set the row/cols and cell sizes here
QgsVectorLayer *inputLayer = inputVectorLayer();
if ( !inputLayer )
return;
mBBox = inputLayer->extent();
QgsCoordinateReferenceSystem layerCrs = inputLayer->crs();
double radiusInMapUnits = 0.0;
if ( mRadiusFieldCheckBox->isChecked() )
{
int idx = inputLayer->fields().indexFromName( mRadiusFieldCombo->currentField() );
double maxInField = inputLayer->maximumValue( idx ).toDouble();
if ( mRadiusFieldUnitCombo->currentIndex() == HeatmapGui::LayerUnits )
{
radiusInMapUnits = mapUnitsOf( maxInField, layerCrs );
}
else if ( mRadiusFieldUnitCombo->currentIndex() == HeatmapGui::MapUnits )
{
radiusInMapUnits = maxInField;
}
}
else
{
double radiusValue = mBufferSizeLineEdit->text().toDouble();
if ( mBufferUnitCombo->currentIndex() == HeatmapGui::LayerUnits )
{
radiusInMapUnits = mapUnitsOf( radiusValue, layerCrs );
}
else if ( mBufferUnitCombo->currentIndex() == HeatmapGui::MapUnits )
{
radiusInMapUnits = radiusValue;
}
}
// get the distance converted into map units
mBBox.setXMinimum( mBBox.xMinimum() - radiusInMapUnits );
mBBox.setYMinimum( mBBox.yMinimum() - radiusInMapUnits );
mBBox.setXMaximum( mBBox.xMaximum() + radiusInMapUnits );
mBBox.setYMaximum( mBBox.yMaximum() + radiusInMapUnits );
// Leave number of rows the same, and calculate new corresponding cell size and number of columns
mYcellsize = mBBox.height() / ( mRows - 1 );
mXcellsize = mYcellsize;
mColumns = max( mBBox.width() / mXcellsize + 1, 1 );
updateSize();
}
示例6: updatePaintNode
QSGNode* FeatureListModelHighlight::updatePaintNode( QSGNode* n, QQuickItem::UpdatePaintNodeData* )
{
if ( mDirty && mMapSettings )
{
delete n;
n = new QSGNode;
int count = mModel->rowCount( QModelIndex() );
QgsSGGeometry* sn = 0;
QModelIndex firstIndex = mModel->index( 0, 0, QModelIndex() );
QgsVectorLayer* layer = mModel->data( firstIndex, MultiFeatureListModel::LayerRole ).value<QgsVectorLayer*>();
if ( layer )
{
QgsCoordinateTransform transf( layer->crs(), mMapSettings->destinationCrs() );
for ( int i = 0; i < count; ++i )
{
QgsSGGeometry* gn;
QModelIndex index = mModel->index( i, 0, QModelIndex() );
QgsFeature feature = mModel->data( index, MultiFeatureListModel::FeatureRole ).value<QgsFeature>();
QgsGeometry geom( feature.geometry() );
geom.transform( transf );
if ( mSelection && mSelection->selection() == i )
{
sn = new QgsSGGeometry( geom, mSelectionColor, mWidth );
sn->setFlag( QSGNode::OwnedByParent );
}
else
{
gn = new QgsSGGeometry( geom, mColor, mWidth );
gn->setFlag( QSGNode::OwnedByParent );
n->appendChildNode( gn );
}
}
if ( sn )
n->appendChildNode( sn );
}
mDirty = false;
}
return n;
}
示例7: exportPath
void RgShortestPathWidget::exportPath()
{
RgExportDlg dlg( this );
if ( !dlg.exec() )
return;
QgsVectorLayer *vl = dlg.mapLayer();
if ( vl == NULL )
return;
QgsPoint p1, p2;
QgsGraph *path = getPath( p1, p2 );
if ( path == NULL )
return;
QgsCoordinateTransform ct( mPlugin->iface()->mapCanvas()->mapRenderer()->destinationCrs(),
vl->crs() );
int startVertexIdx = path->findVertex( p1 );
int stopVertexIdx = path->findVertex( p2 );
QgsPolyline p;
while ( startVertexIdx != stopVertexIdx )
{
QgsGraphArcIdList l = path->vertex( stopVertexIdx ).inArc();
if ( l.empty() )
break;
const QgsGraphArc& e = path->arc( l.front() );
p.push_front( ct.transform( path->vertex( e.inVertex() ).point() ) );
stopVertexIdx = e.outVertex();
}
p.push_front( ct.transform( p1 ) );
vl->startEditing();
QgsFeature f;
f.setGeometry( QgsGeometry::fromPolyline( p ) );
vl->addFeature( f );
vl->updateExtents();
mPlugin->iface()->mapCanvas()->update();
delete path;
}
示例8: ct
QgsGeometryCheckError::QgsGeometryCheckError( const QgsGeometryCheck *check,
const QgsGeometryCheckerUtils::LayerFeature &layerFeature,
const QgsPointXY &errorLocation,
QgsVertexId vidx,
const QVariant &value,
ValueType valueType )
: mCheck( check )
, mLayerId( layerFeature.layerId() )
, mFeatureId( layerFeature.feature().id() )
, mErrorLocation( errorLocation )
, mVidx( vidx )
, mValue( value )
, mValueType( valueType )
, mStatus( StatusPending )
{
if ( vidx.part != -1 )
{
mGeometry = QgsGeometry( QgsGeometryCheckerUtils::getGeomPart( layerFeature.geometry().constGet(), vidx.part )->clone() );
}
else
{
mGeometry = layerFeature.geometry();
}
if ( !layerFeature.useMapCrs() )
{
QgsVectorLayer *vl = layerFeature.layer().data();
if ( vl )
{
QgsCoordinateTransform ct( vl->crs(), check->context()->mapCrs, check->context()->transformContext );
try
{
mGeometry.transform( ct );
mErrorLocation = ct.transform( mErrorLocation );
}
catch ( const QgsCsException &e )
{
QgsDebugMsg( QStringLiteral( "Can not show error in current map coordinate reference system" ) );
}
}
}
}
示例9: refreshExpressionContext
void QgsLayoutItemLabel::refreshExpressionContext()
{
if ( !mLayout )
return;
QgsVectorLayer *layer = mLayout->reportContext().layer();
//setup distance area conversion
if ( layer )
{
mDistanceArea->setSourceCrs( layer->crs(), mLayout->project()->transformContext() );
}
else
{
//set to composition's reference map's crs
QgsLayoutItemMap *referenceMap = mLayout->referenceMap();
if ( referenceMap )
mDistanceArea->setSourceCrs( referenceMap->crs(), mLayout->project()->transformContext() );
}
mDistanceArea->setEllipsoid( mLayout->project()->ellipsoid() );
contentChanged();
update();
}
示例10: canvasReleaseEvent
void CDTMapToolSelectTrainingSamples::canvasReleaseEvent(QgsMapMouseEvent *e)
{
if ( e->button() == Qt::LeftButton )
{
if ( mDragging )
{
mCanvas->panActionEnd( e->pos() );
mDragging = false;
}
else // add pan to mouse cursor
{
// transform the mouse pos to map coordinates
QgsPoint center = mCanvas->getCoordinateTransform()->toMapPoint( e->x(), e->y() );
mCanvas->setExtent( QgsRectangle( center, center ) );
mCanvas->refresh();
}
}
else if (e->button()==Qt::RightButton)
{
QgsVectorLayer* vlayer = NULL;
if ( !mapCanvas->currentLayer()
|| ( vlayer = qobject_cast<QgsVectorLayer *>( mapCanvas->currentLayer() ) ) == NULL )
return;
QRect selectRect( 0, 0, 0, 0 );
int boxSize = 1;
selectRect.setLeft ( e->pos().x() - boxSize );
selectRect.setRight ( e->pos().x() + boxSize );
selectRect.setTop ( e->pos().y() - boxSize );
selectRect.setBottom( e->pos().y() + boxSize );
const QgsMapToPixel* transform = mapCanvas->getCoordinateTransform();
QgsPoint ll = transform->toMapCoordinates( selectRect.left(), selectRect.bottom() );
QgsPoint ur = transform->toMapCoordinates( selectRect.right(), selectRect.top() );
QgsPolyline points;
points.push_back(ll);
points.push_back(QgsPoint( ur.x(), ll.y() ));
points.push_back(ur);
points.push_back(QgsPoint( ll.x(), ur.y() ));
QgsPolygon polygon;
polygon.push_back(points);
QgsGeometry selectGeom = *(QgsGeometry::fromPolygon(polygon) );
if ( mapCanvas->mapSettings().hasCrsTransformEnabled() )
{
QgsCoordinateTransform ct( mapCanvas->mapSettings().destinationCrs(), vlayer->crs() );
selectGeom.transform( ct );
}
QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( selectGeom.boundingBox() ).setFlags( QgsFeatureRequest::ExactIntersect ) );
QgsFeature f;
qint64 closestFeatureId = 0;
bool foundSingleFeature = false;
double closestFeatureDist = std::numeric_limits<double>::max();
while ( fit.nextFeature( f ) )
{
QgsGeometry* g = f.geometry();
if ( !selectGeom.intersects( g ) )
continue;
foundSingleFeature = true;
double distance = g->distance( selectGeom );
if ( distance <= closestFeatureDist )
{
closestFeatureDist = distance;
closestFeatureId = f.attribute("GridCode").toInt();
}
}
if ( foundSingleFeature )
addSingleSample( closestFeatureId );
}
}
示例11: coordTransform
bool QgsComposerAttributeTableV2::getTableContents( QgsComposerTableContents &contents )
{
contents.clear();
if (( mSource == QgsComposerAttributeTableV2::AtlasFeature || mSource == QgsComposerAttributeTableV2::RelationChildren )
&& !mComposition->atlasComposition().enabled() )
{
//source mode requires atlas, but atlas disabled
return false;
}
QgsVectorLayer* layer = sourceLayer();
if ( !layer )
{
//no source layer
return false;
}
//prepare filter expression
std::auto_ptr<QgsExpression> filterExpression;
bool activeFilter = false;
if ( mFilterFeatures && !mFeatureFilter.isEmpty() )
{
filterExpression = std::auto_ptr<QgsExpression>( new QgsExpression( mFeatureFilter ) );
if ( !filterExpression->hasParserError() )
{
activeFilter = true;
}
}
QgsRectangle selectionRect;
if ( mComposerMap && mShowOnlyVisibleFeatures )
{
selectionRect = *mComposerMap->currentMapExtent();
if ( layer && mComposition->mapSettings().hasCrsTransformEnabled() )
{
//transform back to layer CRS
QgsCoordinateTransform coordTransform( layer->crs(), mComposition->mapSettings().destinationCrs() );
try
{
selectionRect = coordTransform.transformBoundingBox( selectionRect, QgsCoordinateTransform::ReverseTransform );
}
catch ( QgsCsException &cse )
{
Q_UNUSED( cse );
return false;
}
}
}
QgsFeatureRequest req;
if ( mSource == QgsComposerAttributeTableV2::RelationChildren )
{
QgsRelation relation = QgsProject::instance()->relationManager()->relation( mRelationId );
QgsFeature* atlasFeature = mComposition->atlasComposition().currentFeature();
if ( atlasFeature )
{
req = relation.getRelatedFeaturesRequest( *atlasFeature );
}
else
{
//no atlas feature, so empty table
return true;
}
}
if ( !selectionRect.isEmpty() )
req.setFilterRect( selectionRect );
req.setFlags( mShowOnlyVisibleFeatures ? QgsFeatureRequest::ExactIntersect : QgsFeatureRequest::NoFlags );
if ( mSource == QgsComposerAttributeTableV2::AtlasFeature
&& mComposition->atlasComposition().enabled() )
{
//source mode is current atlas feature
QgsFeature* atlasFeature = mComposition->atlasComposition().currentFeature();
if ( atlasFeature )
{
req.setFilterFid( atlasFeature->id() );
}
else
{
//no atlas feature, so empty table
return true;
}
}
QgsFeature f;
int counter = 0;
QgsFeatureIterator fit = layer->getFeatures( req );
while ( fit.nextFeature( f ) && counter < mMaximumNumberOfFeatures )
{
//check feature against filter
if ( activeFilter )
{
QVariant result = filterExpression->evaluate( &f, layer->pendingFields() );
// skip this feature if the filter evaluation is false
//.........这里部分代码省略.........
示例12: setSelectFeatures
void QgsMapToolSelectUtils::setSelectFeatures( QgsMapCanvas* canvas,
QgsGeometry* selectGeometry,
bool doContains,
bool doDifference,
bool singleSelect )
{
if ( selectGeometry->type() != QGis::Polygon )
{
return;
}
QgsVectorLayer* vlayer = QgsMapToolSelectUtils::getCurrentVectorLayer( canvas );
if ( vlayer == NULL )
{
return;
}
// toLayerCoordinates will throw an exception for any 'invalid' points in
// the rubber band.
// For example, if you project a world map onto a globe using EPSG 2163
// and then click somewhere off the globe, an exception will be thrown.
QgsGeometry selectGeomTrans( *selectGeometry );
if ( canvas->mapSettings().hasCrsTransformEnabled() )
{
try
{
QgsCoordinateTransform ct( canvas->mapSettings().destinationCrs(), vlayer->crs() );
selectGeomTrans.transform( ct );
}
catch ( QgsCsException &cse )
{
Q_UNUSED( cse );
// catch exception for 'invalid' point and leave existing selection unchanged
QgsLogger::warning( "Caught CRS exception " + QString( __FILE__ ) + ": " + QString::number( __LINE__ ) );
QgisApp::instance()->messageBar()->pushMessage(
QObject::tr( "CRS Exception" ),
QObject::tr( "Selection extends beyond layer's coordinate system" ),
QgsMessageBar::WARNING,
QgisApp::instance()->messageTimeout() );
return;
}
}
QApplication::setOverrideCursor( Qt::WaitCursor );
QgsDebugMsg( "Selection layer: " + vlayer->name() );
QgsDebugMsg( "Selection polygon: " + selectGeomTrans.exportToWkt() );
QgsDebugMsg( "doContains: " + QString( doContains ? "T" : "F" ) );
QgsDebugMsg( "doDifference: " + QString( doDifference ? "T" : "F" ) );
QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( selectGeomTrans.boundingBox() ).setFlags( QgsFeatureRequest::ExactIntersect ).setSubsetOfAttributes( QgsAttributeList() ) );
QgsFeatureIds newSelectedFeatures;
QgsFeature f;
QgsFeatureId closestFeatureId = 0;
bool foundSingleFeature = false;
double closestFeatureDist = std::numeric_limits<double>::max();
while ( fit.nextFeature( f ) )
{
QgsGeometry* g = f.geometry();
if ( doContains )
{
if ( !selectGeomTrans.contains( g ) )
continue;
}
else
{
if ( !selectGeomTrans.intersects( g ) )
continue;
}
if ( singleSelect )
{
foundSingleFeature = true;
double distance = g->distance( selectGeomTrans );
if ( distance <= closestFeatureDist )
{
closestFeatureDist = distance;
closestFeatureId = f.id();
}
}
else
{
newSelectedFeatures.insert( f.id() );
}
}
if ( singleSelect && foundSingleFeature )
{
newSelectedFeatures.insert( closestFeatureId );
}
QgsDebugMsg( "Number of new selected features: " + QString::number( newSelectedFeatures.size() ) );
if ( doDifference )
{
QgsFeatureIds layerSelectedFeatures = vlayer->selectedFeaturesIds();
QgsFeatureIds selectedFeatures;
QgsFeatureIds deselectedFeatures;
QgsFeatureIds::const_iterator i = newSelectedFeatures.constEnd();
//.........这里部分代码省略.........
示例13: showProperties
void QgsBrowserDockWidget::showProperties( )
{
QgsDebugMsg( "Entered" );
QgsDataItem* dataItem = mModel->dataItem( mBrowserView->currentIndex() );
if ( dataItem != NULL && dataItem->type() == QgsDataItem::Layer )
{
QgsLayerItem *layerItem = qobject_cast<QgsLayerItem*>( dataItem );
if ( layerItem != NULL )
{
QgsMapLayer::LayerType type = layerItem->mapLayerType();
QString layerMetadata = tr( "Error" );
QgsCoordinateReferenceSystem layerCrs;
QString notice;
// temporarily override /Projections/defaultBehaviour to avoid dialog prompt
QSettings settings;
QString defaultProjectionOption = settings.value( "/Projections/defaultBehaviour", "prompt" ).toString();
if ( settings.value( "/Projections/defaultBehaviour", "prompt" ).toString() == "prompt" )
{
settings.setValue( "/Projections/defaultBehaviour", "useProject" );
}
// find root item
// we need to create a temporary layer to get metadata
// we could use a provider but the metadata is not as complete and "pretty" and this is easier
QgsDebugMsg( QString( "creating temporary layer using path %1" ).arg( layerItem->path() ) );
if ( type == QgsMapLayer::RasterLayer )
{
QgsDebugMsg( "creating raster layer" );
// should copy code from addLayer() to split uri ?
QgsRasterLayer* layer = new QgsRasterLayer( layerItem->uri(), layerItem->uri(), layerItem->providerKey() );
if ( layer != NULL )
{
layerCrs = layer->crs();
layerMetadata = layer->metadata();
delete layer;
}
}
else if ( type == QgsMapLayer::VectorLayer )
{
QgsDebugMsg( "creating vector layer" );
QgsVectorLayer* layer = new QgsVectorLayer( layerItem->uri(), layerItem->name(), layerItem->providerKey() );
if ( layer != NULL )
{
layerCrs = layer->crs();
layerMetadata = layer->metadata();
delete layer;
}
}
// restore /Projections/defaultBehaviour
if ( defaultProjectionOption == "prompt" )
{
settings.setValue( "/Projections/defaultBehaviour", defaultProjectionOption );
}
// initialize dialog
QDialog *dialog = new QDialog( this );
Ui::QgsBrowserLayerPropertiesBase ui;
ui.setupUi( dialog );
dialog->setWindowTitle( tr( "Layer Properties" ) );
ui.leName->setText( layerItem->name() );
ui.leSource->setText( layerItem->path() );
ui.leProvider->setText( layerItem->providerKey() );
QString myStyle = QgsApplication::reportStyleSheet();
ui.txtbMetadata->document()->setDefaultStyleSheet( myStyle );
ui.txtbMetadata->setHtml( layerMetadata );
// report if layer was set to to project crs without prompt (may give a false positive)
if ( defaultProjectionOption == "prompt" )
{
QgsCoordinateReferenceSystem defaultCrs =
QgisApp::instance()->mapCanvas()->mapRenderer()->destinationCrs();
if ( layerCrs == defaultCrs )
ui.lblNotice->setText( "NOTICE: Layer srs set from project (" + defaultCrs.authid() + ")" );
}
dialog->show();
}
}
}
示例14: getMatchingFeatures
QgsFeatureIds QgsMapToolSelectUtils::getMatchingFeatures( QgsMapCanvas *canvas, const QgsGeometry &selectGeometry, bool doContains, bool singleSelect )
{
QgsFeatureIds newSelectedFeatures;
if ( selectGeometry.type() != QgsWkbTypes::PolygonGeometry )
return newSelectedFeatures;
QgsVectorLayer *vlayer = QgsMapToolSelectUtils::getCurrentVectorLayer( canvas );
if ( !vlayer )
return newSelectedFeatures;
// toLayerCoordinates will throw an exception for any 'invalid' points in
// the rubber band.
// For example, if you project a world map onto a globe using EPSG 2163
// and then click somewhere off the globe, an exception will be thrown.
QgsGeometry selectGeomTrans = selectGeometry;
try
{
QgsCoordinateTransform ct( canvas->mapSettings().destinationCrs(), vlayer->crs(), QgsProject::instance() );
if ( !ct.isShortCircuited() && selectGeomTrans.type() == QgsWkbTypes::PolygonGeometry )
{
// convert add more points to the edges of the rectangle
// improve transformation result
QgsPolygonXY poly( selectGeomTrans.asPolygon() );
if ( poly.size() == 1 && poly.at( 0 ).size() == 5 )
{
const QgsPolylineXY &ringIn = poly.at( 0 );
QgsPolygonXY newpoly( 1 );
newpoly[0].resize( 41 );
QgsPolylineXY &ringOut = newpoly[0];
ringOut[ 0 ] = ringIn.at( 0 );
int i = 1;
for ( int j = 1; j < 5; j++ )
{
QgsVector v( ( ringIn.at( j ) - ringIn.at( j - 1 ) ) / 10.0 );
for ( int k = 0; k < 9; k++ )
{
ringOut[ i ] = ringOut[ i - 1 ] + v;
i++;
}
ringOut[ i++ ] = ringIn.at( j );
}
selectGeomTrans = QgsGeometry::fromPolygonXY( newpoly );
}
}
selectGeomTrans.transform( ct );
}
catch ( QgsCsException &cse )
{
Q_UNUSED( cse );
// catch exception for 'invalid' point and leave existing selection unchanged
QgsDebugMsg( QStringLiteral( "Caught CRS exception " ) );
QgisApp::instance()->messageBar()->pushMessage(
QObject::tr( "CRS Exception" ),
QObject::tr( "Selection extends beyond layer's coordinate system" ),
Qgis::Warning,
QgisApp::instance()->messageTimeout() );
return newSelectedFeatures;
}
QgsDebugMsgLevel( "Selection layer: " + vlayer->name(), 3 );
QgsDebugMsgLevel( "Selection polygon: " + selectGeomTrans.asWkt(), 3 );
QgsDebugMsgLevel( "doContains: " + QString( doContains ? "T" : "F" ), 3 );
QgsRenderContext context = QgsRenderContext::fromMapSettings( canvas->mapSettings() );
context.expressionContext() << QgsExpressionContextUtils::layerScope( vlayer );
std::unique_ptr< QgsFeatureRenderer > r;
if ( vlayer->renderer() )
{
r.reset( vlayer->renderer()->clone() );
r->startRender( context, vlayer->fields() );
}
QgsFeatureRequest request;
request.setFilterRect( selectGeomTrans.boundingBox() );
request.setFlags( QgsFeatureRequest::ExactIntersect );
if ( r )
request.setSubsetOfAttributes( r->usedAttributes( context ), vlayer->fields() );
else
request.setNoAttributes();
QgsFeatureIterator fit = vlayer->getFeatures( request );
QgsFeature f;
QgsFeatureId closestFeatureId = 0;
bool foundSingleFeature = false;
double closestFeatureDist = std::numeric_limits<double>::max();
while ( fit.nextFeature( f ) )
{
context.expressionContext().setFeature( f );
// make sure to only use features that are visible
if ( r && !r->willRenderFeature( f, context ) )
continue;
//.........这里部分代码省略.........
示例15: handleDrop
bool QgsPGConnectionItem::handleDrop( const QMimeData *data, const QString &toSchema )
{
if ( !QgsMimeDataUtils::isUriList( data ) )
return false;
// TODO: probably should show a GUI with settings etc
QgsDataSourceUri uri = QgsPostgresConn::connUri( mName );
QStringList importResults;
bool hasError = false;
QgsMimeDataUtils::UriList lst = QgsMimeDataUtils::decodeUriList( data );
const auto constLst = lst;
for ( const QgsMimeDataUtils::Uri &u : constLst )
{
// open the source layer
bool owner;
QString error;
QgsVectorLayer *srcLayer = u.vectorLayer( owner, error );
if ( !srcLayer )
{
importResults.append( tr( "%1: %2" ).arg( u.name, error ) );
hasError = true;
continue;
}
if ( srcLayer->isValid() )
{
uri.setDataSource( QString(), u.name, srcLayer->geometryType() != QgsWkbTypes::NullGeometry ? QStringLiteral( "geom" ) : QString() );
QgsDebugMsg( "URI " + uri.uri( false ) );
if ( !toSchema.isNull() )
{
uri.setSchema( toSchema );
}
QVariantMap options;
options.insert( QStringLiteral( "forceSinglePartGeometryType" ), true );
std::unique_ptr< QgsVectorLayerExporterTask > exportTask( new QgsVectorLayerExporterTask( srcLayer, uri.uri( false ), QStringLiteral( "postgres" ), srcLayer->crs(), options, owner ) );
// when export is successful:
connect( exportTask.get(), &QgsVectorLayerExporterTask::exportComplete, this, [ = ]()
{
// this is gross - TODO - find a way to get access to messageBar from data items
QMessageBox::information( nullptr, tr( "Import to PostGIS database" ), tr( "Import was successful." ) );
refreshSchema( toSchema );
} );
// when an error occurs:
connect( exportTask.get(), &QgsVectorLayerExporterTask::errorOccurred, this, [ = ]( int error, const QString & errorMessage )
{
if ( error != QgsVectorLayerExporter::ErrUserCanceled )
{
QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
output->setTitle( tr( "Import to PostGIS database" ) );
output->setMessage( tr( "Failed to import some layers!\n\n" ) + errorMessage, QgsMessageOutput::MessageText );
output->showMessage();
}
refreshSchema( toSchema );
} );
QgsApplication::taskManager()->addTask( exportTask.release() );
}
else
{
importResults.append( tr( "%1: Not a valid layer!" ).arg( u.name ) );
hasError = true;
}
}
if ( hasError )
{
QgsMessageOutput *output = QgsMessageOutput::createMessageOutput();
output->setTitle( tr( "Import to PostGIS database" ) );
output->setMessage( tr( "Failed to import some layers!\n\n" ) + importResults.join( QStringLiteral( "\n" ) ), QgsMessageOutput::MessageText );
output->showMessage();
}
return true;
}