QMdiSubWindow标题栏颜色修改报错:错误码-1073741819(0xC0000005)
解决QMdiSubWindow标题栏颜色修改时的崩溃问题
尝试修改QMdiSubWindow标题栏颜色时,使用eyllanesc提供的QProxyStyle方案,运行程序出现进程错误码-1073741819(0xC0000005)退出的问题,该崩溃与QProxyStyle的使用方式及代码缩进错误有关。
原代码问题分析
- 缩进错误:
MdiSubWindow类中@property和@titleColor.setter的缩进不正确,导致属性定义不属于类,引发逻辑错误;Mywindow类__init__内创建子窗口的代码未缩进,会在类定义阶段提前执行,打乱初始化顺序。 - QProxyStyle生命周期问题:
MdiSubWindow的__init__中创建的TitleProxyStyle是局部变量,未被实例持有,易被Python垃圾回收,导致Qt访问无效的样式对象,触发内存访问违规(0xC0000005)。
修正后的代码
from PyQt5 import QtCore, QtGui, QtWidgets def create_icon_by_color(color): pixmap = QtGui.QPixmap(512, 512) pixmap.fill(color) return QtGui.QIcon(pixmap) class TitleProxyStyle(QtWidgets.QProxyStyle): def drawComplexControl(self, control, option, painter, widget=None): if control == QtWidgets.QStyle.CC_TitleBar: if hasattr(widget, "titleColor"): color = widget.titleColor if color.isValid(): option.palette.setBrush( QtGui.QPalette.Highlight, QtGui.QColor(color) ) option.icon = create_icon_by_color(QtGui.QColor("transparent")) super().drawComplexControl(control, option, painter, widget) class MdiSubWindow(QtWidgets.QMdiSubWindow): def __init__(self, parent=None, flags=QtCore.Qt.Widget): super().__init__(parent, flags) # 将样式对象保存为实例属性,避免被垃圾回收 self.style = TitleProxyStyle(self.style()) self.setStyle(self.style) self._titleColor = QtGui.QColor() @property def titleColor(self): return self._titleColor @titleColor.setter def titleColor(self, color): self._titleColor = color self.update() class Mywindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("自定义样式") self.mdiarea = QtWidgets.QMdiArea() self.setCentralWidget(self.mdiarea) self.mdiarea.setWindowTitle("测试") self.window = QtWidgets.QWidget() self.window.setMinimumSize(160, 120) sw = MdiSubWindow() sw.setWindowTitle("测试") sw.titleColor = QtGui.QColor("lightgray") sw.setWidget(self.window) self.mdiarea.addSubWindow(sw) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) app.setStyle("Fusion") view = Mywindow() view.show() sys.exit(app.exec_())
关键修正说明
- 修复缩进问题:调整
@property及子窗口创建代码的缩进,确保逻辑属于对应方法或类。 - 延长样式生命周期:将
TitleProxyStyle赋值给MdiSubWindow的实例属性,避免被垃圾回收,防止Qt访问无效内存。 - 简化父类调用:使用Python 3的
super()简化父类方法调用,提升代码可读性。
内容的提问来源于stack exchange,提问作者Houssam Farag
相关产品推荐
相关产品推荐

