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

<p>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).</p>

<p>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:</p>

<p><a href="https://i.stack.imgur.com/Q90hW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Q90hW.png" alt="output"></a></p>

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

<p><strong>MainWindow:</strong></p>

<pre><code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include &lt;QGridLayout&gt;
#include &lt;QMainWindow&gt;
#include &lt;QWidget&gt;

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

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

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

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

#endif // MAINWINDOW_H
</code></pre>