为了账号安全,请及时绑定邮箱和手机立即绑定

PyQT 不同的图像自动缩放模式

PyQT 不同的图像自动缩放模式

拉风的咖菲猫 2021-09-02 15:02:38
假设我们有一个带有 QPixmap 的 QLabellabel = QLabelPixmap = QPixmap('filepath')label.setPixmap(Pixmap)我已经提到通过使用label.setScaledContents(True) 我们可以强制图像自动缩放到标签大小(如果标签自动缩放到它,小部件也是一个)如果不使用它,图像将以全尺寸显示,而不取决于窗口或标签的大小。现在我希望它自动缩放到标签的大小,但保持它的纵横比。
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

尝试一下:


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

//img1.sycdn.imooc.com//613077420001ca8304630256.jpg

查看完整回答
反对 回复 2021-09-02
  • 1 回答
  • 0 关注
  • 211 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信