I am trying to map one widgets pos() (A) to another widget (B), so that B can do some work based on A's position. I have WidgetA that gets WidgetB pos, these widgets can have different parenting hierarchy:
Global +--- Window +--- WidgetA +--- WidgetB Global +--- Window +--- Sub | +--- Sub | +--- WidgetB | +--- WidgetA Global +--- Window | +--- WidgetB | +--- WidgetA etc.
I have tried to translate B's position to a relative position on A' via (Both widgets share same parent):
WidgetB.setGeometry(150, 150, 100, 100) # expected vs result WidgetA.mapFromGlobal(WidgetB.mapToGlobal(WidgetB.pos())) # 150, 150 125, 200 WidgetA.mapFrom(WidgetA.parent, WidgetB.pos()) # 150, 150 -25, 50 WidgetA.parent.mapFromGlobal(WidgetB.mapToGlobal(WidgetB.pos())) # 150, 150 300, 300 What is the correct way to do this mapping? I cannot seem to wrap it correctly.
Code:
from PyQt5.QtWidgets import QWidget, QApplication from PyQt5 import QtCore import sys class Window(QWidget): def __init__(self, Parent=None): super().__init__() self.WidgetA = QWidget(self) self.WidgetA.setAttribute(QtCore.Qt.WA_StyledBackground, True) self.WidgetA.setObjectName("WidgetA") self.WidgetA.setGeometry(400, 400, 100, 100) self.WidgetB = QWidget(self) self.WidgetB.setAttribute(QtCore.Qt.WA_StyledBackground, True) self.WidgetB.setObjectName("WidgetB") self.WidgetB.setGeometry(0, 0, 100, 100) self.setGeometry(0, 0, 500, 500) self.setStyleSheet(""" #WidgetA { background-color: red; } #WidgetB { background-color: blue; } """) def resizeEvent(self, event): print(self.WidgetB.pos()) print(self.WidgetA.pos()) print(self.WidgetA.mapFromGlobal(self.WidgetB.mapToGlobal(self.WidgetB.pos()))) print(self.WidgetA.mapFrom(self, self.WidgetB.pos())) print(self.mapFromGlobal(self.WidgetB.mapToGlobal(self.WidgetB.pos()))) if __name__ == "__main__": app = QApplication(sys.argv) screen = Window() screen.show() sys.exit(app.exec_()) Output:
PyQt5.QtCore.QPoint() PyQt5.QtCore.QPoint(400, 400) PyQt5.QtCore.QPoint(-400, -400) PyQt5.QtCore.QPoint(-400, -400) PyQt5.QtCore.QPoint() I would expect to get (0, 0) since that is what WidgetB is set to.