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

PyQt QMainWindow中SVG背景图重复显示及居中设置问题

QMainWindow背景图片居中且禁止重复的解决方法

要解决背景图片重复显示的问题并让图片居中,只需在样式表中添加两个CSS属性:

  • background-repeat: no-repeat:关闭图片的平铺重复效果
  • background-position: center center:设置图片在窗口水平、垂直方向均居中

修改后的完整代码如下:

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

class BackgroundIssue(QMainWindow):
    def __init__(self, parent = None):
        super().__init__(parent)

        self.setWindowTitle(f'Background Issue')
        self.setMinimumSize(1000, 800)
        # 新增重复控制与居中属性
        self.setStyleSheet("background-image: url(max.svg); background-repeat: no-repeat; background-position: center center;")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = BackgroundIssue()
    window.show()
    sys.exit(app.exec_())

如果需要让图片保持原比例且自适应窗口大小(不超出窗口范围),可以额外添加background-size: contain;属性:

self.setStyleSheet("background-image: url(max.svg); background-repeat: no-repeat; background-position: center center; background-size: contain;")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:43:28