从QMainWindow geometry()获取错误的位置是因为geometry()方法返回的是窗口在屏幕上的位置和大小,而不是窗口内容区域的位置和大小。如果想要获取窗口内容区域的位置和大小,应该使用QMainWindow centralWidget()方法获取窗口的中心部件,然后再使用QWidget geometry()方法获取中心部件的位置和大小。
QMainWindow是Qt框架中的一个主窗口类,用于创建具有菜单栏、工具栏、状态栏等功能的应用程序窗口。geometry()方法用于获取窗口在屏幕上的位置和大小,返回一个QRect对象,包含窗口的左上角坐标和宽高信息。
然而,如果想要获取窗口内容区域的位置和大小,应该使用centralWidget()方法获取窗口的中心部件。中心部件是一个QWidget对象,可以包含其他的子部件,例如按钮、文本框等。然后,可以使用geometry()方法获取中心部件的位置和大小,同样返回一个QRect对象。
以下是一个示例代码,展示如何正确获取窗口内容区域的位置和大小:
from PyQt5.QtWidgets import QMainWindow, QWidget, QApplication
from PyQt5.QtCore import QRect
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My Main Window")
self.setGeometry(100, 100, 500, 500)
central_widget = QWidget(self)
self.setCentralWidget(central_widget)
central_widget.setGeometry(50, 50, 400, 400)
def get_content_geometry(self):
central_widget = self.centralWidget()
content_geometry = central_widget.geometry()
return content_geometry
if __name__ == "__main__":
app = QApplication([])
window = MyMainWindow()
window.show()
content_geometry = window.get_content_geometry()
print("Content Geometry:", content_geometry)
app.exec_()
在上述示例中,我们创建了一个自定义的主窗口类MyMainWindow,并设置了窗口的标题和位置。在构造函数中,我们创建了一个中心部件central_widget,并将其设置为主窗口的中心部件。然后,我们通过get_content_geometry()方法获取中心部件的位置和大小,并打印输出。
注意,这里的位置和大小是相对于窗口的内容区域而言的,而不是相对于屏幕。如果需要获取相对于屏幕的位置和大小,可以使用QWidget的mapToGlobal()方法将内容区域的位置转换为屏幕坐标。
领取专属 10元无门槛券
手把手带您无忧上云