PyQT different image autoscaling modes [duplicate]

橙三吉。 提交于 2021-01-29 09:07:28

问题


Let's say we have a QLabel with QPixmap

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

I already mentioned that by using

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.


回答1:


Try it:

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



来源:https://stackoverflow.com/questions/53560035/pyqt-different-image-autoscaling-modes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!