PyQT 不同的图像自动缩放模式 [英] PyQT different image autoscaling modes

查看:63
本文介绍了PyQT 不同的图像自动缩放模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个带有 QPixmap 的 QLabel

Let's say we have a QLabel with QPixmap

label = QLabel
Pixmap = QPixmap('filepath')
label.setPixmap(Pixmap)

我已经提到过使用

label.setScaledContents(True) 

我们可以强制图像自动缩放到标签大小(如果标签自动缩放到小部件的大小)如果不使用它,图像将以全尺寸显示,而不取决于窗口或标签的大小.现在我希望它自动缩放到标签的大小,但保持它的纵横比.

We can force image to be autoscaled to label size (And widget's one if label autoscaled to it) Without using it, image gona be displayed in it's full size, not depending on window or label's one. Now i want it to be autoscaled to label's size, but keeping it's aspect ratio.

推荐答案

试试看:

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

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)  

        self.label  = QLabel() 
        self.pixmap = QPixmap("head.jpg")
        self.label.setPixmap(self.pixmap.scaled(self.label.size(),
                Qt.KeepAspectRatio, Qt.SmoothTransformation))

        self.label.setSizePolicy(QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setMinimumSize(100, 100) 

        layout = QGridLayout(centralWidget)    
        layout.addWidget(self.label)        

    def resizeEvent(self, event):
        scaledSize = self.label.size()                       
        scaledSize.scale(self.label.size(), Qt.KeepAspectRatio)
        if not self.label.pixmap() or scaledSize != self.label.pixmap().size():
            self.updateLabel()    

    def updateLabel(self):
        self.label.setPixmap(self.pixmap.scaled(        
                self.label.size(), Qt.KeepAspectRatio,
                Qt.SmoothTransformation))

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

这篇关于PyQT 不同的图像自动缩放模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