相对于父QMainWindow的中心子QMainWindow

时间:2019-06-30 06:09:32

标签: python python-3.x pyqt pyqt5

重点在于代码的这一部分:

prect = self.parent.rect() # <===
prect1 = self.parent.geometry() # <===
center = prect1.center() # <===
self.move(center) # <===

当我使用prect.center()时,它将框正确地居中居中,但是如果我移动窗口并使用菜单(“动作”>“显示Window2”),则Window2不会相对于居中显示父窗口。

当我使用prect1.center()时,它不能正确地使框居中(Window2的左上角坐标在中间),但是如果我移动父级,它会相对于父级窗口移动窗户在其他地方。

问题:如何更改代码以将Window2相对于屏幕上Window的位置显示在Window的中心?

可复制的代码示例:

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())

当前看起来像这样:

Child QMainWindow not centered

希望它相对于主窗口居中:

centered QMainWindow to Parent

1 个答案:

答案 0 :(得分:3)

第一个self.w不是Window的子级,因为您没有将该参数传递给super()。另一方面,move()不会将窗口小部件在该位置居中,而是因为左上角位于该位置。

解决方案是使用其他元素的几何形状来修改几何形状,因为它们都是窗口:

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)