gpt4 book ai didi

c++ - 如何正确清理 QWidget/管理一组窗口?

转载 作者:太空狗 更新时间:2023-10-29 20:28:55 25 4
gpt4 key购买 nike

假设我的应用程序中有 2 个窗口,并且有两个类负责它们:class MainWindow: public QMainWindowclass SomeDialog: public QWidget

在我的主窗口中有一个按钮。单击它时,我需要显示第二个窗口。我这样做:

SomeDialog * dlg = new SomeDialog();
dlg.show();

现在,用户在窗口中做了一些事情,然后将其关闭。此时我想从该窗口获取一些数据,然后,我想,我将不得不delete dlg。但是我如何捕捉那个窗口被关闭的事件呢?

或者有没有其他方法可以避免内存泄漏?也许在启动时为每个窗口创建一个实例会更好,然后只是 Show()/Hide() 它们?

我该如何处理这种情况?

最佳答案

建议使用 show()/exec()hide() 而不是每次都动态创建对话框显示它。还可以使用 QDialog 而不是 QWidget

在主窗口的构造函数中创建并隐藏它

MainWindow::MainWindow()
{
// myDialog is class member. No need to delete it in the destructor
// since Qt will handle its deletion when its parent (MainWindow)
// gets destroyed.
myDialog = new SomeDialog(this);
myDialog->hide();
// connect the accepted signal with a slot that will update values in main window
// when the user presses the Ok button of the dialog
connect (myDialog, SIGNAL(accepted()), this, SLOT(myDialogAccepted()));

// remaining constructor code
}

在连接到按钮的 clicked() 事件的插槽中简单地显示它,如果有必要,将一些数据传递给对话框

void myClickedSlot()
{
myDialog->setData(data);
myDialog->show();
}

void myDialogAccepted()
{
// Get values from the dialog when it closes
}

关于c++ - 如何正确清理 QWidget/管理一组窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11687144/

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