Qt模态对话框和非模态对话框

在这里插入图片描述
模态框和非模态框创建都是一样的,关键在于显示方法的不同。
两者的区别如下:

模态对话框(不能对其他窗口进行操作),非模态对话框(可以对其他窗口进行操作)
模态对话框通过exec()方法显示,而非模态对话框通过show()方法显示。
这里就要说一下show()和exec()的区别,
show():
显示一个非模式对话框。控制权即刻返回给调用函数。
弹出窗口是否模式对话框,取决于modal属性的值。
(原文:Shows the dialog as a modeless dialog. Control returns immediately to the calling code.
The dialog will be modal or modeless according to the value of the modal property. )

exec():
显示一个模式对话框,并且锁住程序直到用户关闭该对话框为止。函数返回一个DialogCode结果。
在对话框弹出期间,用户不可以切换同程序下的其它窗口,直到该对话框被关闭。
(原文:Shows the dialog as a modal dialog, blocking until the user closes it. The function returns a DialogCode result.
Users cannot interact with any other window in the same application until they close the dialog. )
这里我们用代码看一下

  		QDialog dia(this);
    	dia.resize(200,100);
      	dia.exec();
    	qDebug()<<"模态对话框创建";

        //非模态对话框创建
        QDialog * dia1 = new QDialog(this);
        dia1->show();
        dia1->setAttribute(Qt::WA_DeleteOnClose);

这段代码是写在lambda表达式里面的,所以非模态对话框的创建采用了new,否则会出现对话框一闪而过的情况,而模态对话框由于调用了exec()方法,所以不会出现一闪而过的情况,最后一行的setAttribute(Qt::WA_DeleteOnClose);是让堆中的空间在创建后及时的释放,以防申请空间过多而导致的内存泄漏问题(虽然正常情况不可能出现)。

发布了212 篇原创文章 · 获赞 4 · 访问量 8748

猜你喜欢

转载自blog.csdn.net/ShenHang_/article/details/104877408