I have this code for create and open raster map:

    QFileInfo myRasterFileInfo(rasterFileName);
    m_pRasterLayer = QSharedPointer<QgsRasterLayer>(
        new QgsRasterLayer(myRasterFileInfo.filePath(), 

    if (m_pRasterLayer->isValid())
            m_pRasterLayer.data(), true);

        QList<QgsMapCanvasLayer> layerList;
        layerList.append(QgsMapCanvasLayer(m_pRasterLayer.data(), true));


        /* ... */

How can I make (write code for) rectangle selection by mouse on my map?


If I got you right, you can have a look at the source code of the class QgsMapToolSelectRectangle to get an idea of how to select by rectangle on your map.

QgsMapToolSelectRectangle allows you to get a rectangle from mouse events, draw it as a rubber band on the QgsMapCanvas and perform a select operation on your data.

This code snippet performs the selection:

  if ( mRubberBand )
    QgsMapToolSelectUtils::setRubberBand( mCanvas, mSelectRect, mRubberBand );

    QgsGeometry* selectGeom = mRubberBand->asGeometry();
    if ( !mDragging )
      bool doDifference = e->modifiers() & Qt::ControlModifier ? true : false;
      QgsMapToolSelectUtils::setSelectFeatures( mCanvas, selectGeom, false, doDifference, true );
      QgsMapToolSelectUtils::setSelectFeatures( mCanvas, selectGeom, e );

    delete selectGeom;

    mRubberBand->reset( QGis::Polygon );
    delete mRubberBand;
    mRubberBand = 0;

As you can see, it relies on the class QgsMapToolSelectUtils, which does the work from line 138 on (setSelectFeatures() method):

QgsFeatureIterator fit = vlayer->getFeatures( QgsFeatureRequest().setFilterRect( selectGeomTrans.boundingBox() ).setFlags( QgsFeatureRequest::ExactIntersect ).setSubsetOfAttributes( QgsAttributeList() ) );

By the way, no idea of your use case, but why not doing it in Python? Are you developing a C++ core plugin?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.