Unsolved Subclass of QDialog isn't displayed correctly
-
Hey, I make a subclass of QDialog with a simple QFormLayout with 2 Labels, and it looks like this:
It appears that the two labels have been put on top of each other...
Header:
#ifndef DIALOGNEWBRANCH_H #define DIALOGNEWBRANCH_H #include <QDialog> class DialogNewBranch : public QDialog { Q_OBJECT public: DialogNewBranch(QWidget* parent); }; #endif // DIALOGNEWBRANCH_H
Class:
#include "dialognewbranch.h" #include <QFormLayout> #include <QLabel> DialogNewBranch::DialogNewBranch(QWidget* parent) : QDialog(parent) { QFormLayout form(this); form.addRow(new QLabel("Name:")); form.addRow(new QLabel("Position:")); }
Code referencing the class:
DialogNewBranch* dialog = new DialogNewBranch(this); if (dialog->exec() == QDialog::Accepted) { // TODO }
What am I doing wrong?
-
Hi and welcome to devnet,
Your layout is on the stack hence it's destroyed at then of the constructor.
-
@astavie said in Subclass of QDialog isn't displayed correctly:
DialogNewBranch::DialogNewBranch(QWidget* parent) : QDialog(parent)
{
QFormLayout form(this);
form.addRow(new QLabel("Name:"));
form.addRow(new QLabel("Position:"));
}Generally when you do this, you use this->setLayout(&form) so that the layout is saved and "assigned" to the widget. As SGaist mentioned, your locally allocated layout goes away at the end of the constructor unless you keep a reference to it as I've done above...maybe reference isn't the right term, as it probably is member copied internally.
-
Actually, I got to thinking about stack allocated widgets and layouts and decided to check the sourcecode. In QWidget::setLayout() there does NOT appear to be any object copy of the layout. It just saves the address of the already created layout, and possibly "reparents" the widgets in the layout...So, stack created layouts are probably a very bad idea...
Also, the sourcecode comments indicate that if the layout constructor references the target widget that will own the layout, then setLayout is not explicitly required.
-
In QWidget::setLayout() there does NOT appear to be any object copy of the layout.
Just as a by-the-by: since all
QLayout
s inherit fromQObject
you know that there will be no copy,QObject
s can't be copied.... -
@JonB said in Subclass of QDialog isn't displayed correctly:
ust as a by-the-by: since all QLayouts inherit from QObject you know that there will be no copy, QObjects can't be copied....
That's actually what got me thinking about the flaw in my logic.