eric
eric

Reputation: 8098

Applying mapToGlobal to main window position

Here is some code that creates a single window and, just for fun, lets you click in the window to print self.pos() and self.mapToGlobal(self.pos()):

from PySide import QtGui, QtCore

class WinPosExplore(QtGui.QWidget):
    def __init__(self):
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Plastique"))
        QtGui.QWidget.__init__(self)
        self.show()

    def mousePressEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            winPos=self.pos() 
            globalWinPos = self.mapToGlobal(winPos)  
            msg1="winPos=self.pos(): <{0}, {1}>\n".format(winPos.x(), winPos.y())
            msg2="self.mapToGlobal(winPos): <{0}, {1}>\n\n".format(globalWinPos.x(), globalWinPos.y())
            print msg1 + msg2

def main():
    import sys
    qtApp=QtGui.QApplication(sys.argv)
    myWinPos=WinPosExplore()
    sys.exit(qtApp.exec_())

if __name__=="__main__":
    main()

Because I only am using a single top-level window, I would expect the two sets of coordinates to be the same. That is, I expect the program to realize that for the parent window of the application, mapToGlobal is just the identity function. But this is not what happens. I get different coordinates in ways that are not explicable (by me). For example, the following is one printout:

winPos=self.pos(): <86, 101> 
self.mapToGlobal(winPos): <176, 225>

Can anyone explain what is happening?

Note, I realize this is a silly exercise to some degree (we don't technically ever need mapToGlobal for the main window, as pointed out at this post at qtforum). But I am still curious if anyone can make sense of this behavior in this corner case.

Upvotes: 3

Views: 11098

Answers (1)

Avaris
Avaris

Reputation: 36725

Docs:

QPoint QWidget::mapToGlobal ( const QPoint & pos ) const

Translates the widget coordinate pos to global screen coordinates. For example, mapToGlobal(QPoint(0,0)) would give the global coordinates of the top-left pixel of the widget.

The input to mapToGlobal is a point in widget coordinates, i.e. it's relative to the top-left of widget area.

To clarify, consider this image from docs:

enter image description here

mapToGlobal(self.pos()) will give you self.geometry().topLeft() + self.pos()

Note: mapToGlobal(QPoint(0, 0)) will not give same result as self.pos() either. This is because window decorations like title bar, etc. are not included in the widget area (see the difference between geometry().topLeft() and pos() in the image above).

Upvotes: 7

Related Questions