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
相关产品推荐
相关产品推荐

