gpt4 book ai didi

c++ - 使用 show() 只打开一个 QDialog 实例,如果我关闭 QDialog,对象是否也被删除

转载 作者:太空宇宙 更新时间:2023-11-04 12:18:51 28 4
gpt4 key购买 nike

在 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 vector 吗?我的第二个问题是:每次我用 close () 对象 pGroupDialogContainer 关闭 QDialog 窗口负责打开它的是毁灭者版?或者当我检测到 QDIalog 已关闭时我需要删除它吗?

最佳答案

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

QMap对话 map ;

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

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

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

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

但正如我所说,您仍然需要从 Map 中删除对话框,否则您的指针会出错,并且您的代码仍会认为该对话框处于打开状态。

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

This signal is emitted when the dialog's result code has been set, either by the user or by calling done(), accept(), or reject().

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

然后在处理 map 的代码中...

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());
}
}

就是这样。

关于c++ - 使用 show() 只打开一个 QDialog 实例,如果我关闭 QDialog,对象是否也被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218080/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com