You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5最大化窗口时frameGeometry获取高度异常如何解决?

问题根因

你遇到的高度获取错误和showMaximized()方法本身无关,是高度获取时机错误导致的:

  • PyQt的窗口状态变更(最大化、显示、调整尺寸)都是异步请求,调用对应方法后只是向系统窗口管理器提交了状态变更申请,不会同步等待变更生效,对应属性不会立刻更新
  • 你在__init__方法中打印高度时,QApplication的主事件循环(window.exec_())还没有启动,窗口的最大化请求还没被系统处理,拿到的只是窗口初始化时的默认高度值
修复方案

方案1:重写showEvent事件获取真实高度(推荐)

在窗口首次显示完成、状态生效后触发的showEvent中读取高度,是最准确的实现方式:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.showMaximized()
        self.setStyleSheet("QWidget {background: blue;}")
    
    def showEvent(self, event):
        super().showEvent(event)
        # 只有首次显示时打印,避免多次触发重复打印
        if not hasattr(self, '_first_shown'):
            self._first_shown = True
            print(self.frameGeometry().height())

if __name__ == "__main__":
    window = QApplication(sys.argv)
    window.setStyle(QStyleFactory.create("Fusion"))
    app = App()
    window.exec_()

方案2:用QTimer延迟读取

等主事件循环启动后再读取高度,适合临时调试场景:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.showMaximized()
        self.setStyleSheet("QWidget {background: blue;}")
        # 延迟0秒执行,相当于把打印任务放到事件循环队列的最前面,等初始化事件处理完再执行
        QTimer.singleShot(0, lambda: print(self.frameGeometry().height()))

if __name__ == "__main__":
    window = QApplication(sys.argv)
    window.setStyle(QStyleFactory.create("Fusion"))
    app = App()
    window.exec_()

额外说明

如果你只是需要获取屏幕的可用高度(排除任务栏、停靠栏等系统占用区域),不需要等待窗口显示,可以直接调用屏幕接口读取:

# 整个屏幕的总高度
print(QGuiApplication.primaryScreen().geometry().height())
# 屏幕可用高度(排除系统保留区域,和你提到的Tkinter返回的841一致)
print(QGuiApplication.primaryScreen().availableGeometry().height())

内容的提问来源于stack exchange,提问作者blunty6363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 11:15:03