Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

后端 未结 6 2028
长情又很酷
长情又很酷 2020-11-28 03:35

I use a QLabel to display the content of a bigger, dynamically changing QPixmap to the user. It would be nice to make this label smaller/larger depending on the space availa

6条回答
  •  半阙折子戏
    2020-11-28 04:12

    Adapted from Timmmm to PYQT5

    from PyQt5.QtGui import QPixmap
    from PyQt5.QtGui import QResizeEvent
    from PyQt5.QtWidgets import QLabel
    
    
    class Label(QLabel):
    
        def __init__(self):
            super(Label, self).__init__()
            self.pixmap_width: int = 1
            self.pixmapHeight: int = 1
    
        def setPixmap(self, pm: QPixmap) -> None:
            self.pixmap_width = pm.width()
            self.pixmapHeight = pm.height()
    
            self.updateMargins()
            super(Label, self).setPixmap(pm)
    
        def resizeEvent(self, a0: QResizeEvent) -> None:
            self.updateMargins()
            super(Label, self).resizeEvent(a0)
    
        def updateMargins(self):
            if self.pixmap() is None:
                return
            pixmapWidth = self.pixmap().width()
            pixmapHeight = self.pixmap().height()
            if pixmapWidth <= 0 or pixmapHeight <= 0:
                return
            w, h = self.width(), self.height()
            if w <= 0 or h <= 0:
                return
    
            if w * pixmapHeight > h * pixmapWidth:
                m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
                self.setContentsMargins(m, 0, m, 0)
            else:
                m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
                self.setContentsMargins(0, m, 0, m)
    

提交回复
热议问题