2

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?'.

4

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.

0

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

pScreen = QPoint(123, 456)
pMap = iface.mapCanvas().getCoordinateTransform().toMapCoordinates(pScreen)

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.