QCoreApplication 类

QCoreApplication class provides an event loop for Qt applications without UI. 更多...

Header: #include <QCoreApplication>
qmake: QT += core
继承: QObject

特性

公共函数

QCoreApplication (int & argc , char ** argv )
virtual ~QCoreApplication ()
void installNativeEventFilter (QAbstractNativeEventFilter * filterObj )
virtual bool notify (QObject * receiver , QEvent * event )
void removeNativeEventFilter (QAbstractNativeEventFilter * filterObject )

公共槽

void quit ()

信号

静态公共成员

void addLibraryPath (const QString & path )
QString applicationDirPath ()
QString applicationFilePath ()
QString applicationName ()
qint64 applicationPid ()
QString applicationVersion ()
QStringList arguments ()
bool closingDown ()
QAbstractEventDispatcher * eventDispatcher ()
int exec ()
void exit (int returnCode = 0)
bool installTranslator (QTranslator * translationFile )
QCoreApplication * instance ()
bool isQuitLockEnabled ()
bool isSetuidAllowed ()
QStringList libraryPaths ()
QString organizationDomain ()
QString organizationName ()
void postEvent (QObject * receiver , QEvent * event , int priority = Qt::NormalEventPriority)
void processEvents (QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents)
void processEvents (QEventLoop::ProcessEventsFlags flags , int maxtime )
void removeLibraryPath (const QString & path )
void removePostedEvents (QObject * receiver , int eventType = 0)
bool removeTranslator (QTranslator * translationFile )
bool sendEvent (QObject * receiver , QEvent * event )
void sendPostedEvents (QObject * receiver = nullptr, int event_type = 0)
void setApplicationName (const QString & application )
void setApplicationVersion (const QString & version )
void setAttribute (Qt::ApplicationAttribute attribute , bool on = true)
void setEventDispatcher (QAbstractEventDispatcher * eventDispatcher )
void setLibraryPaths (const QStringList & paths )
void setOrganizationDomain (const QString & orgDomain )
void setOrganizationName (const QString & orgName )
void setQuitLockEnabled (bool enabled )
void setSetuidAllowed (bool allow )
bool startingUp ()
const QMetaObject staticMetaObject
bool testAttribute (Qt::ApplicationAttribute attribute )
QString translate (const char * context , const char * sourceText , const char * disambiguation = nullptr, int n = -1)
  • 10 static public members inherited from QObject

重实现保护函数

virtual bool event (QEvent * e ) override
void qAddPostRoutine (QtCleanUpFunction ptr )
void qRemovePostRoutine (QtCleanUpFunction ptr )

Q_COREAPP_STARTUP_FUNCTION (QtStartUpFunction ptr )
Q_DECLARE_TR_FUNCTIONS ( context )

详细描述

QCoreApplication class provides an event loop for Qt applications without UI.

This class is used by non-GUI applications to provide their event loop. For non-GUI application that uses Qt, there should be exactly one QCoreApplication object. For GUI applications, see QGuiApplication . For applications that use the Qt Widgets module, see QApplication .

QCoreApplication contains the main event loop, where all events from the operating system (e.g., timer and network events) and other sources are processed and dispatched. It also handles the application's initialization and finalization, as well as system-wide and application-wide settings.

事件循环和事件处理

开始事件循环通过调用 exec ()。长时间运行的操作可以调用 processEvents () 以保持应用程序的响应速度。

In general, we recommend that you create a QCoreApplication , QGuiApplication QApplication 对象在您的 main() function as early as possible. exec () will not return until the event loop exits; e.g., when quit () 被调用。

Several static convenience functions are also provided. The QCoreApplication object is available from instance (). Events can be sent with sendEvent () or posted to an event queue with postEvent (). Pending events can be removed with removePostedEvents () or dispatched with sendPostedEvents ().

类提供 quit () 槽和 aboutToQuit () 信号。

应用程序和库路径

