通过布局配置QWidget以填充父容器

6
我正在开发一个QMainWindow应用程序,遇到了以下问题:我有一个QMainWindow,它有一个centralWidget作为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个回答

8
在你的代码中,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

enter image description here

//如果需要,下面的代码将隐藏边框中的绿色。
//l->setMargin(0);


setMargin现在已经过时并且不再使用。https://doc.qt.io/qt-5/qlayout-obsolete.html - Ivan P.
在PyQt5的上下文中,至少在构造函数控制权传递后,GridLayout本地变量并不会消失:毫不奇怪,小部件保留了对其自己布局的引用。如果使用C++,我会感到惊讶,这里是否有所不同。最重要的是addWidget方法:子窗口只是其父窗口的子窗口是不够的,如果它要被此布局对象正确处理,它还必须添加到其父布局中。因此,我对这个解决方案感到困惑:对于从PyQt5角度来看的任何人来说,它都不适用... - mike rodent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接