聊一聊Qt中,对话框/窗口、模态、非模态、独立窗口释放内存(设置窗口属性为Qt::WA_DeleteOnClose)。
用得最多的就是对话框/窗口,QMainWindow、QWidget、QDialog等等都是。
常见问题:
1、模态与非模态问题。
模态对话框分为应用程序级别的模态和窗口级别的模态。默认是应用程序级别的模态。
应用程序级别的模态:当该种模态的对话框出现时,用户必须首先对对话框进行交互,直到关闭对话框,然后才能访问程序中其他的窗口。
窗口级别的模态:该模态仅仅阻塞与对话框关联的窗口,但是依然允许用户与程序中其它窗口交互。
Qt::NonModal | The window is not modal and does not block input to other windows. | |
Qt::WindowModal | 1 | The window is modal to a single window hierarchy and blocks input to its parent window, all grandparent windows, and all siblings of its parent and grandparent windows. |
Qt::ApplicationModal | 2 | The window is modal to the application and blocks input to all windows. |
设置窗口模态的函数原型:
void | setWindowModality ( Qt::WindowModality windowModality ) |
用法如:setWindowModality(Qt::WindowModal),设置为窗口级别模态。
2.窗口的内存泄漏问题。
使用了new关键字在堆中申请了内存,但没有释放,或者说没有显示地调用delete来释放。
a>指定了QObject *parent或QWidget *parent。(安全)
交给Qt接管,Qt代为释放内存。
b>不指定parent,如果没处理好就会造成内存泄漏。(注意)
通常有分为两种不同的方式。
第一种,使用show()方法显示窗口。
QDialog *d = new QDialog;
//关闭的同时delete,释放内存
d->setAttribute(Qt::WA_DeleteOnClose);
d->resize(200,100);
d->show();
第二种,使用exec()方法,也叫事件循环机制,显示窗口。
d = new QDialog;
d->resize(200,100);
d->exec();
delete d;
d = NULL;