应用程序有 applicationDirPath () and an applicationFilePath ()。库路径 (见 QLibrary ) 可以被检索采用 libraryPaths () 和操纵通过 setLibraryPaths (), addLibraryPath (),和 removeLibraryPath ().

国际化和翻译

可以添加或移除翻译文件使用 installTranslator () 和 removeTranslator ()。可以翻译应用程序字符串使用 translate ()。 QObject::tr () and QObject::trUtf8() functions are implemented in terms of translate ().

访问命令行自变量

The command line arguments which are passed to QCoreApplication 's constructor should be accessed using the arguments () 函数。

注意: QCoreApplication removes option -qmljsdebugger="..." . It parses the argument of qmljsdebugger , and then removes this option plus its argument.

For more advanced command line option handling, create a QCommandLineParser .

区域设置

On Unix/Linux Qt is configured to use the system locale settings by default. This can cause a conflict when using POSIX functions, for instance, when converting between data types such as floats and strings, since the notation may differ between locales. To get around this problem, call the POSIX function setlocale(LC_NUMERIC,"C") right after initializing QApplication , QGuiApplication or QCoreApplication to reset the locale that is used for number formatting to "C"-locale.

另请参阅 QGuiApplication , QAbstractEventDispatcher , QEventLoop , 信号量范例 ,和 等待条件范例 .

特性文档编制

applicationName : QString

此特性保持该应用程序的名称

The value is used by the QSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time a QSettings object is created.

若未设置,应用程序名称默认为可执行文件名称 (从 5.0 起)。

访问函数:

QString applicationName ()
void setApplicationName (const QString & application )

另请参阅 organizationName , organizationDomain , applicationVersion ,和 applicationFilePath ().

applicationVersion : QString

此特性保持该应用程序的版本

If not set, the application version defaults to a platform-specific value determined from the main application executable or package (since Qt 5.9):

平台 Source
Windows (经典桌面) PRODUCTVERSION parameter of the VERSIONINFO resource
通用 Windows 平台 version attribute of the application package manifest
macOS , iOS, tvOS, watchOS CFBundleVersion property of the information property list
Android android:versionName property of the AndroidManifest.xml manifest element

在其它平台,默认为空字符串。

This property was introduced in Qt 4.4.

访问函数:

QString applicationVersion ()
void setApplicationVersion (const QString & version )

另请参阅 applicationName , organizationName ,和 organizationDomain .

organizationDomain : QString

This property holds the Internet domain of the organization that wrote this application

The value is used by the QSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time a QSettings object is created.

在 Mac, QSettings uses organizationDomain() as the organization if it's not an empty string; otherwise it uses organizationName (). On all other platforms, QSettings 使用 organizationName () as the organization.

访问函数:

QString organizationDomain ()
void setOrganizationDomain (const QString & orgDomain )

另请参阅 organizationName , applicationName ,和 applicationVersion .

organizationName : QString

此特性保持编写此应用程序的组织名称

The value is used by the QSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time a QSettings object is created.

在 Mac, QSettings 使用 organizationDomain() as the organization if it's not an empty string; otherwise it uses organizationName(). On all other platforms, QSettings uses organizationName() as the organization.

访问函数:

QString organizationName ()
void setOrganizationName (const QString & orgName )

另请参阅 organizationDomain and applicationName .

quitLockEnabled : bool

This property holds whether the use of the QEventLoopLocker feature can cause the application to quit.

默认为 true .

访问函数:

bool isQuitLockEnabled ()
void setQuitLockEnabled (bool enabled )

另请参阅 QEventLoopLocker .

成员函数文档编制

QCoreApplication:: QCoreApplication ( int & argc , char ** argv )

Constructs a Qt core application. Core applications are applications without a graphical user interface. Such applications are used at the console or as server processes.

argc and argv arguments are processed by the application, and made available in a more convenient form by the arguments () 函数。

警告: The data referred to by argc and argv must stay valid for the entire lifetime of the QCoreApplication object. In addition, argc must be greater than zero and argv must contain at least one valid character string.

