相对于父QMainWind,将子QMainWindow居中

2024-10-03 13:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

重点是代码的这一部分:

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

当我使用prect.center()时,它会将框正确地居中,但是如果我移动窗口并使用菜单(Action>;Show Window2),Window2不会相对于父窗口居中显示。你知道吗

当我使用prect1.center()时,它不能正确地将框居中(Window2的左上角坐标位于中心),但是如果我将父窗口移到其他地方,它会相对于父窗口移动。你知道吗

问题:如何更改代码,相对于屏幕上Window的位置,在Window的中心显示Window2?你知道吗

可复制代码示例:

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


Tags: 代码importselfinitdefshowsyswindow
1条回答
网友
1楼 · 发布于 2024-10-03 13:30:58

第一个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)

相关问题 更多 >