I’ve created a class and I would like to add this class in an other one (both are layouts) but the only error message that I get is that the program crashed.
I feel like there is some obvious logic flaw but I don’t find it, I can show both of them separately but when I try to add one to the other the program crashes. Here is the code:
Mesure.h:
class Mesure : public QWidget
{
public:
Mesure(QString angle);
private:
QToolButton *m_buttonClose;
QHBoxLayout *m_hlayoutMesure;
QCheckBox *m_checkboxMesure;
QLabel *m_labelAngle;
};
Mesure.cpp:
Mesure::Mesure(QString angle) : QWidget()
{
QHBoxLayout *m_hlayoutMesure = new QHBoxLayout;
QCheckBox *m_checkboxMesure = new QCheckBox(this);
QToolButton *m_buttonClose = new QToolButton(this);
QLabel *m_labelAngle = new QLabel(angle, this);
m_buttonClose->setText("X");
m_hlayoutMesure->addWidget(m_checkboxMesure);
m_hlayoutMesure->addWidget(m_labelAngle);
m_hlayoutMesure->addWidget(m_buttonClose);
setLayout(m_hlayoutMesure);
}
PanneauMesure.h:
class PanneauMesure : public QWidget
{
public:
PanneauMesure();
void add(Mesure *mesure);
private:
QVBoxLayout *m_vlayoutMesures;
};
PanneauMesure.cpp:
PanneauMesure::PanneauMesure() : QWidget()
{
QVBoxLayout *m_vlayoutMesures = new QVBoxLayout;
setLayout(m_vlayoutMesures);
}
void PanneauMesure::add(Mesure *mesure)
{
m_vlayoutMesures->addWidget(mesure);
setLayout(m_vlayoutMesures);
}
main.cpp:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
PanneauMesure panneau;
Mesure mesure("14°");
panneau.add(&mesure);
return app.exec();
}
Edit:
Problem solved, I just had to modify the files like this:
Mesure.cpp:
Mesure::Mesure(QString angle) : QWidget(),
m_hlayoutMesure(new QHBoxLayout(this)),
m_checkboxMesure(new QCheckBox(this)),
m_buttonClose(new QToolButton(this)),
m_labelAngle(new QLabel(angle, this))
{
m_buttonClose->setText("X");
m_hlayoutMesure->addWidget(m_checkboxMesure);
m_hlayoutMesure->addWidget(m_labelAngle);
m_hlayoutMesure->addWidget(m_buttonClose);
setLayout(m_hlayoutMesure);
}
PanneauMesure.cpp:
PanneauMesure::PanneauMesure() : QWidget(),
m_vlayoutMesures( new QVBoxLayout(this))
{
setLayout(m_vlayoutMesures);
}
void PanneauMesure::add(Mesure *mesure)
{
m_vlayoutMesures->addWidget(mesure);
setLayout(m_vlayoutMesures);
}
In your constructors, you create local variables that hide your class members. You store the pointers to allocated elements in these local variables, but your actual class variables are left default-initialized (i.e. they contain garbage).
When accessing these garbage values (as you do in
PanneauMesure::add) you end up having undefined behaviour, this time a crash (lucky you!)As a sidenote, you should probably use initializer lists to initialize your class variables, like this:
Also, you don’t need to call
setLayoutrepeatedly.