QWidgetを適切にクリーンアップ/ウィンドウのセットを管理するにはどうすればよいですか?
-
12-12-2019 - |
質問
私のアプリケーションに2つのウィンドウがあり、それらを担当する2つのクラスがあるとしましょう:class MainWindow: public QMainWindow
と class SomeDialog: public QWidget
.
私のメインウィンドウにはボタンがあります。クリックすると、2番目のウィンドウを表示する必要があります。私はこのようにします:
SomeDialog * dlg = new SomeDialog();
dlg.show();
これで、ユーザーはウィンドウ内で何かを行い、それを閉じます。この時点で、私はそのウィンドウからいくつかのデータを取得したい、と、私は思う、私はする必要があります delete dlg
.しかし、そのウィンドウが閉じられているイベントをキャッチするにはどうすればよいですか?
または、メモリリークを起こさない別の方法はありますか?起動時に各ウィンドウのインスタンスを作成してから、次のようにする方がよいでしょう Show()
/Hide()
彼ら?
そのようなケースを管理するにはどうすればよいですか?
解決
あなたは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.
. 他のヒント
それは使用することをお勧めします 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
}
からのサブクラス QWidget
と再実装
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 ()