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

sun*_*ima 3 python position image pyqt qlabel

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

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

上面的代码工作正常,没有任何问题。但是,图像显示在标签的左侧而不是中心。同样,缩放比例会进一步缩小图像,而不是填充整个标签。

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

ekh*_*oro 6

如果您只希望图像填充整个标签,则无论其大小是多少:

    self.ui.label.setScaledContents(True)
    self.ui.label.setPixmap(myPixmap)
Run Code Online (Sandbox Code Playgroud)

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

    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)
Run Code Online (Sandbox Code Playgroud)

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

PS

为了确保图像始终居中,您还需要这样做:

    self.ui.label.setAlignment(QtCore.Qt.AlignCenter)
Run Code Online (Sandbox Code Playgroud)