The area of focus is on this part of the code:
prect = self.parent.rect() # <===
prect1 = self.parent.geometry() # <===
center = prect1.center() # <===
self.move(center) # <===
When I use prect.center(), it centers the box correctly in the center, but if I move the window and use the menu (Action > Show Window2), Window2 doesn't show centered relative to the parent window.
When I use prect1.center(), it doesn't center the box correctly (top-left coordinate of Window2 is in the center) but it does move relative to the parent window if I move the parent window somewhere else.
Question: How do I alter my code to show Window2 in the center of Window relative to wherever Window is at on the screen?
Reproducible code example:
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow, QAction)
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.top = 100
self.left = 100
self.width = 680
self.height = 500
self.setWindowTitle("Main Window")
self.setGeometry(self.top, self.left, self.width, self.height)
menu = self.menuBar()
action = menu.addMenu("&Action")
show_window2 = QAction("Show Window2", self)
action.addAction(show_window2)
show_window2.triggered.connect(self.show_window2_centered)
self.show()
def show_window2_centered(self):
self.w = Window2(parent=self)
self.w.show()
class Window2(QMainWindow):
def __init__(self, parent=None):
self.parent = parent
super().__init__()
self.setWindowTitle("Centered Window")
prect = self.parent.rect() # <===
prect1 = self.parent.geometry() # <===
center = prect1.center() # <===
self.move(center) # <===
print(prect)
print(prect1)
print(center)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
sys.exit(app.exec())
Currently looks like this:
Would like it to be centered relative to the main window:

