Python – PyQt – automatically resize widgets/images

PyQt – automatically resize widgets/images… here is a solution to the problem.

PyQt – automatically resize widgets/images

I’m working on a software that takes a picture from a CAM and puts it into a widget window. Since my picture is 640×480, I want it to resize the picture to fit the window so that the user can resize the window to zoom in or out of the image.
I did the following algorithm:

  1. Gets the widget size
  2. Scales are calculated based on the height of the picture and widget
  3. Resize the picture
  4. Display the picture

So far, it works well, but there are problems. When I open the program it starts to grow indefinitely, I know that this happens because the widget is expanding and the picture is getting bigger because the window is increasing in the first place, which is a positive feedback.
However, I’ve tried changing the size policy to preferred, fixed, etc., but none of them worked.

My window structure looks like this: Widget->VLayout->Label (Pixmap image).

Solution

One possible solution is to create a custom widget and override the paintEvent method, as shown in the following code.

class Label(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.p = QPixmap()

def setPixmap(self, p):
        self.p = p
        self.update()

def paintEvent(self, event):
        if not self.p.isNull():
            painter = QPainter(self)
            painter.setRenderHint(QPainter.SmoothPixmapTransform)
            painter.drawPixmap(self.rect(), self.p)

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        lay = QVBoxLayout(self)
        lb = Label(self)
        lb.setPixmap(QPixmap("car.jpg"))
        lay.addWidget(lb)

app = QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())

enter image description here

enter image description here

Related Problems and Solutions