[virtual] QCoreApplication:: ~QCoreApplication ()

销毁 QCoreApplication 对象。

[signal] void QCoreApplication:: aboutToQuit ()

This signal is emitted when the application is about to quit the main event loop, e.g. when the event loop level drops to zero. This may happen either after a call to quit () from inside the application or when the user shuts down the entire desktop session.

The signal is particularly useful if your application has to do some last-second cleanup. Note that no user interaction is possible in this state.

注意: 这是私有信号。它可以用于信号连接,但不能由用户发射。

另请参阅 quit ().

[static] void QCoreApplication:: addLibraryPath (const QString & path )

前置 path to the beginning of the library path list, ensuring that it is searched for libraries first. If path is empty or already in the path list, the path list is not changed.

The default path list consists of a single entry, the installation directory for plugins. The default installation directory for plugins is INSTALL/plugins , where INSTALL is the directory where Qt was installed.

The library paths are reset to the default when an instance of QCoreApplication is destructed.

另请参阅 removeLibraryPath (), libraryPaths (),和 setLibraryPaths ().

[static] QString QCoreApplication:: applicationDirPath ()

返回包含应用程序可执行文件的目录。

例如,若有安装 Qt 在 C:\Qt directory, and you run the regexp example, this function will return "C:/Qt/examples/tools/regexp".

On macOS and iOS this will point to the directory actually containing the executable, which may be inside an application bundle (if the application is bundled).

警告: On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.

另请参阅 applicationFilePath ().

[static] QString QCoreApplication:: applicationFilePath ()

Returns the file path of the application executable.

例如,若有安装 Qt 在 /usr/local/qt directory, and you run the regexp example, this function will return "/usr/local/qt/examples/tools/regexp/regexp".

警告: On Linux, this function will try to get the path from the /proc file system. If that fails, it assumes that argv[0] contains the absolute file name of the executable. The function also assumes that the current directory has not been changed by the application.

另请参阅 applicationDirPath ().

[static] qint64 QCoreApplication:: applicationPid ()

返回应用程序的当前进程 ID。

This function was introduced in Qt 4.4.

[static] QStringList QCoreApplication:: arguments ()

返回命令行自变量列表。

Usually arguments().at(0) is the program name, arguments().at(1) is the first argument, and arguments().last() is the last argument. See the note below about Windows.

Calling this function is slow - you should store the result in a variable when parsing the command line.

警告: On Unix, this list is built from the argc and argv parameters passed to the constructor in the main() function. The string-data in argv is interpreted using QString::fromLocal8Bit (); hence it is not possible to pass, for example, Japanese command line arguments on a system that runs in a Latin1 locale. Most modern Unix systems do not have this limitation, as they are Unicode-based.

On Windows, the list is built from the argc and argv parameters only if modified argv/argc parameters are passed to the constructor. In that case, encoding problems might occur.

Otherwise, the arguments() are constructed from the return value of GetCommandLine() . As a result of this, the string given by arguments().at(0) might not be the program name on Windows, depending on how the application was started.

This function was introduced in Qt 4.1.

另请参阅 applicationFilePath () 和 QCommandLineParser .

[static] bool QCoreApplication:: closingDown ()

返回 true 若应用程序对象正在被销毁;否则返回 false .

另请参阅 startingUp ().

[override virtual protected] bool QCoreApplication:: event ( QEvent * e )

Reimplemented from QObject::event ().

[static] QAbstractEventDispatcher *QCoreApplication:: eventDispatcher ()

Returns a pointer to the event dispatcher object for the main thread. If no event dispatcher exists for the thread, this function returns nullptr .

另请参阅 setEventDispatcher ().

[static] int QCoreApplication:: exec ()

进入主事件循环并等待,直到 exit () 被调用。返回值被传递给 exit () (其为 0 若 exit () 被调用凭借 quit ()).

