一 解决的问题
在PyQt或者Pyside中使用QLabel显示OpenCV图像或视频流时,常会出现图像尺寸不能缩放或出现图像自动占满整个QLabel,而图像的长宽比例发生变化。
二 设置图像自动占满整个QLabel
使用如下代码可实现QLabel中的图像的自动调整
from PyQt5.QtWidgets import QLabel, QApplication, QWidget, QVBoxLayout
from PyQt5.QtGui import QPixmap
import sys
class ImageLabel(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建一个 QLabel
self.label = QLabel(self)
# 加载图像
pixmap = QPixmap("path/to/your/image.png") # 用你的图片路径替换这里的"path/to/your/image.png"
# 设置图像到 QLabel
self.label.setPixmap(pixmap)
# 启用自动缩放
self.label.setScaledContents(True)
# 设置布局
layout = QVBoxLayout()
layout.addWidget(self.label)
self.setLayout(layout)
# 设置窗口大小和标题
self.setGeometry(100, 100, 400, 300)
self.setWindowTitle('PyQt QLabel Image Example')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = ImageLabel()
sys.exit(app.exec_())
请注意以上代码的核心是
# 启用自动缩放
self.label.setScaledContents(True)
三 设置图像自动调节长宽尺寸但不改变长宽比例
方法如下:
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout
from PyQt5.QtGui import QPixmap, QImageReader
from PyQt5.QtCore import Qt
class ImageWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建一个 QLabel 用于显示图像
self.imageLabel = QLabel(self)
# 加载图像,但不直接设置到 QLabel 上
self.image = QPixmap("path/to/your/image.png") # 替换为你的图像路径
# 创建一个布局,并将 QLabel 添加到布局中
layout = QVBoxLayout()
layout.addWidget(self.imageLabel)
self.setLayout(layout)
# 调整窗口大小和标题
self.setGeometry(100, 100, 400, 300)
self.setWindowTitle('PyQt5 QLabel Image Example')
# 显示窗口,并触发 resizeEvent
self.show()
def resizeEvent(self, event):
# 当窗口大小改变时,调整图像大小以适应 QLabel,同时保持长宽比例
scaledImage = self.image.scaled(self.imageLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.imageLabel.setPixmap(scaledImage)
if __name__ == '__main__':
app = QApplication([])
window = ImageWindow()
app.exec_()
请注意以上方法的核心是
def resizeEvent(self, event):
# 当窗口大小改变时,调整图像大小以适应 QLabel,同时保持长宽比例
scaledImage = self.image.scaled(self.imageLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.imageLabel.setPixmap(scaledImage)
四 示例
以下图为例,图像在不改变原长宽比例的情况下在QLabel中最大化显示