python - 中心子 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())
目前看起来像这样:
希望它相对于主窗口居中:
解决方案
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)
推荐阅读
- webpack - 在 Webpack 5 生产 javascript 输出中保留一些注释
- c# - Monogame,为什么即使有功能,块也不会移动?
- panel - Altair 和面板:另存为按钮未显示
- javascript - 如何从 json 规则引擎中查找失败的事实
- java - SFTP 传输后处理未正常进行
- google-fit - 由某些数据源聚合导致错误:找不到数据源或不可读
- html - 如何在 HTML 表格中指定列宽,以便一列占用它需要的任何内容,而另一列占用剩余的可用空间?
- oracle - Toad 结果集:直观地突出显示行组
- flutter - 当两个滚动始终可见时嵌套滚动问题(颤振稳定通道)
- node.js - 将 Twilio 呼叫转变为会议