有必要调用此函数以启动事件处理。主事件循环从窗口系统接收事件,并将其分派给应用程序 Widget。

要使应用程序履行空闲处理 (通过执行特殊函数,当没有待决事件时),使用 QTimer 采用 0 超时。更高级空闲处理方案可以被达成,使用 processEvents ().

推荐把清理代码连接到 aboutToQuit() 信号,而非将其放入应用程序的 main() 函数,因为在某些平台,exec() 调用可能不返回。例如在 Windows,当用户注销时,系统在 Qt 关闭所有顶层窗口后终止过程。因此,不保证应用程序会有时间退出其事件循环并执行代码结束 main() 函数在 exec() 调用之后。

另请参阅 quit (), exit (), processEvents (),和 QApplication::exec ().

[static] void QCoreApplication:: exit ( int returnCode = 0)

告诉应用程序采用返回代码去退出。

After this function has been called, the application leaves the main event loop and returns from the call to exec ()。 exec () 函数返回 returnCode . If the event loop is not running, this function does nothing.

按约定, returnCode 0 意味着成功,而任何非零值指示出错。

It's good practice to always connect signals to this slot using a QueuedConnection . If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec() ), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

注意:不像同名 C 库函数,此函数 does 返回给调用者 -- 它停止事件处理。

另请参阅 quit () 和 exec ().

void QCoreApplication:: installNativeEventFilter ( QAbstractNativeEventFilter * filterObj )

安装事件过滤器 filterObj 为所有本机接收事件,通过主线程中的应用程序。

事件过滤器 filterObj 接收事件凭借其 nativeEventFilter() function, which is called for all native events received in the main thread.

QAbstractNativeEventFilter::nativeEventFilter () function should return true if the event should be filtered, i.e. stopped. It should return false to allow normal Qt processing to continue: the native event can then be translated into a QEvent and handled by the standard Qt event filtering, e.g. QObject::installEventFilter ().

If multiple event filters are installed, the filter that was installed last is activated first.

注意: The filter function set here receives native messages, i.e. MSG or XCB event structs.

注意: Native event filters will be disabled in the application when the Qt::AA_PluginApplication attribute is set.

For maximum portability, you should always try to use QEvent and QObject::installEventFilter () 每当可能时。

This function was introduced in Qt 5.0.

另请参阅 QObject::installEventFilter ().

[static] bool QCoreApplication:: installTranslator ( QTranslator * translationFile )

添加翻译文件 translationFile 到用于翻译的翻译文件列表。

Multiple translation files can be installed. Translations are searched for in the reverse order in which they were installed, so the most recently installed translation file is searched first and the first translation file installed is searched last. The search stops as soon as a translation containing a matching string is found.

Installing or removing a QTranslator , or changing an installed QTranslator generates a LanguageChange event for the QCoreApplication instance. A QApplication instance will propagate the event to all toplevel widgets, where a reimplementation of changeEvent can re-translate the user interface by passing user-visible strings via the tr () function to the respective property setters. User-interface classes generated by Qt Designer provide a retranslateUi() function that can be called.

函数返回 true 当成功时和 false 当失败时。

另请参阅 removeTranslator (), translate (), QTranslator::load (),和 动态翻译 .

[static] QCoreApplication *QCoreApplication:: instance ()

返回指针指向应用程序的 QCoreApplication (or QGuiApplication / QApplication ) instance.

若没有分配实例, null 被返回。

[static] bool QCoreApplication:: isSetuidAllowed ()

Returns true if the application is allowed to run setuid on UNIX platforms.

This function was introduced in Qt 5.3.

另请参阅 QCoreApplication::setSetuidAllowed ().

[static] QStringList QCoreApplication:: libraryPaths ()

Returns a list of paths that the application will search when dynamically loading libraries.

The return value of this function may change when a QCoreApplication is created. It is not recommended to call it before creating a QCoreApplication . The directory of the application executable ( not the working directory) is part of the list if it is known. In order to make it known a QCoreApplication has to be constructed as it will use argv[0] to find it.

