首页 文章

问:父母如何影响儿童小部件的布局?

提问于
浏览
1

我一直在努力学习Qt,以便在我的OpenGL项目之上嵌入GUI . 在这种情况下,我的想法是让我的OpenGL视口填充我的主窗口 . 我有一个简单的基于QtWidget的GUI,它包含一个'RenderSurface',它是QGLWidget的子类 . 但是,我注意到让我的RenderSurface成为我的MainWindow的孩子对我的GUI布局产生了不良影响 .


Here's the simple MainWindow code and screen shot without use of parenting:

#include "mainwindow.h"
#include "rendersurface.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    renderSurface()
{
    setCentralWidget(&renderSurface);

    setWindowTitle("QtGL Test");
}

MainWindow::~MainWindow()
{
}

RenderSurface is NOT a child of MainWindow.

在这种情况下,当我在MainWindow初始化列表中调用其构造函数时,我的RenderSurface(QGLWidget子类)未传递指向任何父QWidget的指针 . 您可以看到深灰色的OpenGL上下文符合窗口的大小,即使我扩展和缩小窗口大小,它似乎也会填满窗口 .

Here's the same thing with parenting:

#include "mainwindow.h"
#include "rendersurface.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    renderSurface(this)
{
    setCentralWidget(&renderSurface);

    setWindowTitle("QtGL Test");
}

MainWindow::~MainWindow()
{
}

enter image description here

简单地将'this'传递给RenderSurface构造函数会改变我的OpenGL上下文最初在窗口中呈现的方式 . 同样值得注意的是,一旦我通过拖动边缘调整窗口大小,我的RenderSurface将开始正确填充窗口 .


Why does making my RenderSurface a child of my MainWindow cause this issue? How can I avoid this buggy-looking behaviour? Also, since my GUI seems to work better without parenting, what are some pros and cons of object parenting in Qt?

2 回答

  • 1

    这是一个众所周知的issue . 我也喜欢这个答案:A widget with a parent doesn't become a window but is embedded into its parent. If you don't put it in a layout it might end up in a strange place on the parent and might have an arbitrary size (0x0 included). So if you want your widget to be a window, simply don't pass a parent at all . 因此,在这种情况下,放置窗口小部件的布局是渲染的关键,而QMainWindow不是布局,但可以有自己的布局或一些布局 .

    另一方面,setCentralWidget已经在处理释放嵌入式窗口小部件,因此没有理由为这样的窗口小部件提供父指针 . 并且setCentralWidget使一个无人值守的小部件居中并正确绘制,就像在布局中一样 .

  • 4
    • 案例1:您正在有效地使用QMainWindow布局,这是一个特定的布局实现,其程度与QGridLayout或QStackedLayout相同 .

    • 案例2:您正在使用默认的Qt窗口小部件布局,它具有更宽松的子窗口小部件设置 . 我知道的唯一条件是子矩形在父矩形内,它们的默认位置是0,0 . 布局不会调整孩子的大小 .

    setCentralWidget(&renderSurface); 将尝试将renderSurface添加到Qmainwindow布局 . 在案例2中,rendersurface已经在布局中,因此此尝试将失败 .

    Also, since my GUI seems to work better without parenting
    

    您对育儿部分的看法不正确 . 在这两种情况下 renderSurface 都成为窗口的子项 .

    QWidget* w = new Qwidget(0);
    QLayout* l = new QHBoxLayout();
    
    l->add(w);
    setLayout(l);
    

    在setLayout期间,布局中的所有窗口小部件都会将其关联性更改为拥有布局的窗口小部件 . w 不再是无父小部件 .

    当一个小部件将被添加到一个布局时,最好的方法是创建它而不像你那样使用父级 . 正确的父级将在稍后设置 .

相关问题