代码
'''
设置窗体背景图片,及自动适应窗体大小
'''
from PyQt5 import QtCore,QtGui,QtWidgets
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtGui import QBrush,QPixmap
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(761, 507)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(290, 220, 111, 41))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
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", "选择图片"))
self.pushButton.clicked.connect(self.setImg)
def setImg(self):
try:
self.waterimg = QFileDialog.getOpenFileName(None,'选择背景图片','C:\\',"图片文件(*.jpeg;*.png;*.jpg;*.bmp)")
palette = QtGui.QPalette()
palette.setBrush(MainWindow.backgroundRole(), QBrush(
QPixmap(self.waterimg[0]).scaled(MainWindow.size(), QtCore.Qt.IgnoreAspectRatio,
QtCore.Qt.SmoothTransformation)))
MainWindow.setPalette(palette)
MainWindow.setAutoFillBackground(True)
except Exception as e:
print(e)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
效果