Qt provides default library paths, but they can also be set using a qt.conf file. Paths specified in this file will override default values. Note that if the qt.conf file is in the directory of the application executable, it may not be found until a QCoreApplication is created. If it is not found when calling this function, the default library paths will be used.

The list will include the installation directory for plugins if it exists (the default installation directory for plugins is INSTALL/plugins , where INSTALL is the directory where Qt was installed). The colon separated entries of the QT_PLUGIN_PATH environment variable are always added. The plugin installation directory (and its existence) may change when the directory of the application executable becomes known.

若希望遍历列表,可以使用 foreach 伪关键字:

foreach (const QString &path, app.libraryPaths())
    do_something(path);
							

另请参阅 setLibraryPaths (), addLibraryPath (), removeLibraryPath (), QLibrary ,和 如何创建 Qt 插件 .

[virtual] bool QCoreApplication:: notify ( QObject * receiver , QEvent * event )

发送 event to receiver : receiver ->event( event )。返回来自接收者的事件处理程序返回的值。注意:此函数被调用,对于被发送给在任何线程中的任何对象的所有事件。

对于某些类型的事件 (如鼠标事件和按键事件),事件会被传播给接收者的父级,依此类推直至顶层对象,若接收者对事件不感兴趣 (即:它返回 false ).

有 5 种不同办法可以处理事件。重新实现此虚函数只是它们之一。以下列出了所有 5 种途径:

  1. 重实现 paintEvent() , mousePressEvent() and so on. This is the most common, easiest, and least powerful way.
  2. Reimplementing this function. This is very powerful, providing complete control; but only one subclass can be active at a time.
  3. Installing an event filter on QCoreApplication::instance (). Such an event filter is able to process all events for all widgets, so it's just as powerful as reimplementing notify(); furthermore, it's possible to have more than one application-global event filter. Global event filters even see mouse events for disabled widgets . Note that application event filters are only called for objects that live in the main thread.
  4. 重实现 QObject::event () (as QWidget does). If you do this you get Tab key presses, and you get to see the events before any widget-specific event filters.
  5. Installing an event filter on the object. Such an event filter gets all the events, including Tab and Shift+Tab key press events, as long as they do not change the focus widget.

未来方向: This function will not be called for objects that live outside the main thread in Qt 6. Applications that need that functionality should find other solutions for their event inspection needs in the meantime. The change may be extended to the main thread, causing this function to be deprecated.

警告: If you override this function, you must ensure all threads that process events stop doing so before your application object begins destruction. This includes threads started by other libraries that you may be using, but does not apply to Qt's own threads.

另请参阅 QObject::event () 和 installNativeEventFilter ().

[static] void QCoreApplication:: postEvent ( QObject * receiver , QEvent * event , int priority = Qt::NormalEventPriority)

添加事件 event ,采用对象 receiver 作为事件接收者,到事件队列并立即返回。

事件必须在堆上被分配,因为 Post 事件队列将获取事件的所有权,且事件一旦已被张贴就会被删除。它是 not safe 去访问事件,其它已被张贴之后。

When control returns to the main event loop, all events that are stored in the queue will be sent using the notify () 函数。

Events are sorted in descending priority order, i.e. events with a high priority are queued before events with a lower priority priority can be any integer value, i.e. between INT_MAX and INT_MIN, inclusive; see Qt::EventPriority for more details. Events with equal priority will be processed in the order posted.

注意: 此函数是 thread-safe .

This function was introduced in Qt 4.3.

另请参阅 sendEvent (), notify (), sendPostedEvents (),和 Qt::EventPriority .

[static] void QCoreApplication:: processEvents ( QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents)

处理所有调用线程待决事件,根据指定 flags 直到没有更多要处理事件为止。

可以偶尔调用此函数,当程序忙于履行长时间的操作 (如:拷贝文件) 时。

