Define Qt Layout so that it keeps minimum size

36 views Asked by At

I would like a Qt dialog to have the minimum size possible given the layout.

The layout consists of a QVBoxDialog, with several elements. One is a QLabel with a QPixmap. This is the fixed size element that I would like to constrain the QDialog's width.

The problem now is that it remains possible to enlarge the QDialog, which then leaves a blank space to the side of the QLabel.

How can I achieve that the layout of the widget (the QDialog) cannot be enlarged by "adding empty space" to the right of the QLabel?

Here is a MWE illustrating the problem:

File main.h

#ifndef MAIN_H
#define MAIN_H

#include <QDialog>
#include <QLabel>

class Dialog : public QDialog {
    Q_OBJECT
public:
    Dialog();
    ~Dialog() {};
private:
    QLabel *px;
    QPixmap pxmap;
};


#endif // MAIN_H

File main.cpp

#include <QApplication>
#include <QPixmap>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QColor>
#include <QSizePolicy>

#include "main.h"

Dialog::Dialog() {
    setWindowTitle("MWE");

    resize(100,100);

    QVBoxLayout *vLayout = new QVBoxLayout;
    setLayout(vLayout);

    QHBoxLayout *hLayout = new QHBoxLayout;
    vLayout->addLayout(hLayout);

    QPushButton * btn;
    hLayout->addWidget(btn = new QPushButton("AA"));
    btn->setMinimumWidth(10);
    hLayout->addWidget(btn = new QPushButton("BB"));
    btn->setMinimumWidth(10);
    hLayout->addWidget(btn = new QPushButton("CC"));
    btn->setMinimumWidth(10);

    vLayout->addWidget(px = new QLabel());

    pxmap = QPixmap(QSize(150, 150));
    pxmap.fill((QColor("red")));
    px->setPixmap(pxmap);
}


int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    Dialog w;
    w.show();

    return a.exec();
}

What I would like is this minimum size:

enter image description here

...and I would like to prevent the dialog from being enlarged like below (the green arrows indicate the added space):

enter image description here

I tried setting different QSizePolicys to the dialog and the layout, but without success.

0

There are 0 answers