如果没有为标签设置最小尺寸,将总是使用像素图的尺寸来代替。为了避免这种情况,你可以直接设置一个任意的最小尺寸。
def showDotPlot(self):
dotPng = QPixmap('big1.jpg')
self.dotPlot.setPixmap(dotPng)
self.dotPlot.setMinimumSize(1, 1)
self.dotPlot.setScaledContents(True)
不幸的是,这将导致图像被拉长。
![stretched images are bad!](https://i.stack.imgur.com/19ERK.png)
在这种情况下,唯一的选择就是子类化。
在这个例子中,我继承了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!](https://i.stack.imgur.com/hK8eZ.png)
|