在正在运行连续调用此函数的本地循环事件中,若没有事件循环, DeferredDelete 事件不会被处理。这会影响 Widget 的行为,如 QToolTip 依赖 DeferredDelete 事件才能正确运行。替代是调用 sendPostedEvents() 从本地循环中。

调用此函数仅处理调用线程的事件。

注意: 此函数是 thread-safe .

另请参阅 exec (), QTimer , QEventLoop::processEvents (), flush (),和 sendPostedEvents ().

[static] void QCoreApplication:: processEvents ( QEventLoop::ProcessEventsFlags flags , int maxtime )

This function overloads processEvents ().

Processes pending events for the calling thread for maxtime milliseconds or until there are no more events to process, whichever is shorter.

You can call this function occasionally when your program is busy doing a long operation (e.g. copying a file).

调用此函数仅处理调用线程的事件。

注意: 此函数是 thread-safe .

另请参阅 exec (), QTimer ,和 QEventLoop::processEvents ().

[static slot] void QCoreApplication:: quit ()

Tells the application to exit with return code 0 (success). Equivalent to calling QCoreApplication::exit (0).

It's common to connect the QGuiApplication::lastWindowClosed () signal to quit(), and you also often connect e.g. QAbstractButton::clicked () or signals in QAction , QMenu ,或 QMenuBar to it.

It's good practice to always connect signals to this slot using a QueuedConnection . If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec() ), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

范例:

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, SIGNAL(clicked()), &app, SLOT(quit()), Qt::QueuedConnection);
							

另请参阅 exit (), aboutToQuit (),和 QGuiApplication::lastWindowClosed ().

[static] void QCoreApplication:: removeLibraryPath (const QString & path )

移除 path 从库路径列表。若 path is empty or not in the path list, the list is not changed.

The library paths are reset to the default when an instance of QCoreApplication is destructed.

另请参阅 addLibraryPath (), libraryPaths (),和 setLibraryPaths ().

void QCoreApplication:: removeNativeEventFilter ( QAbstractNativeEventFilter * filterObject )

移除事件 filterObject from this object. The request is ignored if such an event filter has not been installed.

All event filters for this object are automatically removed when this object is destroyed.

It is always safe to remove an event filter, even during event filter activation (i.e. from the nativeEventFilter() function).

This function was introduced in Qt 5.0.

另请参阅 installNativeEventFilter ().

[static] void QCoreApplication:: removePostedEvents ( QObject * receiver , int eventType = 0)

Removes all events of the given eventType that were posted using postEvent () for receiver .

The events are not dispatched, instead they are removed from the queue. You should never need to call this function. If you do call it, be aware that killing events may cause receiver to break one or more invariants.

receiver is null, the events of eventType are removed for all objects. If eventType is 0, all the events are removed for receiver . You should never call this function with eventType of 0.

注意: 此函数是 thread-safe .

This function was introduced in Qt 4.3.

[static] bool QCoreApplication:: removeTranslator ( QTranslator * translationFile )

移除翻译文件 translationFile from the list of translation files used by this application. (It does not delete the translation file from the file system.)

函数返回 true 当成功时和 false 当失败时。

另请参阅 installTranslator (), translate (),和 QObject::tr ().

[static] bool QCoreApplication:: sendEvent ( QObject * receiver , QEvent * event )

发送事件 event 直接到接收者 receiver ,使用 notify () 函数。返回从事件处理程序返回的值。

事件 not 被删除,当事件被发送后。正常途径是在堆栈上创建事件,例如:

QMouseEvent event(QEvent::MouseButtonPress, pos, 0, 0, 0);
QApplication::sendEvent(mainWindow, &event);
							

另请参阅 postEvent () 和 notify ().

[static] void QCoreApplication:: sendPostedEvents ( QObject * receiver = nullptr, int event_type = 0)

立即分派之前队列的所有事件采用 QCoreApplication::postEvent () 和为对象 receiver 和事件类型 event_type .

