1

I am migrating a plugin from QGIS 2 to QGIS 3. The following code is QGIS 2:

    # Define a mapscale-dependent rectangle about the pick point.
    pntGeom = QgsGeometry.fromPoint(point)
    pntBuf = pntGeom.buffer(canvas.mapUnitsPerPixel()*4, 0)
    rect = pntBuf.boundingBox()    

    # Convert the rectangle coordinates to the layer CRS.
    layerRect = canvas.mapRenderer().mapToLayerCoordinates(layer, rect)

    # Select the features that are in the rectangle and return their fids.
    layer.removeSelection()
    layer.select(layerRect, True)
    fids= layer.selectedFeaturesIds()

where canvas is a self.iface.mapCanvas() object and layer is a QgsVectorLayer object.

I need this to work in QGIS 3. The mapRenderer() object is obsolete and it appears the mapToLayerCoordinates() function is a member of the QgsMapSettings and requires that the layer argument "must have type QgsMapSettings" so my replacement code:

    layerRect = QgsMapSettings.mapToLayerCoordinates(layer, rect)

fails with

TypeError: QgsMapSettings.mapToLayerCoordinates(): arguments did not match any overloaded call:

overload 1: first argument of unbound method must have type 'QgsMapSettings'

overload 2: first argument of unbound method must have type 'QgsMapSettings'

The ultimate goal is to return any feature ids that are within the bounding box.

How do I resolve this conflict?

  • 2
    If you've got a bounding box, why not using layer.getFeatures(my_bbox)? If you still need to select the features, you also have layer.selectByRect(my_bbox). After that you already know how to get selected feature ids. In summary, there is no need to deal with the canvas or mapSettings. – Germán Carrillo May 6 at 13:45
  • Adding the layer.selectByRect(my_bbox) rect-ified the issue. Thanks. You may post as an answer if you wish. – CNIDog May 16 at 15:03
  • Good! Added the comment as an answer. – Germán Carrillo May 16 at 15:42
2

If you've got a bounding box, you can use layer.getFeatures(my_bbox).

If you still need to select the features, you also have layer.selectByRect(my_bbox). After that, you already know how to get selected feature ids.

In summary, there is no need to deal with the canvas or mapSettings.

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.