使用show()只打开一个QDialog实例,如果我关闭QDialog,也会删除Object

Open only one instance of QDialog with show() , and also does the Object is deleted if i close the QDialog

本文关键字:QDialog Object 删除 如果 实例 使用 一个 show      更新时间:2023-10-16

在Qt中,每次单击某个项目时都会打开QDialog窗口我用new来做这件事,我想确保我只为每个项目打开一个QDialog实例点击:

void foo::treeWidget_itemClicked(QTreeWidgetItem *item,nt column)                                               
    .....
    QString groupID = item->data(0, Qt::UserRole).toString();
    QString groupName = item->text(0);
    GroupDialogContainer* pGroupDialogContainer = new GroupDialogContainer(groupID,                                                                               groupName,                                                                                   this);
    pGroupDialogContainer->show();
}
class GroupDialogContainer : public QDialog
{
    Q_OBJECT

public:
    GroupDialogContainer(QString GroupId,QString GroupName,QWidget *parent=0); 
    GroupDialogContainer(QWidget *parent=0);
    virtual ~GroupDialogContainer();
    Ui::GroupDialog ui;
public slots:
    void closeEvent(QCloseEvent *event);
};

我需要保留GroupDialogContainer的某种哈希或向量吗?我的第二个问题是:每次我用close()对象pGroupDialogContainer关闭QDialog窗口时负责打开它的是驱逐舰艾德?或者当我检测到QDIalog已经关闭时,我需要删除它吗?

是的,您可能应该保留一些对话框列表,以跟踪哪些对话框已经打开。如果你的GroupID是你唯一的ID,那么你可以这样做:

QMap对话框映射;

void foo::treeWidget_itemClicked(QTreeWidgetItem*项,nt列){
。。。。。QString groupID=item->data(0,Qt::UserRole).toString();

if (! DialogMap.contains(groupID))
{
  //  Popup the dialog and add it to map
  ...
  DialogMap.insert(groupID, pGroupDialogContainer);
}

}

现在,对于另一部分。最重要的是,当对话框关闭时,您需要从地图中删除该项目。然后你可以删除对话框,或者我的建议是让对话框在关闭时删除自己,如下所示:

 // set automatic deletion of object on close
 setAttribute(Qt::WA_DeleteOnClose);

但是,正如我所说,您仍然需要从Map中删除该对话框,否则您会有一个错误的指针,并且您的代码仍然认为该对话框是打开的。

因此,您需要来自对话框的某种信号来指示它正在关闭。有一个finished(int result)信号,当你触发一个结果时就会调用:

当对话框的结果代码已经设置,由用户或通过调用done()、accept()或reject()。

但是,您始终可以在对话框中创建自己的信号,并在对话框中调用closeEvent时发出信号。

然后在处理地图的代码中。。。

connect( pGroupDialogContainer, SIGNAL(WindowClosed()), this, SLOT(vCleanUpTheMap()));
...
void vCleanUpTheMap()
{
   GroupDialogContainer *pDialog = dynamic_cast<GroupDialogContainer *>(sender());
   if (pDialog)
   {
      // Just to keep things clean disconnect from the dialog.
      disconnect(pDialog);
      //  I am assuming that you can get the key groupID from the dialog
      //  Cause it's a lot easier to remove from a map with the key
      DialogMap.remove(pDialog->GetGroupID());
   }
}

就是这样。