来自窗口系统的事件 not 通过此函数分派,而是通过 processEvents ().

receiver is null, the events of event_type are sent for all objects. If event_type 为 0,所有事件被发送给 receiver .

注意: This method must be called from the thread in which its QObject 参数, receiver , lives.

另请参阅 flush () 和 postEvent ().

[static] void QCoreApplication:: setAttribute ( Qt::ApplicationAttribute attribute , bool on = true)

设置属性 attribute if on 为 true;否则清零属性。

注意: 某些应用程序属性必须被设置 before 创建 QCoreApplication 实例。参考 Qt::ApplicationAttribute 文档编制,了解更多信息。

另请参阅 testAttribute ().

[static] void QCoreApplication:: setEventDispatcher ( QAbstractEventDispatcher * eventDispatcher )

Sets the event dispatcher for the main thread to eventDispatcher . This is only possible as long as there is no event dispatcher installed yet. That is, before QCoreApplication 已被实例化。此方法获取对象的所有权。

另请参阅 eventDispatcher ().

[static] void QCoreApplication:: setLibraryPaths (const QStringList & paths )

Sets the list of directories to search when loading libraries to paths . All existing paths will be deleted and the path list will consist of the paths given in paths .

The library paths are reset to the default when an instance of QCoreApplication is destructed.

另请参阅 libraryPaths (), addLibraryPath (), removeLibraryPath (),和 QLibrary .

[static] void QCoreApplication:: setSetuidAllowed ( bool allow )

允许应用程序在 UNIX 平台运行 setuid 若 allow 为 true。

allow is false (the default) and Qt detects the application is running with an effective user id different than the real user id, the application will be aborted when a QCoreApplication instance is created.

Qt is not an appropriate solution for setuid programs due to its large attack surface. However some applications may be required to run in this manner for historical reasons. This flag will prevent Qt from aborting the application when this is detected, and must be set before a QCoreApplication instance is created.

注意: It is strongly recommended not to enable this option since it introduces security risks.

This function was introduced in Qt 5.3.

另请参阅 isSetuidAllowed ().

[static] bool QCoreApplication:: startingUp ()

返回 true 若应用程序对象尚未被创建;否则返回 false .

另请参阅 closingDown ().

[static] bool QCoreApplication:: testAttribute ( Qt::ApplicationAttribute attribute )

返回 true 若属性 attribute 已设置;否则返回 false .

另请参阅 setAttribute ().

[static] QString QCoreApplication:: translate (const char * context , const char * sourceText , const char * disambiguation = nullptr, int n = -1)

Returns the translation text for sourceText , by querying the installed translation files. The translation files are searched from the most recently installed file back to the first installed file.

QObject::tr () provides this functionality more conveniently.

context is typically a class name (e.g., "MyDialog") and sourceText is either English text or a short identifying text.

disambiguation is an identifying string, for when the same sourceText is used in different roles within the same context. By default, it is null.

QTranslator and QObject::tr () documentation for more information about contexts, disambiguations and comments.

n is used in conjunction with %n to support plural forms. See QObject::tr () 了解细节。

If none of the translation files contain a translation for sourceText in context , this function returns a QString equivalent of sourceText .

This function is not virtual. You can use alternative translation techniques by subclassing QTranslator .

注意: 此函数是 thread-safe .

另请参阅 QObject::tr (), installTranslator (), removeTranslator (),及 translate()。

相关非成员

void qAddPostRoutine ( QtCleanUpFunction ptr )

Adds a global routine that will be called from the QCoreApplication destructor. This function is normally used to add cleanup routines for program-wide functionality.

The cleanup routines are called in the reverse order of their addition.

The function specified by ptr should take no arguments and should return nothing. For example:

static int *global_ptr = 0;
static void cleanup_ptr()
{
    delete [] global_ptr;
    global_ptr = 0;
}
void init_ptr()
{
    global_ptr = new int[100];      // allocate data
    qAddPostRoutine(cleanup_ptr);   // delete later
}
							

