Qt模态对话框与非模态对话框

本文介绍Qt模态对话框与非模态对话框。

1.模态对话框

模态对话框是指对话框弹出后,我们不能和其他对话框进行交互,阻塞在这里,直到关闭此对话框。

Qt中模态对话框编写:

MyDialog dialog;
int ret = 0;

ret = dialog.exec();
if (ret == QDialog::Accepted) {

} else {  //Rejected

}

或者(new的方法):

MyDialog *dialog;
int ret = 0;

dialog = new MyDialog();

ret = dialog->exec();
if (ret == QDialog::Accepted) {

} else {  //Rejected

}

delete dialog;

注意:别忘了最后的delete。

2.非模态对话框

非模态对话框是指对话框弹出显示后,直接返回,我们仍可以和其他对话框进行交互。

Qt中非模态对话框编写:

MyDialog *dialog;

dialog = new MyDialog(this);

dialog->show();

非模态对话框只能用new的方法(在堆上分配内存),这里我们指定parent,以保证在父窗口销毁时,子窗口能被析构,以防内存泄漏。

对于无法指定父窗口或希望在对话框关闭后就回收内存,可以这样:

MyDialog *dialog;

dialog = new MyDialog();

dialog->setAttribute(Qt::WA_DeleteOnClose);

dialog->show();

这样,对话框在关闭时,就会被析构。

总结,本文介绍了Qt模态对话框与非模态对话框以及在Qt环境下的编写方法。

你可能感兴趣的:(Qt编程,qt)