PDA

View Full Version : adjust QLabel according to the size of the window



rafik
14th February 2016, 12:15
Hello,
i have an image and i want to display it but i don't want to fix the size of a QLabel, i want the QPixmap to be adjusted automatically with the QLabel and the QLabel also be adjusted dynamically according to the size of the window, i.e i want the QLabel to resize itself according to the resize of my QMainWindow in such way the QPixmap is also adjusted with QLabel
How can i do that please.
ImageViewer.h


#ifndef IMAGEVIEWER_H
#define IMAGEVIEWER_H
#include<QtWidgets>

class ImageViewer : public QMainWindow
{
Q_OBJECT
public:
ImageViewer();
public slots:
void ouvrir();
private:
QLabel *label;
QImage *image;
QVBoxLayout *layout;
};

#endif // IMAGEVIEWER_H

imageViewer.cpp


#include "imageviewer.h"

ImageViewer::ImageViewer(): QMainWindow()
{
label = new QLabel(this);

label->move(100,100);
layout = new QVBoxLayout(this);
layout->addWidget(label);
this->setLayout(layout);
QMenu *fichier = menuBar()->addMenu("Fichier");
QMenu *edition = menuBar()->addMenu("Edition");

QAction *ouvrir = new QAction("Ouvrir",this);
fichier->addAction(ouvrir);
connect(ouvrir,SIGNAL(triggered(bool)),this,SLOT(o uvrir()));

}

void ImageViewer::ouvrir()
{
QString nomFichier = QFileDialog::getOpenFileName(this,"Open file", "C://");

QPixmap p(nomFichier);
label->setPixmap(nomFichier);

}


thank you

anda_skoa
14th February 2016, 14:05
QMainWindow already has a layout, set your label as the window's centralWidget.

If you want the label to scale its contents, set "scaledContents" to true.

Cheers,
_

rafik
14th February 2016, 14:54
Thank you Mr anda for your help, it resizes dynamically now when i expand the size, but when i want to resize into smaller size it didn't resize, are the any solutions if possible?
ImageViewer.cpp


#include "imageviewer.h"

ImageViewer::ImageViewer(): QMainWindow()
{
QWidget *centralArea = new QWidget(this);
this->setCentralWidget(centralArea);
label = new QLabel(this);
bouton = new QPushButton("ok", this);
layout = new QVBoxLayout(centralArea);

layout->addWidget(label);
layout->addWidget(bouton);
centralArea->setLayout(layout);


QMenu *fichier = menuBar()->addMenu("Fichier");
QMenu *edition = menuBar()->addMenu("Edition");

QAction *ouvrir = new QAction("Ouvrir",this);
fichier->addAction(ouvrir);
connect(ouvrir,SIGNAL(triggered(bool)),this,SLOT(o uvrir()));

}

void ImageViewer::ouvrir()
{
QString nomFichier = QFileDialog::getOpenFileName(this,"Open file", "C://");

QPixmap p(nomFichier);
label->setPixmap(nomFichier);
label->setScaledContents(true);
}