0

I want to use ResizeEvent to receive the size of the window and set it to the size of a QLabel, in order to make the image stretched and adapted to the window's dimensions.by a left click of the mouse I can resize my window and the image takes a new size.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Beside of the fact that you should provide a [mcve]: I already fiddled with resizing of label/image contents in previous posts which might be worth a look: [SO: qt remove layouts code](https://stackoverflow.com/a/48871682/7478597). – Scheff's Cat Mar 09 '18 at 16:02

1 Answers1

2

You must have the following considerations:

  • It is not necessary to store QPixmap by means of a pointer since when passing it to the QLabel it is copied by value.

  • Therefore, if you change the size of the QPixmap p will not be reflected in the QLabel since the QPixmap that has the QLabel is a copy of the one you established at the beginning.

  • It is not necessary to use a layout for this task since it will create an infinite loop since this also intervenes in the resizeEvent of the widget where it has been established so if you change the size of the QLabel, it will change the size of the QWidget, and this again I will try to change the QLabel, and so on.

  • It is not advisable to modify the original QPixmap since changing its size modifies the pixels and you will get an unexpected effect.

Using the above we obtain the following code:

*.h

#ifndef TESTSIZE_H
#define TESTSIZE_H

#include <QWidget>

class QLabel;

class testsize : public QWidget
{
    Q_OBJECT

public:
    explicit testsize(QWidget *parent = 0);
    ~testsize();

private:
    QLabel *image;
    QPixmap original_px;

protected:
    void resizeEvent(QResizeEvent *event);
};

#endif // TESTSIZE_H

*.cpp

#include "testsize.h"

#include <QLabel>
#include <QResizeEvent>

testsize::testsize(QWidget *parent) :
    QWidget(parent)
{
    image = new QLabel(this);
    original_px = QPixmap(":/wallpaper.jpg");
    image->setPixmap(original_px);
    resize(640, 480);
}

testsize::~testsize()
{
}


void testsize::resizeEvent(QResizeEvent *event)
{
    QPixmap px = original_px.scaled(event->size());
    image->setPixmap(px);
    image->resize(event->size());
    QWidget::resizeEvent(event);
}

You can find the complete example in the following link.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • the real story that i want to add two images to the Window , in that case we have to use a layout to set positions , but as use said if we ada a layout it will create an infinite loop ...??? – Hassene Lahmar Mar 12 '18 at 07:57