【问题标题】:PyQT different image autoscaling modes [duplicate]PyQT不同的图像自动缩放模式[重复]
【发布时间】:2019-05-02 18:09:46
【问题描述】:

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

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

我已经提到过使用

label.setScaledContents(True) 

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

【问题讨论】:

    标签: python pyqt pyqt5 qpixmap


    【解决方案1】:

    试试看:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 2022-11-13
      • 2014-10-21
      相关资源
      最近更新 更多