gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:36 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

如果你只是想让图片填满整个标签,不管它的大小是多少:

    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)。

附言:

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

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

关于python - PyQt:将缩放图像放在标签的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27676034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com