2012-07-27 55 views
3

假設我在我的應用程序中有兩個窗口,並且有兩個窗口負責它們: class MainWindow: public QMainWindowclass SomeDialog: public QWidget如何正確清理QWidget /管理一組窗口?

在我的主窗口中,我有一個按鈕。點擊時,我需要顯示第二個窗口。我這樣做:

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

現在,用戶在窗口中做了一些事情,並關閉它。此時我想從該窗口獲取一些數據,然後,我想,我將不得不delete dlg。但是,我怎樣才能捕捉到正在關閉的窗口?

或者有沒有另一種方式沒有內存泄漏?也許最好是在啓動時創建每個窗口的實例,然後他們只是Show()/Hide()

如何管理這種情況?從QWidget

回答

1

我認爲你正在尋找的Qt :: WA_DeleteOnClose窗口標誌:http://doc.qt.io/archives/qt-4.7/qt.html#WidgetAttribute-enum

QDialog *dialog = new QDialog(parent); 
dialog->setAttribute(Qt::WA_DeleteOnClose) 
// set content, do whatever... 
dialog->open(); 
// safely forget about it, it will be destroyed either when parent is gone or when the user closes it. 
+0

ctor使用窗口標誌,而不是窗口小部件屬性。正確的調用是dialog-> setAttribute(Qt :: WA_DeleteOnClose) – 2012-07-28 08:02:27

+0

@FrankOsterfeld謝謝。當我輸入時,我無法編譯,因此我從未檢查過。 – MrFox 2012-07-28 16:49:09

+0

@FrankOsterfeld關閉對話框意味着什麼?說我有一個按鈕,並調用插槽關閉(),然後會發生什麼?對話框是否會從內存中清除? – 2015-10-09 10:58:14

1

子類並重新實現

virtual void QWidget::closeEvent (QCloseEvent * event)

http://doc.qt.io/qt-4.8/qwidget.html#closeEvent

而且它看起來像你想顯示的窗口小部件是一個對話框。所以考慮使用QDialog或它的子類。 QDialog有您可以連接到有用的信號:

void accepted() 
void finished (int result) 
void rejected() 
3

它建議使用的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 
}