重点是代码的这一部分:
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())
当前看起来是这样的:
希望它相对于主窗口居中:
第一个
self.w
不是Window
的子级,因为您没有将该参数传递给super()
。另一方面move()
没有将小部件居中于该位置,它所做的是左上角位于该位置。你知道吗解决方案是使用另一个图元的几何图形修改几何图形,因为它们都是窗口:
相关问题 更多 >
编程相关推荐