Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 971
Eduardo Avatar asked Apr 16 '26 23:04

Eduardo


1 Answers

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

like image 113
eyllanesc Avatar answered Apr 18 '26 13:04

eyllanesc