当我尝试制作我的应用程序时,当我在 QLabel
中重新显示新的 QPixmap
时,我偶然发现了这种意外行为。我尝试简化代码并最终得到下面的代码。我还附上了该行为的视频。
我在这里提供了一个可复制的示例(它只需要同一目录中的一些 .jpg 文件):
import sys
import os
import random
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QSizePolicy
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
class AppDemo(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(200, 200, 400, 400)
current_working_dir = os.path.abspath('')
dir_files = os.listdir(current_working_dir)
# Saving .jpg from the dir
self.picture = []
for file in dir_files:
if file.endswith(".jpg"):
self.picture.append(file)
self.label = QLabel()
self.label.setStyleSheet("border: 1px solid black;") # <- for the debugging
self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding)
self.label.setPixmap(self.random_picture_selector())
button = QPushButton("Reload Picture")
button.clicked.connect(self.reload_picture)
layout = QVBoxLayout(self)
layout.addWidget(button)
layout.addWidget(self.label)
def reload_picture(self):
self.label.setPixmap(self.random_picture_selector())
def random_picture_selector(self):
rnd_picture = random.choice(self.picture)
pixmap = QPixmap(rnd_picture)
pixmap = pixmap.scaledToWidth(self.label.width(), Qt.SmoothTransformation)
# pixmap = pixmap.scaled(self.label.width(), self.label.height(), Qt.KeepAspectRatio) # <- even this is not working
return pixmap
if __name__ == '__main__':
app = QApplication(sys.argv)
demo = AppDemo()
demo.show()
sys.exit(app.exec_())
其他信息:
在简化代码时,我意识到当我删除以下这些行时问题就消失了。 (虽然我不太确定这部分代码确实导致了问题)
pixmap = pixmap.scaledToWidth(self.label.width(), Qt.SmoothTransformation)
# pixmap = pixmap.scaled(self.label.width(), self.label.height(), Qt.KeepAspectRatio) # <- even this is not working
即使在查找了QPixmap
和QLabel
的文档后,我真的不知道是什么原因导致了问题。
最佳答案
该问题是由样式表边框引起的。如果您在设置像素图之后打印像素图和标签大小,您会看到标签宽度增加了 2 个像素,这是左右边框的总和。
您可以删除边框,或者使用 contentsRect()
:
width = self.label.contentsRect().width()
pixmap = pixmap.scaledToWidth(width, Qt.SmoothTransformation)
了解有关 Box Model 的更多信息在 Qt 样式表文档中。
关于python - 重新加载时`QPixmap`和`QLabel`大小略有增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71902095/