I'd like to set the position of a plugin's window or dialog relative to the map canvas frame. For example, if I start a plugin, I want it to appear somewhere in the left upper corner of the map canvas.
I can use absolute screen coordinates (choosing appropriate values for the first two parameters of the setGeometry
method of a dialog), but that's not a flexible solution as users might adapt the size of the map canvas frame according to their wishes.
FYI: I use the Plugin Builder plugin to take off...
Based on @Matthias Kuhn's concise answer, I found a solution which I share here below. Note that the code corresponds to the script that is produced by the Plugin Builder plugin. Also note that the argument of mapToGlobal()
must be a QPoint
.
def run():
self.mapcanvas_upperleft = self.iface.mapCanvas().mapToGlobal(QPoint(0, 0))
offset_x = 24
offset_y = 43
pos_x = self.mapcanvas_upperleft.x() + offset_x
pos_y = self.mapcanvas_upperleft.y() + offset_y
self.dlg.setGeometry(pos_x, pos_y, 0, 0)
# show the dialog
self.dlg.show()
# Do this a first step... then delete
print self.dlg.pos().x()
print self.dlg.pos().x()
In order to define the offsets, you can print the upper left corner of your dialog before you change its position with setGeometry
. The pos()
method returns a QPoint
.
(hint: in QGIS, click Plugins > Python Console to see the print output)
As such, you know the difference between the global coordinates of 1) the upperleft corner of the map canvas and 2) the upperleft corner of the plugin dialog, which then helps you to define the offset you prefer.