简体   繁体   English

Qt布局,作为父级传递和不传递QWidget之间的区别

[英]Qt layouts, difference between passing and not passing QWidget as parent

I have created a simple QHBoxLayout (horizontal) that is pushed to the bottom of the QVBoxLayout (Vertical) and it contains two buttons. 我创建了一个简单的QHBoxLayout (水平),将其推到QVBoxLayout (垂直)的底部,它包含两个按钮。 See code: 看到代码:

QWidget* create_ver_and_horizontal_box() {
    QWidget* temp = new QWidget();

    // Add buttons to the horizontal box
    QHBoxLayout* hbox = new QHBoxLayout();

    QPushButton *ok = new QPushButton("OK");
    QPushButton *cancel = new QPushButton("Cancel");

    hbox->addWidget(ok);
    hbox->addWidget(cancel);

    // Create a vertical box and add the horizontal box to 
    // the end of it
    QVBoxLayout* vbox = new QVBoxLayout();   
    vbox->addStretch(1);
    vbox->addLayout(hbox);

    // set the layout and return
    temp->setLayout(vbox);
    return temp;
}

and the resulting UI is the following. 最终的用户界面如下。 在此处输入图片说明

But when I add the QWidget temp to be the parent of the QHBoxLayout, like so: 但是,当我将QWidget temp添加为QHBoxLayout的父级时,如下所示:

    // Add buttons to the horizontal box
    QHBoxLayout* hbox = new QHBoxLayout(temp);

This is what I get: 这是我得到的: 在此处输入图片说明

I want to understand what is going on here. 我想了解这里发生了什么。 And in which cases I want the QWidget to be the parent of a layout or any other QWidget(s) and in which cases I don't the containing QWidget to be the parent of the containing QWidgets. 在某些情况下,我希望QWidget成为布局或任何其他QWidget的父项,在那种情况下,我不让包含QWidget的人成为包含QWidget的父项。 For example, I could've added temp to be the parent of the two Push buttons but I didn't. 例如,我可以将temp添加为两个“按钮”的父级,但我没有。 What is the implication of not adding vs adding. 不添加与添加的含义是什么。

Thanks, 谢谢,

QHBoxLayout* hbox = new QHBoxLayout(temp);

is equivalent to 相当于

QHBoxLayout* hbox = new QHBoxLayout();
temp->setLayout(hbox);

Ie you are making the horizontal layout responsible for temp . 也就是说,您正在制作负责temp的水平布局。

The call to setLayout(vbox) should have generated a runtime warning message, that temp already has a layout, hinting at that. setLayout(vbox)的调用应该已经生成了运行时警告消息,该temp消息已经具有布局,以进行提示。

Since you want the vertical layout to be responsible for that widget, either keep the temp->setLayout(vbox) or pass temp to the constructor of QVBoxLayout . 由于您希望垂直布局负责该小部件,因此请保留temp->setLayout(vbox)或将temp传递给QVBoxLayout的构造QVBoxLayout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM