Armen Tsirunyan
Armen Tsirunyan

Reputation: 133092

Parents and setters

This is a general question, which I will illustrate with two examples.

First example: Suppose I have a widget and a Layout associated with it:

QWidget myWidget;
QVBoxLayout* mainLayout = new QVBoxLayout(&myWidget);

Note that I have specified my widget as the parent of my layout. Question is, is this sufficient to associate the layout with my widget or do I have to additionally explicitly set the layout as in:

myWidget.setLayout(mainLayout);

If I do have to explicitly set the layout, then AFAIK setting will also make myWidget the parent of my layout, so what is the point of specifying the parent in the constructor?

Second example:

Suppose I have a line edit and a validator for it.

QLineEdit* lineEdit = new QLineEdit(whatever);
QIntValidator* validator = new QIntValidator(0, 100, lineEdit);

Note that I have set the parent for my validator. In order for the validator to "work", i.e. listen to lineEdit's value change events, do I also have to explicitly set the validator as in

lineEdit->setValidator(validator);

If so, will the setValidator function itself set the parent, and if so, why should I bother specifying the parent in the Validator's constructor?

Hopefully my questions are clear.

Upvotes: 1

Views: 61

Answers (1)

vahancho
vahancho

Reputation: 21250

WRT the first question:

I think QWidget::setLayout() function call and setting the parent widget to a layout are equivalent operations. This pretty much fits to the Qt documentation, that states for QWidget::setLayout():

An alternative to calling this function is to pass this widget to the layout's constructor.

Thus, you do need to call QWidget::setLayout() if the parent widget is already set for the layout.

WRT the second question:

When you construct the validator with line edit as a parent you do not set validator to the line edit - this is just defines the QObjects hierarchy and objects ownership. I think you do not need to mix hierarchical and functional concepts here.

Upvotes: 2

Related Questions