Eduardo
Eduardo

Reputation: 641

PyQt - Automatically resizing widget/picture

I'm developing a software that gets a pictures from a CAM and put it in a widget window. Since my picture is 640x480, I want it to resize the picture to fit the window size, so user can resize the window to zoom in or out the image. I made the following algorithm:

  1. Get the widget size
  2. Calculate the ration based on picture and widget heights
  3. Resize the image
  4. Display the picture

So far it has worked great but there is a problem. When I open the program it starts growing indefinitely, I know this happens because the widget is expanding and the picture gets bigger because the window is increasing in the first place, it's a positive feedback. However, I have already tried to change the size policy to Preferred, Fixed, etc.. and none have worked.

My window is structure is this: Widget->VLayout->Label(Pixmap image)

Upvotes: 3

Views: 8023

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

A possible solution is to create a custom widget and overwrite 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

Upvotes: 3

Related Questions