PDA

View Full Version : [solved]Dynamically removing QPushButtons from Flowlayout



neff
30th January 2013, 14:21
Hi all,

I read a few tutorials and started to experiment with qt but I ran into a problem I just don't understand.
So, I'm trying to add and remove QPushButtons to/from a flowlayout (the one from the examples here (http://doc.qt.digia.com/4.7/layouts-flowlayout.html)) which works quite well except for the last item.
Here is my code:



MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{


deletebutton = new QPushButton("delete",this);
addbutton = new QPushButton("add",this);

hbox = new QHBoxLayout();
hbox->addWidget(deletebutton);
hbox->addWidget(addbutton);

QWidget* widget = new QWidget(this);
flowlayout = new FlowLayout(widget);
widget->setLayout(flowlayout);
QScrollArea *scrollArea = new QScrollArea();
scrollArea->setWidgetResizable(true);
scrollArea->setWidget(widget);

vbox = new QVBoxLayout(this);
vbox->addLayout(hbox);
vbox->addWidget(scrollArea);

setLayout(vbox);

connect(deletebutton, SIGNAL(clicked()), this, SLOT(deleteButton()));
connect(addbutton, SIGNAL(clicked()), this, SLOT(addButton()));

}

void MyWidget::deleteButton() {


flowlayout->takeAt(0);
flowlayout->update();

qDebug() <<"deleted: "<<flowlayout->count();
}

void MyWidget::addButton() {

QPushButton* newButton = new QPushButton("button");
flowlayout->addWidget(newButton);
flowlayout->update();
connect(newButton, SIGNAL(clicked()), this, SLOT(buttonpressed()));

qDebug() <<"added: "<<flowlayout->count();
}

void MyWidget::buttonpressed() {


qDebug() <<"button pressed";

}

When I want to delete the last button, I get the correct qDebug() output (0), but the QPushButton does not disappear and when I click on it, it still produces the "button pressed" output. Everything else works just fine. I can add buttons and every button disappears when I click on delete.

What am I doing wrong?

Thanks!

Lesiok
30th January 2013, 15:03
How about this :

void MyWidget::deleteButton()
{
QLayoutItem *item = flowlayout->takeAt(0);
if( item )
{
delete item;
}

qDebug() <<"deleted: "<<flowlayout->count();
}

neff
30th January 2013, 15:20
Thank you for your reply.
Unfortunately the proposed correction doesn't solve the problem.
If I omit "flowlayout->update()" nothing in my program changes after I press the delete button (all Buttons remain in the flowlayout and all buttons still work). If I add "flowlayout->update()" to your correction, the program behaviour is the same as explained in the top post.

I tried a bit more and now I have the behaviour I aimed for with:

void MyWidget::deleteButton() {

QLayoutItem *item = flowlayout->takeAt(0);

if( item )
{
item->widget()->hide();
delete item->widget();
delete item;
}

qDebug() <<"deleted: "<<flowlayout->count();
}

delete item->widget(); makes the button disappear from the layout.
item->widget()->hide(); makes sure that the buttons that are left get rearranged.