PDA

View Full Version : QPushButton if passed by reference to initialize, app crashing on connect statement



rawfool
6th March 2014, 09:00
I have written a function which takes argument as QPushButton pointer, to initialize and apply stylesheet. And later wrote connect statements for the corresponding buttons. On running the application, it is crashing at connect statement. On debugging it's showing segmentation fault. If I comment the connect statements the application runs fine.

If I can see the buttons laid out & also styles applied to them, then why is it giving the segmentation fault error which resembles for unallocated pointers ?


MyWidget::MyWidget(QWidget * parent)
: QWidget(parent)
{
vLyt = new QVBoxlayout;
this->setLayout(vLyt);
addButtons(btn1, "background: green");
addButtons(btn2, "background: white");
addButtons(btn3, "background: black");
addButtons(btn4, "background: blue");

connect(btn1, SIGNAL(clicked(bool)), this, SLOT(mySlot1(bool))); // <<--- In debug mode, it's crashing here
connect(btn2, SIGNAL(clicked(bool)), this, SLOT(mySlot2(bool)));
connect(btn3, SIGNAL(clicked(bool)), this, SLOT(mySlot3(bool)));
connect(btn4, SIGNAL(clicked(bool)), this, SLOT(mySlot4(bool)));
}

void MyWidget::addButtons(QPushButton * pb, QString str)
{
pb = new QPushButton;
pb->setCheckable(true);
pb->setStyleSheet(str);
vLyt->addWidget(pb);
}

Why does the application crash at connect statement ?

anda_skoa
6th March 2014, 10:04
Why does the application crash at connect statement ?

Hint: check the value of btn1 before and after


addButtons(btn1, "background: green");


Cheers,
_

rawfool
6th March 2014, 10:51
Oh got it.
Now I changed it like this & it's working fine.


MyWidget::MyWidget(QWidget * parent)
: QWidget(parent)
{
...
...
btn1 = addButtons( "background: green");
}

QToolButton * MyWidget::addButtons(QString str)
{
QPushButton * pb = new QPushButton;
pb->setCheckable(true);
pb->setStyleSheet(str);
vLyt->addWidget(pb); // <<--- Adding the button to the layout here. Is it ok ??

return pb;
}

anda_skoa
6th March 2014, 15:37
That doesn't look like something that would compile.

"pb" is of type QPushButton* but the method return value is of type QToolButton*, so either of the two needs to be changed.

Adding the button to the layout in there should be OK

Cheers,
_

rawfool
7th March 2014, 10:25
Oh sorry for the typo. I meant QToolButton there.
Thank you.

Infinity
7th March 2014, 19:37
To your code from the first post: You don't pass a QPushButton by reference. You pass "a pointer to QPushButton by value". That's why btn1/2/3/4 doesn't change after calling addButtons - just a copy of that pointer changes.
The following piece of code might work.


void MyWidget::addButtons(QPushButton *&pb, const QString &str)
{
pb = new QPushButton(this);
pb->setCheckable(true);
pb->setStyleSheet(str);
vLyt->addWidget(pb);
}