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_())

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM