模态
只能操作当前弹出的窗口是模态,及在其没有被关闭之前,用户不能与同一个应用程序的其他窗口进行交互,直到该对话框关闭
常规方法:
QDialog dlg;
dlg.exec();
这种情况下,我们一般都是将对象分配上 stack 上,而不是heap上。
设置成为模态的关键是需要setAttribute:
QDialog * dlg = new QDialog();
dlg->setAttribute(Qt::WA_ShowModal, true);
dlg->show();
有问题是不?为啥exec() 直接可以显示模态对话框呢?看QDialog源代码吧
int QDialog::exec()
{
Q_D(QDialog);
…
setAttribute(Qt::WA_ShowModal, true);
…
show();
…
QEventLoop eventLoop;
(void) eventLoop.exec(QEventLoop::DialogExec);
…
}
看到答案没:exec() 先设置modal属性,而后调用 show() 显示对话框,最后启用事件循环
非模态
可以同时对其他窗口进行操作的是非模态,及当被打开时,用户既可选择和该对话框进行交互,也可以选择同应用程序的其他窗口交互
常规方法:
QDialog * dlg = new QDialog()
dlg->show();
当然,这儿用指针(即分配到heap中)不是必须的。 (有疑问?或者有时发现窗口一闪而过?那么你需要了解C、C++中变量的作用域和生存周期)
想让一个Widget成为模态,我们只需要对其设置:
setAttribute(Qt::WA_ShowModal, true);
注意:这是QWidget的成员函数 ,也就是说,QWidget可以显示为模态或非模态!
https://blog.youkuaiyun.com/dbzhang800/article/details/6300416