Search code examples
c++qtqwidget

How to delete a widget


Actually im having 2 Qwidgets say "Widget" , "NewWidget". I'm calling "NewWidget" in "Widget" keypress event and viced versa,

void Widget::keyPressEvent(QKeyEvent *qv)
{
  // i want to delete "Widget" here before i call "NewWidget"
   NewWidget *newWidget = new NewWidget();
   newWidget->setStyleSheet("background-color:black;");
   newWidget->setGeometry(0,0,640,480);    
   newWidget->show();
}

I want to delete or destroy the "Widget" before calling "NewWidget"


Solution

  • Try the following

    this->deleteLater();
    

    It will attempt to destroy the widget when the function exits.

    It sounds dangerous/bad to destroy the current widget when you are busy inside a member function of the widget that you want to destroy. Try the above code but otherwise think about redesigning your interactions.