Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
To add widgets to a layout I could write:
Why does nit not work, when I write:
@ QLabel label("Name:");
I thought that I create a QLineEdit object and a QHBoxLayout object by calling their default constructor. But this is obviously not the case, because the compiler refuses to compile that code. If these two line are not constructor calls, what else happens here?
Zlatomir last edited by
For the default constructor use: QHBoxLayout layout;
Because this: QHBoxLayout layout(); gets interpreted like a function declaration (a function named layout witch doesn't take any parameters and returns a QHBoxLayout)
iunknwn last edited by
QLineEdit lineEdit(); or QHBoxLayout layout() could be parsed as an object definition with an empty initializer or a function declaration. The language standard specifies that the ambiguity is always resolved in favor of the function declaration. An empty parentheses initializer is allowed in other contexts e.g. in a new expression or constructing a value-initialized temporary.
@QLineEdit* lineEdit = new QLineEdit();@
In Qt, it is a good practice to create all widgets (all classes that inherits QWidget) on heap, that way they all stay in parent-child relationship and parents cleans up on deletion.
So I would rather do this.
QWidget* widget = new QWidget(); //parent
QLabel* label = new QLabel("Name:");
QLineEdit* lineEdit = new QLineEdit();
QHBoxLayout* layout = new QHBoxLayout();
widget->setLayout(layout); //This re-parents layout, label and lineEdit as children of widget.
lyuts last edited by
Zlatomir is write, in your code:
this means the declaration of a function. Everybody should be careful about this. Scott Meyers mentioned about this in his books. That's why I prefer writing
@QLineEdit lineEdit; // on stack@
@QLineEdit *lineEdit = new QLineEdit(); // on heap@
Just to expand iunknwn's explanation:
This won't work. Look at it this way. As soon as the execution leaves this block, label, lineEdit and layout will be destroyed, because they are local variable (i.e. on stack). So You have to declare them on heap. (Or maybe, make them members of your class. It depends on your design).
Thanks for your help. That answers my question.
I also understand that I normally should create Widgets on the heap. In case of that small test application, the code above works because it is located in the main() function.
Meanwhile bought a helpful book. I understand now that the Mainwindow calls "delete" for all child elements, which is a second cause why child elements must be created on the heap.
My program possibly crashed whenever I closed the main windows but I did not notice it because I did not execute it from a shell window.