QWIDGET을 올바르게 정리하는 방법 / Windows 집합을 관리하는 방법은 무엇입니까?
-
12-12-2019 - |
문제
내 응용 프로그램에 2 개의 창이 있고 두 개의 클래스가 책임을 져야합니다.
class MainWindow: public QMainWindow
및 class SomeDialog: public QWidget
.
내 기본 창에서는 버튼이 있습니다.클릭하면 두 번째 창을 표시해야합니다.나는 그것을 이런 식으로한다 :
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
또는 SubClasses를 사용하는 것을 고려하십시오.QDialog
에는 연결할 수있는 유용한 신호가 있습니다.
void accepted ()
void finished ( int result )
void rejected ()
.