在Qt中单击按钮时销毁并重建对象

Destroy and rebuild object on button clicked in Qt

这是一个基本示例,我需要开始工作才能在我的项目中使用它。

我需要有人帮助我通过单击按钮来销毁和重建对象。我的意思是:

//mainwindow.cpp  

{//constructor 
    ui->setupUi(this);  
    /*private*/frame = new QFrame(ui->centralWidget);  
    /*private*/temp = new QPushButton(frame);  
    QPushButton ok = new QPushButton(ui->centralWidget);  
    ok->setGeometry(100,100,50,50);  
    connect(ok, SIGNAL(clicked()), SLOT(des()));  
}

{//slot des()  
    temp->~QPuhsButton();  
    temp = new QPushButton(frame);  
}

看,我只需要temp销毁重建

temp = new QPushButton(frame); 不起作用,因为无论有没有它,temp 都会从布局中消失,这意味着 temp->~QPuhsButton(); 正在 起作用。

现在,这困扰我的原因是因为这个有效:

{//constructor 
    ui->setupUi(this);  
    frame = new QFrame(ui->centralWidget);  
    temp = new QPushButton(frame); 
    temp->~QPuhsButton();  
    temp = new QPushButton(frame);  
    /*QPushButton ok = new QPushButton(ui->centralWidget);  
    ok->setGeometry(100,100,50,50);  
    connect(ok, SIGNAL(clicked()), SLOT(des()));*/
}

我尝试了最后一段代码,看看是否可以按照我尝试的方式通过单击按钮来销毁和重建对象。事实证明是的,这次 temp = new QPushButton(frame); 并且按钮保持在那里。

编辑: 感谢您的回答和评论,但很抱歉,因为在提问之前我没有意识到一些事情。

按钮是deleted/destroyed,它们只是不是 "repainted" 当我再次写 temp = new QPushButton(frame); 时,它们仍然不是。关于这个新问题的帮助,再次抱歉。

您可以使用删除来销毁对象。 destroy 方法只能由对象本身调用。并且 qwidgets 可以被应用程序自动回收。使用指针指向新内存space.

不要手动调用析构函数,除非您正在使用内存池和 placement new。

在 Qt 中最好使用 delateLater() 以避免未处理事件的错误。此外,小部件默认情况下是隐藏的,因此您需要 show() 小部件。

所以你的代码应该是:

{//slot des()  
    if (temp) temp->deleteLater();
    temp = new QPushButton(frame);  
    temp->show();
}