Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt5 - resize label to fill the whole window

from PyQt5 import QtGui, QtCore, QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.label = QtWidgets.QLabel(self)
        self.label.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
        self.label.resize(800, 600)
        self.label.setContentsMargins(0, 0, 0, 0);
        self.pixmap = QtGui.QPixmap("image.jpg")
        self.label.setPixmap(self.pixmap)
        self.label.setMinimumSize(1, 1)
        self.label.installEventFilter(self)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.label)

    def eventFilter(self, source, event):
        if (source is self.label and event.type() == QtCore.QEvent.Resize):
            self.label.setPixmap(self.pixmap.scaled(
                self.label.size(), QtCore.Qt.KeepAspectRatio))
        return super(Window, self).eventFilter(source, event)

if __name__ == '__main__':

    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    window.resize(800, 600)
    sys.exit(app.exec_())

This is my application, my goal is simple - have an image that fills the whole window and resizes after the window resize.

This code works okay in resizing the image, but the label doesn't cover the whole window, I have those "borders". How can I remove them/resize the label to window size? I am working on Windows if this changes things.

Window look

That is the effect I get now.

like image 783
MWaw Avatar asked Oct 24 '25 23:10

MWaw


1 Answers

I solved it in PyQt4, so I'm not 100% sure if it will work for PyQt5, but I guess it should (some minor modifications might be needed, e.g. import PyQt5 instead of PyQt4).

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.label = QtGui.QLabel(self)
        self.label.resize(800, 600)
        pixmap1 = QtGui.QPixmap("image.png")
        self.pixmap = pixmap1.scaled(self.width(), self.height())
        self.label.setPixmap(self.pixmap)
        self.label.setMinimumSize(1, 1)

    def resizeEvent(self, event):
        pixmap1 = QtGui.QPixmap("image.png")
        self.pixmap = pixmap1.scaled(self.width(), self.height())
        self.label.setPixmap(self.pixmap)
        self.label.resize(self.width(), self.height())

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    window.resize(800, 600)
    sys.exit(app.exec_())

The most important for you is definition of resizeEvent. You could use already defined self.pixmap and just resize it, but the quality of the image would degrade the more resizing you use. Therefore, it's better always create new pixmap scaled to current width and height of the Window.

like image 88
Matho Avatar answered Oct 26 '25 13:10

Matho