1.使用样式表
(1)背景:自适应图片,图片会根据窗口大小进行自动拉伸
self.label1.setStyleSheet("QWidget{border-image: url('./images/tupian.png') }")
(2)背景:图片为平铺,不改变图片大小
self.label2.setStyleSheet("QWidget{background-image: url('./images/tupian.png') }")
(3)前景:自适应图片,图片会根据窗口大小进行自动拉伸
self.label3.setStyleSheet("QWidget{Image: url('./images/tupian.png') }")
2.使用QPixmap
通过使用 QPixmap 的构造函数和 setPixmap 函数,加载图像文件并在 QLabel 中显示图像
将图片调整到所需大小,因此清晰度会有损失
pic = QPixmap('./images/tupian.png') pic = pic.scaled(380, 380) self.label5.setPixmap(pic)
3.重写paintEvent事件
paintEvent(QPaintEvent*)函数是QWidget类中的虚函数,用于ui的绘制,会在多种情况下被其他函数自动调用
def paintEvent(self, a0: QPaintEvent) -> None: painter = QPainter(self) pixmap = QPixmap('./images/tupian.png') painter.drawPixmap(QRect(405,405,385,380), pixmap)
示例:
#coding = 'utf-8'
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Example(QWidget):
def __init__(self):
super().__init__()
self.Init_UI()
def Init_UI(self):
self.setGeometry(300,300,1200,800)
self.setWindowTitle('加载图片')
self.layout = QGridLayout()
self.label1 = QLabel()
self.label1.resize(300, 300)
# 背景:自适应图片,根据窗口大小对图片拉伸
self.label1.setStyleSheet("QWidget{border-image: url('./images/tupian.png') }")
self.label2 = QLabel()
self.label2.resize(300, 300)
# 背景:平铺,图片尺寸不变
self.label2.setStyleSheet("QWidget{background-image: url('./images/tupian.png') }")
self.label3 = QLabel()
self.label3.resize(300, 300)
# 前景:自适应图片,根据窗口大小对图片拉伸
self.label3.setStyleSheet("QWidget{Image: url('./images/tupian.png') }")
self.label4 = QLabel()
self.label4.resize(300, 300)
# painter = QPainter()
# pixmap = QPixmap('./images/tupian.png')
# painter.drawPixmap(label4.rect(), pixmap)
self.label5 = QLabel()
self.label5.resize(300, 300)
pic = QPixmap('./images/tupian.png')
pic = pic.scaled(380, 380)
self.label5.setPixmap(pic)
self.layout.addWidget(self.label1, 0, 0, 1, 1)
self.layout.addWidget(self.label2, 0, 1, 1, 1)
self.layout.addWidget(self.label3, 1, 0, 1, 1)
self.layout.addWidget(self.label4, 1, 1, 1, 1)
self.layout.addWidget(self.label5, 1, 2, 1, 1)
self.setLayout(self.layout)
self.show()
def paintEvent(self, a0: QPaintEvent) -> None:
painter = QPainter(self)
pixmap = QPixmap('./images/tupian.png')
painter.drawPixmap(QRect(405,405,385,380), pixmap)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
app.exit(app.exec_())
运行结果: