gpt4 book ai didi

c++ - 配置 QWidget 以通过布局填充父级

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:51:47 26 4
gpt4 key购买 nike

我正在开发一个 QMainWindow 应用程序,遇到了以下问题:我有一个 QMainWindow,它有一个 QWidget 作为 centralWidget 而这个小部件又有另一个 QWidget 作为 child 完全填满第一个(见下面的代码)。

为了实现这一点,我使用了布局。但是在将第二个小部件放入布局并将该布局应用于第一个小部件之后,第二个小部件仍然不会更改其大小,尽管第一个小部件会更改(在调整主窗口大小时)。

我将第一个小部件的背景色设置为绿色,将第二个小部件的背景色设置为红色,因此我希望生成的窗口完全是红色,但我得到以下输出:

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

最佳答案

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

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

关于c++ - 配置 QWidget 以通过布局填充父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35185113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com