4

With PyQGIS how can I convert absolute screen coordinates (say, 123,456) into map coordinates of the iface.mapCanvas?

It would be no problem if I had screen coordinates relative to the iface.mapCanvas.viewport(), since iface.mapCanvas.viewport().geometry() gives me sth like QRect(2,2,2198, 1090) and iface.mapCanvas().extent() gives me a QgsRectangle with xmin,xmax,ymin,ymax, so (leaving projection issues out of the scope) the conversion would be simple.

But since the absolute position of the mapCanvas may vary with toolbar positions or layer windows width, the question reduces to 'how to derive the absolute screen position of the map canvas?'.

1

2 Answers 2

5

You can use mapToGlobal(), which takes a QPoint as its argument. For example:

map_coor = iface.mapCanvas().mapToGlobal(QPoint(123, 456))

I couldn't find QGIS API documentation, but I'm guessing this inherits from QWidget through the map canvas and Python interface: http://doc.qt.io/qt-4.8/qwidget.html#mapToGlobal.

4

mapToGlobal() function gives me global screen coordinates. The next code works for me:

pScreen = QPoint(123, 456)
pMap = iface.mapCanvas().getCoordinateTransform().toMapCoordinates(pScreen)
1
  • thanks, this was what I needed as well - the accepted answer is just converting the canvas coordinate to a screen coordinate wheras this converts a canvas coordinate to a world coordinate - it even uses the current layer's CRS which saved me a ton of work
    – Rugnir
    Commented Aug 11, 2021 at 13:49

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.