如何通过QSS为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
相关产品推荐
相关产品推荐

