PDA

View Full Version : Segmentation fault when trying to add GroupBox to mainLayout



imperator
20th November 2009, 13:47
Hi

I get an segmentation fault when running a program I'm working on. From a button in a application based on QMainWindow, I open a new dialog to create a new activity. In the dialog I want to group the layout in group boxes.



// This is the constructor of the dialog
NewEvent::NewEvent(QWidget* parent) : QDialog(parent){

void createHorizontalGroupBox();

QVBoxLayout* mainLayout = new QVBoxLayout(this);

mainLayout->addWidget(horizontalGroupBox);

setLayout(mainLayout);

...
}

void NewEvent::createHorizontalGroupBox(){
// horizontalGroupBox is declared in the h-file
horizontalGroupBox = new QGroupBox(tr("Some text"));
QHBoxLayout* layout = new QHBoxLayout;

QLabel* actLabel = new QLabel(tr("Some text"));
QLineEdit* actType = new QLineEdit;

layout->addWidget(actLabel);
layout->addWidget(actType);

horizontalGroupBox->setLayout(layout);
}


What happens is that when I click the button in the application the program quits and the "segmentation fault" is returned to the terminal.

If I remove/comment the mainLayout->addWidget(horizontalGroupBox); line, the program works the way I want.

What could this be down to?

Regards,

André

high_flyer
20th November 2009, 14:11
Are you sure the code you posted compiles?




NewEvent::NewEvent(QWidget* parent) : QDialog(parent){

void createHorizontalGroupBox(); //<<<--- this compiles?

QVBoxLayout* mainLayout = new QVBoxLayout(this);

mainLayout->addWidget(horizontalGroupBox);

setLayout(mainLayout);

...
}

imperator
20th November 2009, 14:34
Yes, it does compile.

It's similar to the layout example in the docs (search for Basic Layouts Example).

The function is declared as a private function in the h-file.

rknowles
20th November 2009, 15:45
Compare the example and your code again. It looks like the problem is just what high_flyer points out. Your code says:

void createHorizontalGroupBox();
while this is more like the example:

createHorizontalGroupBox();
Your code declares a new local method. It never defines it and never calls it. Without "void" you actually call the defined method, which creates "horizontalGroupBox", which allows

mainLayout->addWidget(horizontalGroupBox);
to run with a good rather than NULL pointer.

imperator
20th November 2009, 15:53
Oh my :o

I did not notice before now. It did compile, but I can see why I got the segmentation fault.

After correction it works just fine.

Thanks for the replies. I'm off having my eyes checked.

André

disokika
23rd November 2009, 23:48
I accept with code:
void NewEvent::createHorizontalGroupBox()
{
// horizontalGroupBox is declared in the h-file
horizontalGroupBox = new QGroupBox(tr("hello all"));
QHBoxLayout* layout = new QHBoxLayout;

QLabel* actLabel = new QLabel(tr("I love you"));
QLineEdit* actType = new QLineEdit;

layout->addWidget(actLabel);
layout->addWidget(actType);

horizontalGroupBox->setLayout(layout);
}