Qt qApp宏

一 QApplication
  1. 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.

  1. 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
  1. 在基于QtWidgets的Qt GUI应用程序代码中,若需要使用QApplication对象,可直接调用qApp宏。
  2. qApp宏定义
// 源码 QtWidgets/qapplication.h
#define qApp (static_cast<QApplication *>(QCoreApplication::instance()))
  1. 细究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;
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值