2016-02-03 22 views
1

我工作的一個QMainWindow應用和遇到下列問題就來了: 我有一個QMainWindow具有QWidgetcentralWidget和這個小部件反過來又另一個QWidget爲孩子應該完全填充第一個(見下面的代碼)。配置了QWidget通過佈局填補父

爲了達到這個目的,我使用了佈局。但在將第二個小部件放置到佈局中並將此佈局應用於第一個佈局後,第二個小部件仍然不會更改其大小,儘管第一個小部件的大小不變(調整主窗口大小時)。

我設置了第一小部件綠色和第二紅色之一的背景顏色,所以我希望得到的窗口是完全的紅色,但是我得到以下輸出:

output

爲了讓第二個小部件填充第一個小部件並相應調整大小,我需要做些什麼?

主窗口:

#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 

回答

1

在代碼中的 「QGridLayout l」 是一個局部變量。一旦構造函數代碼塊超出範圍,這將會死亡。所以(1)在類級別添加這個「QGridLayout l」,並保持代碼不變 或者(2)將它作爲指針在構造函數中聲明如下。代碼註釋將詳細解釋。

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 neede, 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

//如果需要它,然後下面的代碼會隱藏在邊框的綠色。
// 1--> setMargin(0);