Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure QWidget to fill parent via layouts

Tags:

c++

layout

qt

I'm working on a QMainWindow application and came across the following problem: I have a QMainWindow which has a QWidget as centralWidget and this widget in turn has another QWidget as child that should completely fill the first one (see code below).

To achieve this I used layouts. But after placing the second widget into a layout and applying this layout to the first one, the second widget still won't change its size although the first one does (when resizing the main window).

I set the background color of the first widget to green and the one of the second to red, so I would expect the resulting window to be completely red, however I get the following output:

output

What do I have to do in order to make the second widget fill the first one and resize accordingly?

MainWindow:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QGridLayout>
#include <QMainWindow>
#include <QWidget>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0) : QMainWindow(parent) {

        QWidget *p = new QWidget(this);  // first widget
        p->setStyleSheet("QWidget { background: green; }");
        this->setCentralWidget(p);

        QWidget *c = new QWidget(p);  // second widget
        c->setStyleSheet("QWidget { background: red; }");

        QGridLayout l;
        l.addWidget(c, 0, 0, 1, 1);
        p->setLayout(&l);
    }
};

#endif // MAINWINDOW_H
like image 787
a_guest Avatar asked Feb 03 '16 18:02

a_guest


Video Answer


1 Answers

In your code the QGridLayout l is a local variable. This will die once the constructor code block goes out of scope. So (1) add this QGridLayout l in the class level and remaining of your code unchanged OR (2) declare it as a pointer inside the constructor as below. Code comment will explain in detail.

QWidget *p = new QWidget(this);  // first widget
p->setStyleSheet("QWidget { background: green; }");
this->setCentralWidget(p);

QWidget *c = new QWidget(p);  // second widget
c->setStyleSheet("QWidget { background: red; }");

//Central widget is the parent for the grid layout.
//So this pointer is in the QObject tree and the memory deallocation will be taken care
QGridLayout *l = new QGridLayout(p); 
//If it is needed, then the below code will hide the green color in the border. 
//l->setMargin(0);
l->addWidget(c, 0, 0, 1, 1);
//p->setLayout(&l); //removed. As the parent was set to the grid layout

enter image description here

//If it is needed, then the below code will hide the green color in the border.
//l->setMargin(0);

like image 50
Jeet Avatar answered Oct 26 '22 23:10

Jeet