Qt官方助手对该标志的解释如下:
Makes Qt quit the application when the last widget with the attribute set has accepted closeEvent(). This behavior can be modified with the QApplication::quitOnLastWindowClosed property. By default this attribute is set for all widgets of type Qt::Window.
大意是:
当最后一个设置了本属性的窗体部件关闭时(即接受了closeEvent()事件)退出应用程序。这个属性可以被QApplication::quitOnLastWindowClosed函数修改。对所有类型为Qt::Window.的窗体,这个属性默认被设置为true。
如下:
#include "QtWidgetsApplication1.h"
#include "QtTestWidget.h"
QtWidgetsApplication1::QtWidgetsApplication1(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
setWindowTitle("WidgetsApplication1");
// setAttribute(Qt::WA_QuitOnClose, false);
m_pTestWidget = new QtTestWidget();
m_pTestWidget->show();
}
QtWidgetsApplication1::~QtWidgetsApplication1()
{
}
其中 m_pTestWidget是QtWidgetsApplication1的成员变量,类型为:QtTestWidget。QtTestWidget.cpp如下:
#include "QtTestWidget.h"
QtTestWidget::QtTestWidget(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
setWindowTitle("TestWidget");
// setAttribute(Qt::WA_QuitOnClose, false);
}
QtTestWidget::~QtTestWidget()
{
}
弹出标题为:WidgetsApplication1、TestWidget两个窗体。按Qt助手的解释:这两个窗体的Qt::WA_QuitOnClose默认都为true,所以先关闭其中任何一个窗体,程序不会退出,只有当最后一个窗体关闭时,应用程序才退出。
当将QtWidgetsApplication1.cpp构造函数中的setAttribute(Qt::WA_QuitOnClose, false);注释去掉,则:
a):先关闭WidgetsApplication1窗体,程序不退出;再关闭TestWidget窗体,程序才退出。因为此时WidgetsApplication1窗体的Qt::WA_QuitOnClose为false,即剔除了该属性;TestWidget窗体的Qt::WA_QuitOnClose依然为true,即TestWidget窗体是包含Qt::WA_QuitOnClose属性的最后一个窗体,当最后一个包含Qt::WA_QuitOnClose属性的窗体退出时,程序退出。
b):先关闭TestWidget窗体,程序退出。道理同a)条目所述。
当将QtWidgetsApplication1.cpp、QtTestWidget.cpp构造函数中的setAttribute(Qt::WA_QuitOnClose, false);注释都去掉,无论先关闭哪个窗体或两个窗体都关闭,应用程序都不会退出。