0

假设某个插槽被某个基于 QDialog 的类调用,

我在别处创建对话框,例如

 MyDialog *dlg = new MyDialog (this);
 connect (dlg , SIGNAL(valueSet(QString)) , SLOT(slotGetValue(QString)));
 dlg->exec ();

在插槽中,我使用删除它的“最深”父类来删除对象,即 QObject:

 void slotGetValue (const QString & key)
 {
    // process the value we retrieved
    // now delete the dialog created
    sender()->deletLater ();
 }

这是正确的做法吗?那安全吗?

4

1 回答 1

1

应该没有理由删除模态对话框。由于 QDialog::exec() 阻塞,对话框可以在返回后立即安全删除。

MyDialog *dlg = new MyDialog (this);
connect (dlg , SIGNAL(valueSet(QString)) , SLOT(slotGetValue(QString)));
dlg->exec ();
delete (dlg);

由此,您可能猜到不需要使用 new 和 delete。你可以把它放在堆栈上,离开作用域时它会被销毁。像这样:

MyDialog dlg(this);
connect(&dlg, SIGNAL(valueSet(QString)) , SLOT(slotGetValue(QString)));
dlg.exec();

除非您在 MyDialog 构造函数中需要 this 指针,否则没有理由传递它。

于 2012-05-03T14:53:21.047 回答