Reputation: 18883
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:
Upvotes: 3
Views: 1723
Reputation: 243887
First self.w
is not a child ofWindow
because you do not pass that parameter to super()
. On the other hand move()
does not center the widget in that position, what it does is that the top-left is located in that position.
The solution is to modify the geometry using the geometry of the other element since they are both windows:
class Window2(QMainWindow):
def __init__(self, parent=None):
self.parent = parent
super().__init__()
self.setWindowTitle("Centered Window")
geo = self.geometry()
geo.moveCenter(self.parent.geometry().center())
self.setGeometry(geo)
Upvotes: 3