首页 > 解决方案 > 中心子 QMainWindow 相对于父 QMainWindow

问题描述

重点领域是这部分代码:

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

目前看起来像这样:

子 QMainWindow 未居中

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

将 QMainWindow 居中到父级

标签: pythonpython-3.xpyqtpyqt5

解决方案


Firstself.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)

推荐阅读