Pyside2&PyQt5设置背景图片
平时我们在Designer中的styleSheet设置背景图片会导致其它控件也会被设置上背景图片。(如果一定要用Designer解决方法在下面)
为解决这个问题,在代码中按如下设置即可单独设置背景图不影响其它。图片会随着窗口的尺寸变化自适应改变大小。
self.centralwidget.setObjectName("wkWgt") # 替换背景图片只对当前窗口生效 核心代码
self.centralwidget.setStyleSheet("#wkWgt{border-image:url(C:/User/变色龙.jpg);}") # 替换图片路径 核心代码
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtWidgets import QMainWindow, QApplication,QMessageBox
import sys
class Ui_MainWindow(QMainWindow):
def __init__(self, parent=None):
super(Ui_MainWindow, self).__init__(parent)
self.setupUi(self)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(518, 421)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("wkWgt") # 替换背景图片只对当前窗口生效 核心代码
self.centralwidget.setStyleSheet("#wkWgt{border-image:url(C:/User/变色龙.jpg);}") # 替换图片路径 核心代码
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(20, 330, 201, 61))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "背景设置"))
self.pushButton.setText(_translate("MainWindow", "设置背景-其它控件不受影响"))
if __name__ == '__main__':
app = QApplication(sys.argv)
myWin = Ui_MainWindow()
myWin.show()
sys.exit(app.exec_())
1、点击QWidget
2、选中QWidget,搜索stylesheet
3、点击stylesheet旁边的三个点,在弹出的编辑框中输入:
#centralwidget{border-image: url(:/background-image/Desktop/壁纸/卡通月夜.jpg);}