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

PySide6自定义Button类重写sizeHint()函数触发‘Fatal Python error: Cannot recover from stack overflow’错误排查

解决PySide6计算器示例中的栈溢出错误

你遇到的「Fatal Python error: Cannot recover from stack overflow」错误根源非常明确——自定义Button类的sizeHint()方法里出现了无限递归调用。

错误原因分析

看你重写的sizeHint()方法:

def sizeHint(self) -> QtCore.QSize:
    size = self.sizeHint()  # 这里是问题核心!
    size.setHeight(size.height + 20)
    size.setWidth(max(size.width(), size.height()))
    return size

当你调用self.sizeHint()时,实际上是在调用当前你重写的这个方法,这会形成无限循环:每次调用sizeHint()都会再次调用自己,直到Python的调用栈被耗尽,最终触发栈溢出错误。

另外还有两个小问题:

  1. QSize的height和width是方法,不是属性,需要加()调用(比如size.height()而不是size.height);
  2. 你注释里的rheight()/rwidth()是Qt C++的语法,PySide6中并没有这些方法,不能直接照搬。

解决方案

1. 修复递归调用与尺寸修改逻辑

把self.sizeHint()替换为super().sizeHint(),这样就能获取QToolButton父类的默认尺寸提示,避免递归。同时修正属性访问的错误,改用PySide6支持的方式修改尺寸:

class Button(QToolButton):
    def __init__(self, text, parent=None):
        super(Button, self).__init__(parent)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.setText(text)

    def sizeHint(self) -> QtCore.QSize:
        # 调用父类的sizeHint获取默认尺寸
        size = super().sizeHint()
        # 增加高度20像素
        new_height = size.height() + 20
        size.setHeight(new_height)
        # 确保宽度不小于调整后的高度,让按钮更方正
        new_width = max(size.width(), new_height)
        size.setWidth(new_width)
        return size

2. 清理重复的布局代码

在你的Advanced_Calculator类中,重复了多次添加self.button_power到布局的代码:

self.layout_button.addWidget(self.button_power, 3, 0, 1, 1)
self.layout_button.addWidget(self.button_power, 3, 0, 1, 1)
self.layout_button.addWidget(self.button_power, 3, 0, 1, 1)
self.layout_button.addWidget(self.button_power, 3, 0, 1, 1)

这会导致按钮被多次添加到同一个布局位置,可能引发显示异常,建议只保留一行即可,删除其余重复的行。

验证效果

修改完成后,重新运行代码,栈溢出错误会消失,计算器的按钮也会按照你预期的尺寸显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:17:30