PyQt:将缩放图像放置在标签的中心

时间:2014-12-28 11:37:11

标签: python image position pyqt qlabel

我正在使用QPixmap在标签上显示不同尺寸的图片。我使用以下代码显示图像:

myPixmap = QtGui.QPixmap(os.path.join("data", "images", image_name))
myScaledPixmap = myPixmap.scaled(self.ui.label.size(), QtCore.Qt.KeepAspectRatio)

上面的代码没有任何问题。但是,图像显示在标签的左侧而不是中心。此外,缩放还可以进一步缩小图像,而不是填充整个标签。

是否可以在标签的中心显示图像?

2 个答案:

答案 0 :(得分:5)

如果您只想让图片填满整个标签,无论其大小如何:

    self.ui.label.setScaledContents(True)
    self.ui.label.setPixmap(myPixmap)

但是,这不会保持图像的宽高比。为此,您需要在每次标签更改大小时重新缩放像素图:

    self.pixmap = QtGui.QPixmap(os.path.join("data", "images", image_name))
    self.ui.label.setPixmap(self.pixmap)
    # this ensures the label can also re-size downwards
    self.ui.label.setMinimumSize(1, 1)
    # get resize events for the label
    self.ui.label.installEventFilter(self)
    ...

def eventFilter(self, source, event):
    if (source is self.ui.label and event.type() == QtCore.QEvent.Resize):
        # re-scale the pixmap when the label resizes
        self.ui.label.setPixmap(self.pixmap.scaled(
            self.ui.label.size(), QtCore.Qt.KeepAspectRatio,
            QtCore.Qt.SmoothTransformation))
    return super(MainWindow, self).eventFilter(source, event)

(注意:您可能需要在最后一行更改MainWindow

<强> PS

为了保证图像始终居中,您还需要:

    self.ui.label.setAlignment(QtCore.Qt.AlignCenter)

答案 1 :(得分:0)

我认为使用mainWindow.size()

会导致图像下采样的问题

尝试使用mt_rand代替