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

PyQt5翻页按钮失效,点击后进程崩溃(错误码0xC0000409)求助

解决PyQt5页面跳转时Python崩溃的问题

错误原因分析

  1. 核心崩溃诱因:代码中使用widget.currentWidget()+1来计算下一页索引,但currentWidget()返回的是QWidget对象而非整数索引,对对象执行加法运算会触发非法内存访问,直接导致程序崩溃(错误码0xC0000409通常关联栈溢出或无效内存操作)。
  2. 跳转逻辑错误:Screen2的返回方法中,currentIndex()+1会让索引超出StackedWidget的有效范围(仅包含索引0和1的两个页面),进一步加剧异常风险。
  3. 额外小问题:重复调用setFixedWidth导致窗口宽度设置无效,且未设置高度;使用app.exec()存在与Python内置函数冲突的风险。

修正后的代码

import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        loadUi("screen1.ui", self)
        self.button.clicked.connect(self.gotoScreen2)

    def gotoScreen2(self):
        # 通过父部件获取StackedWidget,避免全局变量依赖
        stacked_widget = self.parent()
        stacked_widget.setCurrentIndex(stacked_widget.currentIndex() + 1)

class Screen2(QMainWindow):
    def __init__(self):
        super(Screen2, self).__init__()
        loadUi("screen2.ui",self)
        self.button2.clicked.connect(self.gotoScreen1)

    def gotoScreen1(self):
        stacked_widget = self.parent()
        stacked_widget.setCurrentIndex(stacked_widget.currentIndex() - 1)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    widget = QtWidgets.QStackedWidget()

    mainwindow = MainWindow()
    widget.addWidget(mainwindow)

    screen2 = Screen2()
    widget.addWidget(screen2)

    # 修正窗口尺寸设置,同时指定宽高
    widget.setFixedWidth(800)
    widget.setFixedHeight(600)
    widget.show()

try:
    # 使用PyQt5规范的exec_()方法,避免与内置函数冲突
    sys.exit(app.exec_())
except:
    print("Exiting..")

关键修正点说明

  • 用currentIndex()替代currentWidget()获取页面索引,确保运算对象是整数。
  • 调整Screen2的跳转逻辑为currentIndex() - 1,回到上一页的正确索引。
  • 通过self.parent()获取StackedWidget实例,消除全局变量依赖,提升代码健壮性。
  • 修复窗口尺寸设置的重复问题,补充高度设置。
  • 替换app.exec()为app.exec_(),符合PyQt5的规范写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:01:42