Question

I have four widgets in a QWidgets named FourWindowWidget I am trying to put these four widgets in FourWindowWidget as one at top and remaining under that while the top one should always have 70% of the size of FourWindowWidget. I tried following :

QSize size = ui->FourWindowWidget->size();

ui->View1->setFixedHeight(size.height()*0.70);

QHBoxLayout * lay = new QHBoxLayout();
lay->addWidget(ui->View2);
lay->addWidget(ui->View3);
lay->addWidget(ui->View4);
lay->setMargin(0);
lay->setContentsMargins(0,0,0,0);

QGridLayout * mainlay =  new QGridLayout;
mainlay->addWidget(ui->View1,0,0);
mainlay->setContentsMargins(0,0,0,0);
mainlay->setHorizontalSpacing(0);
mainlay->setSpacing(0);
mainlay->setMargin(0);
mainlay->addLayout(lay,1,0);

delete ui->FourWindowWidget->layout();
ui->FourWindowWidget->setLayout(mainlay);
this->update();

Now the problem is now View1 have fixed size but size of FourWindowWidget is not fixed. It changes when I remove any other widget around it like closing dock widget. This resize is expected, or say I don't want to make it fixed. So when ever FourWindowWidget get resized its child widgets should be as per ratio set. But I am unable to do this cause 1. There is no any signal that inform resize so the height of internal widget will be calculated. 2. No other way I found to set 70% height of top widget rather than setFixedHeight in grid layout.

I have tried with setting QSizePolicy to setHieghtForWidth but iit is not a working solution. Please suggest me to do this by any way.


The Question is kind of duplicat of Resizing Qt Widgets based on Window size but there nobody answered.

Was it helpful?

Solution

Setting the stretch factor for your layout should work. I'm not sure why you are using a grid layout for this, when you are adding everything in the same column, but here is an example that works:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    gridLayout = new QGridLayout;
    this->centralWidget()->setLayout(gridLayout);
    label1 = new QLabel("l1");
    label2 = new QLabel("l2");
    label3 = new QLabel("l3");
    label4 = new QLabel("l4");
    gridLayout->addWidget(label1, 0, 0);
    gridLayout->addWidget(label2, 1, 0);
    gridLayout->addWidget(label3, 2, 0);
    gridLayout->addWidget(label4, 3, 0);
    gridLayout->setRowStretch(0,7);
    gridLayout->setRowStretch(1,1);
    gridLayout->setRowStretch(2,1);
    gridLayout->setRowStretch(3,1);
}

In this example label1 will take 70% of the available vertical space, while the other labels will take combined 30% of the available vertical space.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top