Get dimensions of QMovie and setScaledSize respecting aspect ratio
-
Hello,
I was building a minimal image/gif viewer for my app and came across an issue.
I wanted to resize the image/gif to fit the label after comparing the images height and width; if height if greater than width, resize keeping the aspect ratio and put the image in centre or else just stretch the image to fit the label.QPixMap image can be dealt with easily but QMovie gif is giving me trouble.
I wanted the same thing like above for the gif but I'm not sure how to compare the QMovie width and height or resize it while respecting aspect ratio.
Given below is a minimal reproduceble code;
import pathlib import sys from PySide6.QtCore import * from PySide6.QtGui import * from PySide6.QtWidgets import * class ImageViewer(QWidget): def __init__(self): super(ImageViewer, self).__init__() self.label = QLabel(self) url = QUrl() url.setUrl("image.gif") self.load_image(url) self.setFixedSize(400, 400) def load_image(self, image_url): suf = pathlib.Path(image_url.url()).suffix if suf == ".gif": gif = QMovie(image_url.url()) print(gif.scaledSize()) if gif.scaledSize().height() > gif.scaledSize().width(): self.label.move(int(self.width() / 2) - gif.scaledSize().width()/2, 0) gif.setScaledSize(self.size()) self.label.setMovie(gif) else: self.label.move(0, 0) gif.setScaledSize(self.size()) self.label.setMovie(gif) gif.start() else: pixmap = QPixmap() pixmap.load(image_url.url) if pixmap.height() > pixmap.width(): scaled_pixmap = pixmap.scaled(self.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation) self.label.setPixmap(scaled_pixmap) self.label.move(int(self.width() / 2) - scaled_pixmap.width() / 2, 0) else: scaled_pixmap = pixmap.scaled(self.width(), self.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation) self.label.move(0, 0) self.label.setPixmap(scaled_pixmap) if __name__ == '__main__': app = QApplication(sys.argv) iv = ImageViewer() iv.show() sys.exit(app.exec())
Printing the gif size before scaling gives -1, -1.
-
Hi,
From memory, I would say that until you start playing it, it won't have any valid size information.
-
Glad you found a solution and thanks for sharing !
Please mark the thread as solved using the "Topic Tools" button or the three dotted menu beside the answer you deem correct so that other forum users may know a solution has been found :-)