Qt销毁非模态对话框

很多时候需要非模态对话框:当关闭主窗口时,往往非模态对话框依然存在。

bool QWidget::close () 
       Closes this widget. Returns true if the widget was closed; otherwise returns false.
       First it sends the widget a QCloseEvent. The widget is hidden if it accepts the close event. If it ignores the event, nothing happens. The default implementation of QWidget::closeEvent() accepts the close event.
       If the widget has the Qt::WA_DeleteOnClose flag, the widget is also deleted. A close events is delivered to the widget no matter if the widget is visible or not.
       The QApplication::lastWindowClosed() signal is emitted when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed. By default this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus.

由以上可以通过QPointer,在closeEvent中delete掉非模态对话框,如下:

ParentWidget窗体类中有一个QPointer m_pChildWidget;子窗体。

ParentWidget::ParentWidget(QWidget *parent, Qt::WFlags flags)
	: QWidget(parent, flags),m_pChildWidget(NULL)
{
	ui.setupUi(this);
	connect(ui.pushButton,SIGNAL(clicked()),this,SLOT(createWidget()));
}

ParentWidget::~ParentWidget()
{
}

void ParentWidget::createWidget()
{
	if(m_pChildWidget)
	{
		qDebug()<<"m_pChildWidget != NULL";
		m_pChildWidget->showNormal();
		m_pChildWidget->activateWindow();
	}
	else
	{
		qDebug()<<"m_pChildWidget == NULL";
		m_pChildWidget = new ChildWidget;
		m_pChildWidget->show();
	}

}

void ParentWidget::closeEvent( QCloseEvent *ev )
{
	qDebug()<

ChildWidget可以设置setAttribute (Qt::WA_DeleteOnClose);属性,当close时就delete widget。QPointer指针在对象被销毁时会自动被设置为NULL。以下是QPointer的Assistant中的介绍:

      The QPointer class is a template class that provides guarded pointers to QObject.
      A guarded pointer, QPointer, behaves like a normal C++ pointer T *, except that it is automatically set to 0 when the referenced object is destroyed (unlike normal C++ pointers, which become "dangling pointers" in such cases). T must be a subclass of QObject.
      Guarded pointers are useful whenever you need to store a pointer to a QObject that is owned by someone else, and therefore might be destroyed while you still hold a reference to it. You can safely test the pointer for validity.

     QPointer label = new QLabel;
     label->setText("&Status:");
     ...
     if (label)
         label->show();




你可能感兴趣的:(Qt)