QLabel显示图片,图片可以自适应label的大小

showpicture.py

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *


import sys

class MyWidget(QWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.setWindowTitle(self.tr('显示图片'))
        self.resize(500,400)
        self.label = QLabel(self)
        self.label.setFrameShape(QFrame.Box)
        self.label.setAlignment(Qt.AlignCenter)
        img = QImage()
        if img.load('meixi.jpg'):
            self.label.setGeometry(0,0,400,300)
            width = img.width()
            height = img.height()

            if width/400 >= height/300:
                ratio = width/400
            else:
                ratio = height/300
            new_width = width/ratio
            new_height = height/ratio
            new_img = img.scaled(new_width,new_height,Qt.KeepAspectRatio)
            print(new_img)
            self.label.setPixmap(QPixmap.fromImage(new_img))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    widget = MyWidget()
    widget.show()
    #print(widget.children())
    sys.exit(app.exec_())

 

原文地址:https://www.cnblogs.com/ACPIE-liusiqi/p/10610274.html