1

I'm using for my first time QgsMapCanvas() and when I write my script and I then run it, I don't see anything in the canvas. That's my script:

canva = QgsMapCanvas()
r = QgsRubberBand(canva,True)
points = [[QgsPointXY(607826.87000000011175871, 380922.09400000004097819),
           QgsPointXY(607846.87000000011175871, 380922.09400000004097819),
           QgsPointXY(607846.87000000011175871, 380952.09400000004097819)]]
r.setToGeometry(QgsGeometry.fromPolygonXY(points),None)

r.show()
canva.show()

Any help from you?

3
  • 1
    Try just after defining r : r.setWidth(1) and r.setColor(QColor(255, 0, 0)), and canva = iface.mapCanvas(). Commented Jun 28, 2021 at 9:36
  • Make it an answer I think
    – ThomasG77
    Commented Jun 28, 2021 at 9:42
  • 1
    imho the solution is setting the canvas extent
    – Ben W
    Commented Jun 28, 2021 at 9:46

1 Answer 1

2

You need to set the extent of your QgsMapCanvas object.

Simply add the following line:

canva.setExtent(QgsGeometry.fromPolygonXY(points).boundingBox())

By the way, if you wish to zoom out slightly from the polygon extent, you can use the method zoomByFactor()

E.g. running:

canva = QgsMapCanvas()
r = QgsRubberBand(canva,True)
points = [[QgsPointXY(607826.87000000011175871, 380922.09400000004097819),
           QgsPointXY(607846.87000000011175871, 380922.09400000004097819),
           QgsPointXY(607846.87000000011175871, 380952.09400000004097819)]]
r.setToGeometry(QgsGeometry.fromPolygonXY(points),None)
canva.setExtent(QgsGeometry.fromPolygonXY(points).boundingBox())
canva.zoomByFactor(1.1)
r.show()
canva.show()

from the Python console results in:

enter image description here

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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