I'm playing around with QPixmaps in PyQt. I want to make them resize while maintaining the same aspect ratio when the window resizes, but when I try, I can only make the window bigger, never smaller.
Why is this, and is there a workaround?
Here is the code:
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
class ResizablePixmapWidget(QWidget):
def __init__(self, pixmap: QPixmap, parent=None):
super().__init__(parent)
self.original_pixmap = pixmap
self.pixmap_label = QLabel(self)
self.pixmap_label.setPixmap(self.original_pixmap)
layout = QVBoxLayout(self)
layout.addWidget(self.pixmap_label)
layout.setContentsMargins(0, 0, 0, 0)
def resizeEvent(self, event):
widget_size = self.size()
scaled_pixmap = self.original_pixmap.scaled(widget_size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
self.pixmap_label.setPixmap(scaled_pixmap)
self.pixmap_label.resize(scaled_pixmap.size())
# self.pixmap_label.adjustSize()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Replace 'path_to_image.jpg' with the path of your image file
pixmap = QPixmap("path_to_image.jpg")
resizable_pixmap_widget = ResizablePixmapWidget(pixmap, self)
self.setCentralWidget(resizable_pixmap_widget)
self.setWindowTitle('Resizable QPixmap')
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
I've tried to apply the QPixmap to custom QWidget (as seen above) and also a regular Qlablel.
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QPixmap
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Replace 'path_to_image.jpg' with the path of your image file
pixmap = QPixmap("path_to_image.jpg")
scaled_pixmap = pixmap.scaled(self.size(), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
pixmap_label = QLabel(self)
pixmap_label.setPixmap(scaled_pixmap)
self.setCentralWidget(pixmap_label)
self.setWindowTitle('Resizable QPixmap')
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec())
I've tried the available aspect ratio modes (KeepAspectRatio, KeepAspectRatioByExpanding & KeepAspectRatio).
In my actual code I gave up and just used a QPushbutton to rezise the QPixmap manually when I resize the window. But this isn't very elegant.