Note that for an application- or module-wide cleanup, qAddPostRoutine() is often not suitable. For example, if the program is split into dynamically loaded modules, the relevant module may be unloaded long before the QCoreApplication destructor is called. In such cases, if using qAddPostRoutine() is still desirable, qRemovePostRoutine () can be used to prevent a routine from being called by the QCoreApplication destructor. For example, if that routine was called before the module was unloaded.

For modules and libraries, using a reference-counted initialization manager or Qt's parent-child deletion mechanism may be better. Here is an example of a private class that uses the parent-child mechanism to call a cleanup function at the right time:

class MyPrivateInitStuff : public QObject
{
public:
    static MyPrivateInitStuff *initStuff(QObject *parent)
    {
        if (!p)
            p = new MyPrivateInitStuff(parent);
        return p;
    }
    ~MyPrivateInitStuff()
    {
        // cleanup goes here
    }
private:
    MyPrivateInitStuff(QObject *parent)
        : QObject(parent)
    {
        // initialization goes here
    }
    MyPrivateInitStuff *p;
};
							

By selecting the right parent object, this can often be made to clean up the module's data at the right moment.

注意: 该函数自 Qt 5.10 起是 Thread-Safety (线程安全) 的。

注意: 此函数是 thread-safe .

另请参阅 qRemovePostRoutine ().

void qRemovePostRoutine ( QtCleanUpFunction ptr )

Removes the cleanup routine specified by ptr from the list of routines called by the QCoreApplication destructor. The routine must have been previously added to the list by a call to qAddPostRoutine (), otherwise this function has no effect.

注意: 该函数自 Qt 5.10 起是 Thread-Safety (线程安全) 的。

注意: 此函数是 thread-safe .

This function was introduced in Qt 5.3.

另请参阅 qAddPostRoutine ().

宏文档编制

Q_COREAPP_STARTUP_FUNCTION ( QtStartUpFunction ptr )

Adds a global function that will be called from the QCoreApplication constructor. This macro is normally used to initialize libraries for program-wide functionality, without requiring the application to call into the library for initialization.

The function specified by ptr should take no arguments and should return nothing. For example:

// Called once QCoreApplication exists
static void preRoutineMyDebugTool()
{
    MyDebugTool* tool = new MyDebugTool(QCoreApplication::instance());
    QCoreApplication::instance()->installEventFilter(tool);
}
Q_COREAPP_STARTUP_FUNCTION(preRoutineMyDebugTool)
							

Note that the startup function will run at the end of the QCoreApplication constructor, before any GUI initialization. If GUI code is required in the function, use a timer (or a queued invocation) to perform the initialization later on, from the event loop.

QCoreApplication is deleted and another QCoreApplication is created, the startup function will be invoked again.

注意: This macro is not suitable for use in library code that is then statically linked into an application since the function may not be called at all due to being eliminated by the linker.

注意: 此函数是 可重入 .

This function was introduced in Qt 5.1.

Q_DECLARE_TR_FUNCTIONS ( context )

The Q_DECLARE_TR_FUNCTIONS() macro declares and implements two translation functions, tr() and trUtf8() , with these signatures:

static inline QString tr(const char *sourceText,
                         const char *comment = 0);
static inline QString trUtf8(const char *sourceText,
                             const char *comment = 0);
							

此宏很有用,若希望使用 QObject::tr () or QObject::trUtf8() in classes that don't inherit from QObject .

Q_DECLARE_TR_FUNCTIONS() must appear at the very top of the class definition (before the first public: or protected: )。例如:

class MyMfcView : public CView
{
    Q_DECLARE_TR_FUNCTIONS(MyMfcView)
public:
    MyMfcView();
    ...
};
							

context parameter is normally the class name, but it can be any text.

另请参阅 Q_OBJECT , QObject::tr (),和 QObject::trUtf8 ().