4

I'm trying to set the initial position of my QGIS plugin dialog. I'm using .setGeometry() but the problem is that I don't know how to get coordinates. I want to set the initial position in the top corner of the canvas in QGIS (like the image below). I've tried this but it does not work.

self.dlg = SetZoomDialog()
canvasCenter = iface.mapCanvas().extent().center()
canvasToGlobal = iface.mapCanvas().mapToGlobal(QPoint(int(canvasCenter.x())/2, int(canvasCenter.y())/2))
x= canvasToGlobal.x()
y= canvasToGlobal.y()
self.dlg.setGeometry(x,y,width,height)

I tried also this canvasToGlobal = QgsMapTool(iface.mapCanvas()).toCanvasCoordinates(canvasCenter) but still I don't understand how to convert canvas coordinates to screen coordinates.

2

1 Answer 1

3

It is not very difficult to do that. That position in Map Canvas corresponds to QPoint(0,0), so you only need 'mapToGlobal' QgsMapCanvas method to find screen coordinates. I used a test plugin for testing my approach. It can be observed in following code snippet.

.
.
.
from PyQt5.QtCore import QSettings, QTranslator, qVersion, QCoreApplication, QVariant, QPoint
.
.
.

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        mapcanvas = self.iface.mapCanvas()
        point = mapcanvas.mapToGlobal(QPoint(0,0))
        self.dlg.move(point.x(), point.y())
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass

When I launch my plugin by clicking in corresponding icon, it appears in desired position; as it can be observed in following image:

enter image description here

2
  • Thank you, it's exactly what I've asked for.
    – Lorenzo
    Commented Nov 22, 2019 at 21:39
  • I’m happy to help.
    – xunilk
    Commented Nov 26, 2019 at 15:26

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.