This question already has answers here:
Resize multiple labels containing images with changing window size
(1 answer)
Auto Resize of Label in PyQt4
(1 answer)
Closed 1 year ago.
In PyQt I'm trying to create a label which contains a pixmap and have the pixmap automatically resize as the label resizes — say, as a result of the window the label is in resizing.
I am experiencing several problems:
The window refuses to resize smaller than its original size.
If you resize the window to a larger size, you can never resize back to a smaller size.
As the window resizes, the label also resizes correctly, but its pixmap does not repaint properly. It appears to "tear" or repeat pixels horizontally and/or vertically.
I started by creating a class PixmapLabel that inherits from QLabel since I wanted to override the resizeEvent event:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
# You can plug in a path to an image of your choosing.
IMAGE_PATH = '../assets/launch_image.jpeg'
class PixmapLabel(QLabel):
"""
A label widget that has a pixmap. As the label resizes so does the
pixmap.
"""
def __init__(self, pixmap: QPixmap = None):
super().__init__()
self.setStyleSheet('background-color: lightgray')
self.setPixmap(pixmap)
def resizeEvent(self, event: QResizeEvent):
"""As the PixmapLabel resizes, resize its pixmap."""
super().resizeEvent(event)
self.setPixmap(self.pixmap())
def setPixmap(self, pixmap: QPixmap):
if pixmap is None:
return
# Resize the widget's pixmap to match the width of the widget preserving
# the aspect ratio.
width = self.width()
pixmap = pixmap.scaledToWidth(width)
super().setPixmap(pixmap)
Here is the code for the MainWindow (which derives from QDialog):
class MainWindow(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle('PyQt PixmapLabelWidget Test')
self.resize(300, 300)
# Set the window's main layout.
self.main_layout = QVBoxLayout()
self.setLayout(self.main_layout)
# Add a single widget — a PixmapLabel — to the main layout.
self.lbl_image = PixmapLabel()
self.main_layout.addWidget(self.lbl_image)
pixmap = QPixmap(IMAGE_PATH)
self.lbl_image.setPixmap(pixmap)
Finally, here's the code to run the Python app/script:
if __name__ == '__main__':
app = QApplication([])
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
Here's how the window initially renders with the label and its pixmap: https://cln.sh/gEldrO+.
Here's what it looks like after it has been resized: https://cln.sh/MuhknK+.
You should be able to see the "tearing."
Any suggestions about how to make this widget resize its pixmap correctly?
Related
I'm trying to make a simple image editor GUI using the GridLayout. However, I am coming across a problem where the ratios between the image and the side panels are not what I want them to be. Currently, my code is:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Window(QMainWindow):
def __init__(self, parent = None):
super().__init__(parent)
self.setWindowTitle("PyEditor")
self.setGeometry(100, 100, 500, 300)
self.centralWidget = QLabel()
self.setCentralWidget(self.centralWidget)
self.gridLayout = QGridLayout(self.centralWidget)
self.createImagePanel()
self.createDrawPanel()
self.createLayerPanel()
def createImagePanel(self):
imageLabel = QLabel(self)
pixmap = QPixmap('amongus.png')
imageLabel.setPixmap(pixmap)
self.gridLayout.addWidget(imageLabel, 0, 0, 3, 4)
def createDrawPanel(self):
drawPanel = QLabel(self)
drawLayout = QVBoxLayout()
drawPanel.setLayout(drawLayout)
tabs = QTabWidget()
filterTab = QWidget()
drawTab = QWidget()
tabs.addTab(filterTab, "Filter")
tabs.addTab(drawTab, "Draw")
drawLayout.addWidget(tabs)
self.gridLayout.addWidget(drawPanel, 0, 4, 1, 1)
def createLayerPanel(self):
layerPanel = QLabel(self)
layerLayout = QVBoxLayout()
layerPanel.setLayout(layerLayout)
tab = QTabWidget()
layerTab = QWidget()
tab.addTab(layerTab, "Layers")
layerLayout.addWidget(tab)
self.gridLayout.addWidget(layerPanel, 1, 4, 1, 1)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
This gives me the following window:
When I resize the window, only the filter/draw and layer panels are stretching, and not the image panel. I want to image panel to stretch as well and take up the majority of the window instead.
While theoretically every Qt widget could be used as a container, some widgets should not be used for such a purpose, as their size hints, size policies and resizing have different and specific behavior depending on their nature.
QLabel is intended as a display widget, not as a container. Everything related to its size is based on the content (text, image or animation), so the possible layout set for it will have no result in size related matters and will also create some inconsistencies in displaying the widgets added to that layout.
If a basic container is required, then basic QWidget is the most logical choice.
Then, if stretching is also a requirement, that should be applied using the widget or layout stretch factors. For QGridLayout, this is achieved by using setColumnStretch() or setRowStretch().
Trying to use the row or column span is not correct for this purpose, as the spanning only indicates how many grid "cells" a certain layout item will use, which only makes sense whenever there are widgets that should occupy more than one "cell", exactly like the spanning of a table.
So, the following changes are required to achieve the wanted behavior:
change all QLabel to QWidget (except for the label that shows the image, obviously);
use the proper row/column spans; the imageLabel should be added with only one column span (unless otherwise required):
self.gridLayout.addWidget(imageLabel, 0, 0, 3, 1, alignment=Qt.AlignCenter)
set a column stretch of (at least) 1 for the first column:
self.gridLayout.setColumnStretch(0, 1)
if you want the image to be center aligned in the available space, set the alignment on the widget (not when adding it to the layout):
imageLabel = QLabel(self, alignment=Qt.AlignCenter)
Note that all the above will not scale the image whenever the available size is greater than that of the image. While you can set the scaledContents to True, the result will be that the image will be stretched to fill the whole available space, and unfortunately QLabel doesn't provide the ability to keep the aspect ratio. If you need that, then it's usually easier to subclass QWidget and provide proper implementation for size hint and paint event.
class ImageViewer(QWidget):
_pixmap = None
def __init__(self, pixmap=None, parent=None):
super().__init__(parent)
self.setPixmap(pixmap)
def setPixmap(self, pixmap):
if self._pixmap != pixmap:
self._pixmap = pixmap
self.updateGeometry()
def sizeHint(self):
if self._pixmap and not self._pixmap.isNull():
return self._pixmap.size()
return super().sizeHint()
def paintEvent(self, event):
if self._pixmap and not self._pixmap.isNull():
qp = QPainter(self)
scaled = self._pixmap.scaled(self.width(), self.height(),
Qt.KeepAspectRatio, Qt.SmoothTransformation)
rect = scaled.rect()
rect.moveCenter(self.rect().center())
qp.drawPixmap(rect, scaled)
I have a class of textboxs subclassed from QTextEdit, it automatically resizes to its content and it also resizes when the window is resized.
The texts can be very long, and the textboxs automatically line-wrap the texts, so when the horizontal space increases, the textboxs can shrunk in height, because of less wrapped lines.
The problem is when the textboxs shrunk, their bottom border will be missing, they will only have left, top, and right borders unless the window's width shrunk.
Minimal, reproducible example:
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
class Editor(QTextEdit):
def __init__(self):
super().__init__()
self.textChanged.connect(self.autoResize)
def autoResize(self):
self.document().setTextWidth(self.viewport().width())
margins = self.contentsMargins()
height = int(self.document().size().height() + margins.top() + margins.bottom())
self.setFixedHeight(height)
def resizeEvent(self, e: QResizeEvent) -> None:
self.autoResize()
class Window(QWidget):
def __init__(self):
super().__init__()
self.resize(405, 720)
frame = self.frameGeometry()
center = self.screen().availableGeometry().center()
frame.moveCenter(center)
self.move(frame.topLeft())
self.vbox = QVBoxLayout(self)
self.vbox.setAlignment(Qt.AlignmentFlag.AlignTop)
self.textbox = Editor()
self.textbox.setText(
'Symphony No.6 in F, Op.68 \u2014Pastoral\u2014I. Erwachen heiterer Empfindungen bei der Ankunft auf dem Lande\u2014 Allegro ma non troppo'
)
self.vbox.addWidget(self.textbox)
app = QApplication([])
window = Window()
window.show()
app.exec()
When you click the maximize button, the textbox goes from three wrapped lines to one line, and the bottom border will be missing until you restore the window.
I would like to redraw the borders, I have Google searched for 8+ hours and can't find a solution, and I have tried to the add following autoResize function to no avail:
self.update()
self.viewport().update()
self.repaint()
self.viewport().repaint()
self.setFrameRect(QRect(0, 0, self.width(), height))
How can this be done?
I have got it, the border will be recalculated if the number of lines of text changed, so just define a resizeEvent in whatever is the parent of the QTextEdit, add a new line and remove the new line, job done.
The code:
def resizeEvent(self, e: QResizeEvent) -> None:
text = self.textbox.toPlainText()
self.textbox.setText(text + '\n')
self.textbox.setText(text)
On a second thought, it is better to use a widget that can intercept the resizeEvent, and create a signal and make it emit the signal every time the window is resized, and connect the signal to the slots.
I used the QMainWindow the intercept the event.
Example code:
class UI_MainWindow(QMainWindow):
resized = pyqtSignal(QMainWindow)
def __init__(self):
super().__init__()
...
def resizeEvent(self, e: QResizeEvent) -> None:
self.resized.emit(self)
The above is the main window.
Window = UI_MainWindow()
class TextCell(QVBoxLayout):
...
Window.resized.connect(self.redraw_border)
def redraw_border(self):
text = self.editor.toPlainText()
self.editor.setText(text + '\n')
self.editor.setText(text)
TextCell is the container of the textboxs, and editor is the auto-resizing textbox.
I set the size policy of items in a QSplitter but it doesn't seem to affect anything. When I resize the window in the example below I want my left widget to stop growing once it reaches its size hint (QSizePolicy.Preferred) and the right widget to expand as big as possible (QSizePolicy.Expanding).
It works if I put them in a layout:
from PyQt5 import QtWidgets, QtCore
app = QtWidgets.QApplication([])
class ColoredBox(QtWidgets.QFrame):
def __init__(self, color):
super().__init__()
self.setStyleSheet(f'background-color: {color}')
def sizeHint(self) -> QtCore.QSize:
return QtCore.QSize(200, 200)
box1 = ColoredBox('red')
box2 = ColoredBox('green')
splitter = QtWidgets.QHBoxLayout()
splitter.setContentsMargins(0, 0, 0, 0)
splitter.setSpacing(0)
splitter.addWidget(box1)
splitter.addWidget(box2)
box1.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
box2.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
container = QtWidgets.QWidget()
container.setLayout(splitter)
container.show()
app.exec_()
But it doesn't work if I put them in a QSplitter, the splitter just splits space between them evenly:
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt
app = QtWidgets.QApplication([])
class ColoredBox(QtWidgets.QFrame):
def __init__(self, color):
super().__init__()
self.setStyleSheet(f'background-color: {color}')
def sizeHint(self) -> QtCore.QSize:
return QtCore.QSize(200, 200)
box1 = ColoredBox('red')
box2 = ColoredBox('green')
splitter = QtWidgets.QSplitter(Qt.Horizontal)
splitter.setStretchFactor(0, 0)
splitter.setStretchFactor(1, 1)
splitter.addWidget(box1)
splitter.addWidget(box2)
box1.setSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
box2.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
container = QtWidgets.QMainWindow()
container.setCentralWidget(splitter)
container.show()
app.exec_()
Layout vs Splitter:
The problem comes from the fact that you're setting the stretch factor too early.
setStretchFactor() is ignored if done on a widget index that doesn't exist yet (see the source code for its implementation);
QSplitter resizes the widget proportions based on their size policy; the size policy also includes the horizontal and vertical stretch factors, and they're reset to the 0 default value whenever set again with the basic setSizePolicy(horizontalPolicy, verticalPolicy) (which means that you can specify the stretch in the QSizePolicy, which is the same as using setStretchFactor).
The solution is simple: move the setStretchFactor lines after adding the widgets and setting their policies.
Obviously, a possible alternative is to set the maximum dimension (based on the QSplitter orientation), but that is not exactly the same thing.
If all widgets in the splitter have a maximum size (including situations for which only one widget exists), the result is that the splitter will have a maximum size based on those widgets, depending on other widgets in (or "above") its layout, but if the splitter is the top level window then there will be some blank space remaining whenever it's resized to a size bigger than the maximum of its child[ren].
I'm trying to learn it by re-making an old command line C program I've got for working with pixel art.
At the moment, the main window starts as a single QLabel set to show a 300 x 300 scaled up version of a 10 x 10 white image.
I'm using the resizeEvent (I've also tried using paintEvent with the same problem) to rescale the image to fill the window as the window size is increased.
My question is, how do I rescale the image to fit in the window as the window size is decreased? As it stands, the window can't be resized smaller than the widget displaying the image. Essentially, I can make the window (and image) bigger, but never smaller.
My code for this so far is below. As it stands it's only working based on changes to window width, just to keep it simple while I'm working this out. Is there a way to allow the window to be resized to be smaller than the largest widget? Or is there a better way to approach this problem?
#Create white 10*10 image
image = QImage(10,10,QImage.Format.Format_ARGB32)
image_scaled = QImage()
image.fill(QColor(255,255,255))
class Window(QMainWindow):
#scale image to change in window width (image is window width * window width square)
def resizeEvent(self,event):
if self.imageLabel.width()>self.imageLabel.height():
self.image_scaled = image.scaled(self.imageLabel.width(),self.imageLabel.width())
self.pixmap = QPixmap.fromImage(self.image_scaled)
self.imageLabel.setPixmap(self.pixmap)
QWidget.resizeEvent(self, event)
def __init__(self, parent=None):
super().__init__(parent)
self.setGeometry(100,100,300,300)
self.imageLabel = QLabel()
self.setCentralWidget(self.imageLabel)
self.image_scaled = image.scaled(self.imageLabel.width(),self.imageLabel.width())
self.pixmap = QPixmap.fromImage(self.image_scaled)
self.imageLabel.setPixmap(self.pixmap)
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
While the OP proposed solution might work, it has an important drawback: it uses a QScrollArea for the wrong purpose (since it's never used for scrolling). That approach creates unnecessary overhead while resizing, as the view will need to compute lots of things about its contents before "finishing" the resize event (including scroll bar ranges and geometries) that, in the end, will never be actually used.
The main problem comes from the fact that QLabel doesn't allow resizing to a size smaller than the original pixmap set. To work around this issue, the simplest solution is to create a custom QWidget subclass that draws the pixmap on its own.
class ImageViewer(QWidget):
pixmap = None
_sizeHint = QSize()
ratio = Qt.KeepAspectRatio
transformation = Qt.SmoothTransformation
def __init__(self, pixmap=None):
super().__init__()
self.setPixmap(pixmap)
def setPixmap(self, pixmap):
if self.pixmap != pixmap:
self.pixmap = pixmap
if isinstance(pixmap, QPixmap):
self._sizeHint = pixmap.size()
else:
self._sizeHint = QSize()
self.updateGeometry()
self.updateScaled()
def setAspectRatio(self, ratio):
if self.ratio != ratio:
self.ratio = ratio
self.updateScaled()
def setTransformation(self, transformation):
if self.transformation != transformation:
self.transformation = transformation
self.updateScaled()
def updateScaled(self):
if self.pixmap:
self.scaled = self.pixmap.scaled(self.size(), self.ratio, self.transformation)
self.update()
def sizeHint(self):
return self._sizeHint
def resizeEvent(self, event):
self.updateScaled()
def paintEvent(self, event):
if not self.pixmap:
return
qp = QPainter(self)
r = self.scaled.rect()
r.moveCenter(self.rect().center())
qp.drawPixmap(r, self.scaled)
class Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.imageLabel = ImageViewer(QPixmap.fromImage(image))
self.setCentralWidget(self.imageLabel)
Found a solution. Turns out putting the image inside a QScrollArea widget allows the window to be made smaller than the image it contains even if the scroll bars are disabled. This then allows the image to be rescaled to fit the window as the window size is reduced.
class Window(QMainWindow):
#scale image to change in window width (image is window width * window width square)
def resizeEvent(self,event):
self.image_scaled = image.scaled(self.scroll.width(),self.scroll.height())
self.pixmap = QPixmap.fromImage(self.image_scaled)
self.imageLabel.setPixmap(self.pixmap)
QMainWindow.resizeEvent(self, event)
def __init__(self, parent=None):
super().__init__(parent)
self.setGeometry(100,100,200,200)
self.imageLabel = QLabel()
self.scroll = QScrollArea()
self.scroll.setWidget(self.imageLabel)
self.setCentralWidget(self.scroll)
self.scroll.setWidgetResizable(True)
self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.image_scaled = image.scaled(self.scroll.width(),self.scroll.width())
self.pixmap = QPixmap.fromImage(self.image_scaled)
self.imageLabel.setPixmap(self.pixmap)
app = QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())
I want to use an image (svg file) as background in an QMdiArea. I load the image as QPixmap and scale it in the resizeEvent method to the size of the QMdiArea using
self._background_scaled = self._background.scaled(self.size(), QtCore.Qt.KeepAspectRatio)
self.setBackground(self._background_scaled)
But that puts the image in the upper left corner and repeats it in either X or Y. I want the image to be centered.
How do I scale the QPixmap so it is resized preserving aspect ratio but then add borders to get the exact size?
The setBackground() method accepts a QBrush that is built based on the QPixmap you pass to it, but if a QBrush is built based on a QPixmap it will create the texture (repeating elements) and there is no way to change that behavior. So the solution is to override the paintEvent method and directly paint the QPixmap:
import sys
from PySide2 import QtCore, QtGui, QtWidgets
def create_pixmap(size):
pixmap = QtGui.QPixmap(size)
pixmap.fill(QtCore.Qt.red)
painter = QtGui.QPainter(pixmap)
painter.setBrush(QtCore.Qt.blue)
painter.drawEllipse(pixmap.rect())
return pixmap
class MdiArea(QtWidgets.QMdiArea):
def __init__(self, parent=None):
super().__init__(parent)
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(QtGui.QColor("transparent"))
self._background = pixmap
#property
def background(self):
return self._background
#background.setter
def background(self, background):
self._background = background
self.update()
def paintEvent(self, event):
super().paintEvent(event)
painter = QtGui.QPainter(self.viewport())
background_scaled = self.background.scaled(
self.size(), QtCore.Qt.KeepAspectRatio
)
background_scaled_rect = background_scaled.rect()
background_scaled_rect.moveCenter(self.rect().center())
painter.drawPixmap(background_scaled_rect.topLeft(), background_scaled)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mdiarea = MdiArea()
mdiarea.show()
mdiarea.background = create_pixmap(QtCore.QSize(100, 100))
sys.exit(app.exec_())