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<ChildWidget> 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()<<m_pChildWidget;
	delete m_pChildWidget;
}

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<T>, 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<QLabel> label = new QLabel;
     label->setText("&Status:");
     ...
     if (label)
         label->show();




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值