模态对话框就是指在子对话框弹出时,焦点被强行集中于该子对话框,子对话框不关闭,用户将无法操作其他的窗口。非模态相反,用户仍然可以操作其他的窗口,包括该子对话框的父对话框。
如果从线程角度来讲,模态对话框实际上是线程阻塞的,也就是子对话框是一个线程,但是在创建这个子线程之后,父窗口就阻塞了;模态对话框则不是阻塞型的线程模型,父子线程可以并行运行。
和所有流行的图形类库一样,Qt也提供了创建模态和非模态对话框的机制。
在Qt中创建模态对话框,主要用到了QDialog的exec函数:
SonDialog dlg(this);
int res = dlg.exec();
if (res == QDialog::Accepted)
{
QMessageBox::information(this, "INFORMATION", "You clicked OK button!");
}
if (res == QDialog::Rejected)
{
QMessageBox::information(this, "INFORMATION", "You clicked CANCEL button!");
}
正如上面代码所显示的,可以通过exec函数的返回值来判断用户点击了哪个按钮使得模态对话框退出的,这可以使得我们能够根据用户的不同行为在推出退出模态对话框之后采取不同的处理方法。
在Qt中创建非模态对话框,主要用到了QDialog的show函数:
SonDialog *dlg;
dlg = new SonDialog(this);
dlg->show();
由上面代码,细心的读者可能就会问了,既然new了,如果不delete,那么内存不就存在了泄露的问题了吗?确实如此!所以,我们希望该Qt窗口在退出时自动能够delete掉自己,因此,我们在SonDialog的构造函数里,添加这样的一句代码:
setAttribute (Qt::WA_DeleteOnClose);
这样,我们的SonDialog就能够在它退出时自动的delete掉自己了,不会再造成内存泄漏问题。
PS: setAttribute()使用时存在一个问题,当要获取对话框数据时,这时对话框其实已经关闭销毁。而没有加这句时,其实只是隐藏了,可以获取数据。
最好 使用delete(dlg);
http://doc.qt.nokia.com/4.7/qdialog.html#finished
void QDialog::done ( int r ) [virtual slot]
Closes the dialog and sets its result code to r. If this dialog is shown with exec(), done() causes the local event loop to finish, and exec() to return r.
As with QWidget::close(), done() deletes the dialog if the Qt::WA_DeleteOnClose flag is set. If the dialog is the application's main widget, the application terminates. If the dialog is the last window closed, the QApplication::lastWindowClosed() signal is emitted.
http://doc.qt.nokia.com/4.7/qwidget.html#close
bool QWidget::close () [slot]
Closes this widget. Returns true if the widget was closed; otherwise returns false.
First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget::closeEvent() accepts the close event.
If the widget has the Qt::WA_DeleteOnClose flag, the widget is also deleted. A close events is delivered to the widget no matter if the widget is visible or not.
The QApplication::lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus.