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

如何通过QSS为QPushButton设置背景图并调整位置,解决重复显示问题?

解决QPushButton背景图重复及位置调整问题

问题根源是QSS里background-image默认会平铺重复填充按钮区域,要实现单张图并自定义位置,只需在样式里加两个属性:

  • 禁止重复:添加background-repeat: no-repeat;,让背景图只显示一次
  • 调整位置:用background-position设置图在按钮内的位置,支持关键字(如center居中、left top左上)或具体像素值(如15px 10px表示距左15px、距上10px)

修改后的完整样式表代码:

self.button1.setStyleSheet("""
QPushButton{
    background-image: url(resources/picture1.png);
    border-radius: 8px;
    background-color: lightgrey;
    background-repeat: no-repeat;
    background-position: center; /* 这里可以换成你需要的位置 */
}
QPushButton:pressed{
    background-image: url(resources/picture2.png);
    border-radius: 8px;
    background-color: red;
    background-repeat: no-repeat;
    background-position: center;
}
""")

如果需要更灵活的位置控制,比如让图靠右下角,就把background-position改成right bottom;要是想精确偏移,用像素值比如20px 20px即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:31:07