QWidget to closing itself
-
Hello, the QWidget seems to not able to close itself, here is a little snippet of the code:
//A simple wiget with 1 button. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect (ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(showChild(bool))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::showChild(bool){ ChildWidget *widget= new ChildWidget(0); widget->show(); } //The widget which not closing itself ChildWidget::ChildWidget(QWidget *parent) : QWidget(parent) { close(); } void ChildWidget::closeEvent(QCloseEvent * event){ qDebug()<<"close event"; event->accept(); }
it's just mainwindow with 1 button. This code written just to test the problem. After clicking on the button on the mainwindow, i expect the mainwindow display the child widget, and the child widget will close itself by invoking close method from it's constructor, but even after calling close() method the child widget is still on screen
. Any advise or me doing something wrong? Thanks in advance! -
Hi
ChildWidget *widget= new ChildWidget(0);
0 = no parent
this = mainwindow as parent.Could you try to call close(); in a button on the child.
You call close() in its constructor which very uncommon.
I assume its why it stay open. -
Calling close() in constructor doesn't have effect because you're calling
widget->show();
after it and window pops up again.
-
@Ivan-Netskin
you are calling close() in the constructor of the widget. At this time the widget isn't even visible.
I am pretty sure the close event is discarded by some event optimization.Try calling it after you called show() on it.
Or withQMetaObject::invokeMethod( widget, "close", Qt::QueuedConnection );
since show() is called right after you create it.
-
The reason i called close method from constructor is just was a bit lazy to write a few more lines of code, i know it is unusual, but thought it doesn't really matter. But i was wrong as you point me out. Yes, the close method, invoked from function or the method which @raven-worx suggested working as expected, sorry for taking your time. And thanks for the really quick reply!