Search code examples
pythonpyqtpositioncoordinatesqmainwindow

How to get the screen position of `QMainWindow` and print it?


I'm trying to get the screen position of QMainWindow and print the position (x,y) values. I have tried both self.pos() and self.mapToGlobal(self.pos()) and both of these return 0.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow


class MainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(400, 200)

        # PRINTS 0 0
        print(self.pos().x(), self.pos().y())

        # PRINTS 0 0
        print(self.mapToGlobal(self.pos()).x(), self.mapToGlobal(self.pos()).y())


app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

I'm using Python 3.7 and PyQt 5.11, how can I achieve this?


Solution

  • The position of a widget is with respect to the parent if it has it, and if it does not have it is with respect to the screen, so in the case of MainWindow, since it is a window, pos() should be used, if it were a widget that has a parent you must use self.mapToGlobal(QtCore.QPoint(0, 0)) since it is the top-left position.

    On the other hand the initial position of every widget is QPoint(0, 0), and if it is a window the OS manipulates its position and moves it, so you get the value of (0, 0), so in your case you must track the change of position, for example using moveEvent:

    import sys
    from PyQt5 import QtCore, QtWidgets
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self):
            super(MainWindow, self).__init__()
            self.resize(400, 200)
    
        def moveEvent(self, e):
            print(self.pos())
            super(MainWindow, self).moveEvent(e)
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())