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

PyQt6中QMdiArea移动子窗口时行为异常问题求助

问题分析与解决

问题根源在于你重写paintEvent时没有调用父类的实现——QMdiArea本身需要处理子窗口管理、背景重绘等核心逻辑,直接覆盖后这些关键流程被跳过,导致子窗口移动时出现异常。

解决步骤

  • 重写paintEvent时,必须先调用父类的paintEvent方法,让QMdiArea完成自身的基础绘制工作,再执行你的logo绘制逻辑。
  • 确保logo绘制在父类绘制之后,避免覆盖子窗口或其他UI元素。

示例代码

from PyQt6.QtWidgets import QMdiArea, QApplication
from PyQt6.QtGui import QPainter, QPixmap
from PyQt6.QtCore import Qt

class CustomMdiArea(QMdiArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.logo = QPixmap("your_logo_path.png")  # 替换为你的logo路径

    def paintEvent(self, event):
        # 先执行父类绘制逻辑,保证QMdiArea功能正常
        super().paintEvent(event)
        
        # 绘制居中logo
        if not self.logo.isNull():
            painter = QPainter(self.viewport())
            # 计算居中坐标
            x = (self.viewport().width() - self.logo.width()) // 2
            y = (self.viewport().height() - self.logo.height()) // 2
            painter.drawPixmap(x, y, self.logo)

if __name__ == "__main__":
    app = QApplication([])
    mdi = CustomMdiArea()
    mdi.show()
    app.exec()

额外提示

  • 若想让logo作为背景显示在子窗口下方,保持当前绘制顺序即可;如果想让logo浮在子窗口上方,调换父类调用和logo绘制的顺序。
  • 若logo尺寸过大,可添加缩放处理:self.logo.scaled(self.viewport().size() * 0.8, Qt.AspectRatioMode.KeepAspectRatio)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:39:51