Qt對話方塊/視窗、模態和非模態、Qt::WA_DeleteOnClose
阿新 • • 發佈:2019-02-04
聊一聊Qt中,對話方塊/視窗、模態、非模態、獨立視窗釋放記憶體(設定視窗屬性為Qt::WA_DeleteOnClose)。
用得最多的就是對話方塊/視窗,QMainWindow、QWidget、QDialog等等都是。
常見問題:
1、模態與非模態問題。
模態對話方塊分為應用程式級別的模態和視窗級別的模態。預設是應用程式級別的模態。
應用程式級別的模態:當該種模態的對話框出現時,使用者必須首先對對話方塊進行互動,直到關閉對話方塊,然後才能訪問程式中其他的視窗。
視窗級別的模態:該模態僅僅阻塞與對話方塊關聯的視窗,但是依然允許使用者與程式中其它視窗互動。
Qt::NonModal | 0 | 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::WindowModalitywindowModality) |
用法如:setWindowModality(Qt::WindowModal),設定為視窗級別模態。
2.視窗的記憶體洩漏問題。
使用了new關鍵字在堆中申請了記憶體,但沒有釋放,或者說沒有顯示地呼叫delete來釋放。
a>指定了QObject *parent或QWidget *parent。(安全)
交給Qt接管,Qt代為釋放記憶體。
b>不指定parent,如果沒處理好就會造成記憶體洩漏。(注意)
通常有分為兩種不同的方式。
第一種,使用show()方法顯示視窗。
QDialog *d=newQDialog;
//關閉的同時delete,釋放記憶體
d->setAttribute(Qt::WA_DeleteOnClose);
d->resize(200,100);
d->show();
第二種,使用exec()方法,也叫事件迴圈機制,顯示視窗。
d=newQDialog;
d->resize(200,100);
d->exec();
deleted;
d=NULL;