如何在QLabel中调整图片的大小?

您所在的位置:网站首页 widgets怎么设置图片 如何在QLabel中调整图片的大小?

如何在QLabel中调整图片的大小?

2023-04-13 23:45| 来源: 网络整理| 查看: 265

如果没有为标签设置最小尺寸,将总是使用像素图的尺寸来代替。为了避免这种情况,你可以直接设置一个任意的最小尺寸。

def showDotPlot(self): dotPng = QPixmap('big1.jpg') self.dotPlot.setPixmap(dotPng) self.dotPlot.setMinimumSize(1, 1) self.dotPlot.setScaledContents(True)

不幸的是,这将导致图像被拉长。

stretched images are bad!

在这种情况下,唯一的选择就是子类化。 在这个例子中,我继承了QLabel,但如果你不需要该类提供的所有功能,使用一个标准的QWidget就足够了(但你可能需要添加设置像素图和对齐方式的方法)。

class ScaledPixmapLabel(QLabel): scaled = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # if no minimum size is set, it will always use the image size self.setMinimumSize(1, 1) def resizeEvent(self, event): if self.pixmap() and not self.pixmap().isNull(): self.scaled = self.pixmap().scaled( self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) def paintEvent(self, event): if self.pixmap() and not self.pixmap().isNull(): if not self.scaled: self.scaled = self.pixmap().scaled( self.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation) # the available rectangle available = self.rect() # the pixmap rectangle that will be used as a reference to paint into rect = self.scaled.rect() # move to the center of the available rectangle rect.moveCenter(available.center()) # then move the rectangle according to the alingment align = self.alignment() if align & Qt.AlignLeft: rect.moveLeft(available.left()) elif align & Qt.AlignRight: rect.moveRight(available.right()) if align & Qt.AlignTop: rect.moveTop(available.top()) elif align & Qt.AlignBottom: rect.moveBottom(available.bottom()) qp = QPainter(self) qp.drawPixmap(rect, self.scaled) class goShow(QMainWindow): def initGUI(self): # ... self.dotPlot = ScaledPixmapLabel(alignment=Qt.AlignCenter) self.barPlot = ScaledPixmapLabel(alignment=Qt.AlignCenter) # ... def showDotPlot(self): dotPng = QPixmap(os.path.join('F:\\job\\projects\\snpExplore\\test\\res_temp',"dotplot.png")) self.dotPlot.setPixmap(dotPng) # no need to set other options

aspect ratio is good!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3