PDA

View Full Version : QPushButton deleting itself on click



Cruz
23rd January 2009, 08:27
I'm trying to implement little close buttons on widgets, so that when the close button is pressed the widget is deleted. I connected the clicked() signal of the button to a slot of the widget.



void MyWidget::delete()
{
delete this;
}


This works really well too. The widget is deleted from its parent and from the layout and the layout is redone. Except that I get a warning:

QObject: Do not delete object, 'unnamed', during its event handler!

I suppose it's because the clicked() signal hasn't returned yet and the destructor of the button is called, since the parent widget is deleted. But then, how can a button ever delete itself on click?

h123
23rd January 2009, 08:46
one way is: hide this button in 'MyWidget::delete(){}' and later delete this object.

spirit
23rd January 2009, 08:48
I would make this a little different. I'd set Qt::WA_DeleteOnClose for a widget and by clicking on button just close the window. Qt::WA_DeleteOnClose -- means that a widget will be delete (the dtor will be called and memory will be free) when it closes.

Cruz
23rd January 2009, 09:14
Awesome! Like spirit suggested, this is all it takes:



MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
QPushButton *deleteButton = new QPushButton(this);
setAttribute(Qt::WA_DeleteOnClose);
connect(deleteButton, SIGNAL(clicked()), this, SLOT(close()));
}


The widget is also removed from its parent and the layout. It flickers a bit (why isn't double buffering kicking in?), but it's worth the simplicity.

Cruz
23rd January 2009, 09:18
Even better:



MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
QPushButton *deleteButton = new QPushButton(this);
connect(deleteButton, SIGNAL(clicked()), this, SLOT(deleteLater()));
}


Simpler and no more flickering.

I love how better and better solutions converge towards simplicity. :)