我工作的一个QMainWindow应用程序,并遇到下列问题来了:我有一个QMainWindow具有QWidget作为centralWidget和这个小部件又具有另一种QWidget为孩子应该完全填充第一个(见下面的代码)。
为了实现这一点,我使用了布局。但是在将第二个小部件放入一个布局并将这个布局应用到第一个小部件之后,第二个小部件仍然不会改变它的大小,尽管第一个小部件会改变它的大小(当调整主窗口的大小时)。
我将第一个小部件的背景颜色设置为绿色,将第二个小部件的背景颜色设置为红色,因此我希望生成的窗口完全为红色,但是我得到以下输出:
我该怎么做才能使第二个小部件填充第一个小部件并相应地调整大小?
主窗口:
#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
Run Code Online (Sandbox Code Playgroud)
在您的代码中,这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 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
Run Code Online (Sandbox Code Playgroud)
//如果需要,那么下面的代码将隐藏边框中的绿色。
//l->setMargin(0);