一 QApplication
- QApplication
- 一个Qt GUI应用程序,仅有一个QApplication对象,负责管理应用程序的控制流和主设置。
The QApplication class manages the GUI application’s control flow and main settings.
For any GUI application using Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any given time.
- QCoreApplication QGuiApplication QApplication
- QApplication 派生自 QGuiApplication
- QGuiApplication 派生自 QCoreApplication 。
The QCoreApplication class provides an event loop for Qt applications without UI.
For GUI applications, see QGuiApplication. For applications that use the Qt Widgets module, see QApplication. - 使用了QtWidgets模块的Qt应用程序,需使用QApplication类。
二 qApp
- 在基于QtWidgets的Qt GUI应用程序代码中,若需要使用QApplication对象,可直接调用qApp宏。
- qApp宏定义
// 源码 QtWidgets/qapplication.h
#define qApp (static_cast<QApplication *>(QCoreApplication::instance()))
- 细究QCoreApplication::instance
- QCoreApplication::instance 定义
// 源码 QtCore/qcoreapplication.h
static QCoreApplication *instance() { return self; }
...
static QCoreApplication *self;
- QCoreApplication::self赋值过程
// 源码 Src/qtbase/src/corelib/kernel/qcoreapplication.cpp
// self初始化
QCoreApplication *QCoreApplication::self = 0;
...
// QCoreApplication 构造函数
QCoreApplication::QCoreApplication(int &argc, char **argv
#ifndef Q_QDOC
, int _internal
#endif
)
#ifdef QT_NO_QOBJECT
: d_ptr(new QCoreApplicationPrivate(argc, argv, _internal))
#else
: QObject(*new QCoreApplicationPrivate(argc, argv, _internal))
#endif
{
d_func()->q_ptr = this;
d_func()->init(); // 调用 QCoreApplicationPrivate::init
// d_func()函数说明见后续
#ifndef QT_NO_QOBJECT
QCoreApplicationPrivate::eventDispatcher->startingUp();
#endif
}
...
// QCoreApplicationPrivate::init
void QCoreApplicationPrivate::init()
{
#if defined(Q_OS_MACOS)
QMacAutoReleasePool pool;
#endif
Q_Q(QCoreApplication);
initLocale();
Q_ASSERT_X(!QCoreApplication::self, "QCoreApplication",
"there should be only one application object");
QCoreApplication::self = q; // self 赋值语句
...
}
- 补充说明 d_func()
// 源码 Src/qtbase/src/corelib/kernel/qcoreapplication.h
Q_DECLARE_PRIVATE(QCoreApplication)
// 源码 QtCore/qglobal.h
#define Q_DECLARE_PRIVATE(Class) \
inline Class##Private* d_func() { return reinterpret_cast<Class##Private *>(qGetPtrHelper(d_ptr)); } \
inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(qGetPtrHelper(d_ptr)); } \
friend class Class##Private;