Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QCoreApplication Class Reference

\inmodule QtCore More...

#include <qcoreapplication.h>

+ Inheritance diagram for QCoreApplication:
+ Collaboration diagram for QCoreApplication:

Public Types

enum  { ApplicationFlags = QT_VERSION }
 

Public Slots

static void quit ()
 \threadsafe
 
static void exit (int retcode=0)
 Tells the application to exit with a return code.
 
- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 

Signals

void aboutToQuit (QPrivateSignal)
 This signal is emitted when the application is about to quit the main event loop, e.g.
 
void organizationNameChanged ()
 
void organizationDomainChanged ()
 
void applicationNameChanged ()
 
void applicationVersionChanged ()
 
- Signals inherited from QObject
void destroyed (QObject *=nullptr)
 This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.
 
void objectNameChanged (const QString &objectName, QPrivateSignal)
 This signal is emitted after the object's name has been changed.
 

Public Member Functions

 QCoreApplication (int &argc, char **argv, int=ApplicationFlags)
 Constructs a Qt core application.
 
 ~QCoreApplication ()
 Destroys the QCoreApplication object.
 
virtual bool notify (QObject *, QEvent *)
 Sends event to receiver: {receiver}->event(event).
 
void installNativeEventFilter (QAbstractNativeEventFilter *filterObj)
 Installs an event filter filterObj for all native events received by the application in the main thread.
 
void removeNativeEventFilter (QAbstractNativeEventFilter *filterObj)
 Removes an event filterObject from this object.
 
- Public Member Functions inherited from QObject
Q_INVOKABLE QObject (QObject *parent=nullptr)
 Constructs an object with parent object parent.
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects.
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 Filters events if this object has been installed as an event filter for the watched object.
 
QString objectName () const
 
Q_WEAK_OVERLOAD void setObjectName (const QString &name)
 Sets the object's name to name.
 
void setObjectName (QAnyStringView name)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QBindable< QStringbindableObjectName ()
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false.
 
bool isWindowType () const
 Returns true if the object is a window; otherwise returns false.
 
bool isQuickItemType () const
 Returns true if the object is a QQuickItem; otherwise returns false.
 
bool signalsBlocked () const noexcept
 Returns true if signals are blocked; otherwise returns false.
 
bool blockSignals (bool b) noexcept
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it).
 
QThreadthread () const
 Returns the thread in which the object lives.
 
bool moveToThread (QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL)
 Changes the thread affinity for this object and its children and returns true on success.
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds.
 
int startTimer (std::chrono::nanoseconds time, Qt::TimerType timerType=Qt::CoarseTimer)
 
void killTimer (int id)
 Kills the timer with timer identifier, id.
 
void killTimer (Qt::TimerId id)
 
template<typename T >
findChild (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object.
 
template<typename T >
QList< T > findChildren (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects.
 
template<typename T >
findChild (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename T >
QList< T > findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
const QObjectListchildren () const
 Returns a list of child objects.
 
void setParent (QObject *parent)
 Makes the object a child of parent.
 
void installEventFilter (QObject *filterObj)
 Installs an event filter filterObj on this object.
 
void removeEventFilter (QObject *obj)
 Removes an event filter object obj from this object.
 
QMetaObject::Connection connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const
 
bool disconnect (const QObject *receiver, const char *member=nullptr) const
 
void dumpObjectTree () const
 Dumps a tree of children to the debug output.
 
void dumpObjectInfo () const
 Dumps information about signal connections, etc.
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value.
 
bool setProperty (const char *name, QVariant &&value)
 
QVariant property (const char *name) const
 Returns the value of the object's name property.
 
QList< QByteArraydynamicPropertyNames () const
 
QBindingStoragebindingStorage ()
 
const QBindingStoragebindingStorage () const
 
QObjectparent () const
 Returns a pointer to the parent object.
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
 

Static Public Member Functions

static QStringList arguments ()
 
static void setAttribute (Qt::ApplicationAttribute attribute, bool on=true)
 Sets the attribute attribute if on is true; otherwise clears the attribute.
 
static bool testAttribute (Qt::ApplicationAttribute attribute)
 Returns true if attribute attribute is set; otherwise returns false.
 
static void setOrganizationDomain (const QString &orgDomain)
 
static QString organizationDomain ()
 
static void setOrganizationName (const QString &orgName)
 [11]
 
static QString organizationName ()
 
static void setApplicationName (const QString &application)
 
static QString applicationName ()
 
static void setApplicationVersion (const QString &version)
 
static QString applicationVersion ()
 
static void setSetuidAllowed (bool allow)
 
static bool isSetuidAllowed ()
 
static QCoreApplicationinstance () noexcept
 Returns a pointer to the application's QCoreApplication (or QGuiApplication/QApplication) instance.
 
static int exec ()
 Enters the main event loop and waits until exit() is called.
 
static void processEvents (QEventLoop::ProcessEventsFlags flags=QEventLoop::AllEvents)
 Processes some pending events for the calling thread according to the specified flags.
 
static void processEvents (QEventLoop::ProcessEventsFlags flags, int maxtime)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Processes pending events for the calling thread for ms milliseconds or until there are no more events to process, whichever is shorter.
 
static void processEvents (QEventLoop::ProcessEventsFlags flags, QDeadlineTimer deadline)
 
static bool sendEvent (QObject *receiver, QEvent *event)
 Sends event event directly to receiver receiver, using the notify() function.
 
static void postEvent (QObject *receiver, QEvent *event, int priority=Qt::NormalEventPriority)
 
static void sendPostedEvents (QObject *receiver=nullptr, int event_type=0)
 Immediately dispatches all events which have been previously queued with QCoreApplication::postEvent() and which are for the object receiver and have the event type event_type.
 
static void removePostedEvents (QObject *receiver, int eventType=0)
 
static QAbstractEventDispatchereventDispatcher ()
 Returns a pointer to the event dispatcher object for the main thread.
 
static void setEventDispatcher (QAbstractEventDispatcher *eventDispatcher)
 Sets the event dispatcher for the main thread to eventDispatcher.
 
static bool startingUp ()
 Returns true if an application object has not been created yet; otherwise returns false.
 
static bool closingDown ()
 Returns true if the application objects are being destroyed; otherwise returns false.
 
static QString applicationDirPath ()
 Returns the directory that contains the application executable.
 
static QString applicationFilePath ()
 Returns the file path of the application executable.
 
static qint64 applicationPid () Q_DECL_CONST_FUNCTION
 
static bool installTranslator (QTranslator *messageFile)
 Adds the translation file translationFile to the list of translation files to be used for translations.
 
static bool removeTranslator (QTranslator *messageFile)
 Removes the translation file translationFile from the list of translation files used by this application.
 
static QString translate (const char *context, const char *key, const char *disambiguation=nullptr, int n=-1)
 \threadsafe
 
static bool isQuitLockEnabled ()
 
static void setQuitLockEnabled (bool enabled)
 
- Static Public Member Functions inherited from QObject
static QMetaObject::Connection connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 \threadsafe
 
static QMetaObject::Connection connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 \threadsafe
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static bool disconnect (const QMetaObject::Connection &)
 Disconnect a connection.
 
template<typename Func1 , typename Func2 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot)
 
template<typename Func1 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero)
 

Protected Member Functions

bool event (QEvent *) override
 \reimp
 
virtual bool compressEvent (QEvent *, QObject *receiver, QPostEventList *)
 
 QCoreApplication (QCoreApplicationPrivate &p)
 
- Protected Member Functions inherited from QObject
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr.
 
int senderSignalIndex () const
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal.
 
bool isSignalConnected (const QMetaMethod &signal) const
 
virtual void timerEvent (QTimerEvent *event)
 This event handler can be reimplemented in a subclass to receive timer events for the object.
 
virtual void childEvent (QChildEvent *event)
 This event handler can be reimplemented in a subclass to receive child events.
 
virtual void customEvent (QEvent *event)
 This event handler can be reimplemented in a subclass to receive custom events.
 
virtual void connectNotify (const QMetaMethod &signal)
 
virtual void disconnectNotify (const QMetaMethod &signal)
 
 QObject (QObjectPrivate &dd, QObject *parent=nullptr)
 

Properties

QString applicationName
 the name of this application
 
QString applicationVersion
 the version of this application
 
QString organizationName
 the name of the organization that wrote this application
 
QString organizationDomain
 the Internet domain of the organization that wrote this application
 
bool quitLockEnabled
 Whether the use of the QEventLoopLocker feature can cause the application to quit.
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Friends

class QEventLoopLocker
 
class QApplication
 
class QApplicationPrivate
 
class QGuiApplication
 
class QGuiApplicationPrivate
 
class QWidget
 
class QWidgetWindow
 
class QWidgetPrivate
 
class QEventDispatcherUNIXPrivate
 
class QCocoaEventDispatcherPrivate
 
class QCommandLineParserPrivate
 
bool qt_sendSpontaneousEvent (QObject *, QEvent *)
 
Q_CORE_EXPORT QString qAppName ()
 

Related Symbols

(Note that these are not member symbols.)

void qAddPostRoutine (QtCleanUpFunction ptr)
 \macro Q_COREAPP_STARTUP_FUNCTION(QtStartUpFunction ptr)
 
void qRemovePostRoutine (QtCleanUpFunction ptr)
 \threadsafe
 
voidresolveInterface (const char *name, int revision) const
 \macro Q_DECLARE_TR_FUNCTIONS(context)
 

Additional Inherited Members

- Protected Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 

Detailed Description

\inmodule QtCore

The 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.

Definition at line 44 of file qcoreapplication.h.

Member Enumeration Documentation

◆ anonymous enum

anonymous enum
Enumerator
ApplicationFlags 

Definition at line 69 of file qcoreapplication.h.

Constructor & Destructor Documentation

◆ QCoreApplication() [1/2]

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

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.

The argc and argv arguments are processed by the application, and made available in a more convenient form by the arguments() function.

Warning
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.

Definition at line 809 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::eventDispatcher.

◆ ~QCoreApplication()

QCoreApplication::~QCoreApplication ( )

Destroys the QCoreApplication object.

Definition at line 944 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::eventDispatcher, QThreadPool::globalInstance(), QCoreApplicationPrivate::is_app_closing, QCoreApplicationPrivate::is_app_running, preRoutinesCalled, qt_call_post_routines(), QT_CATCH, QT_TRY, and QThreadPoolPrivate::qtGuiInstance().

+ Here is the call graph for this function:

◆ QCoreApplication() [2/2]

QCoreApplication::QCoreApplication ( QCoreApplicationPrivate & p)
protected

Definition at line 783 of file qcoreapplication.cpp.

Member Function Documentation

◆ aboutToQuit

void QCoreApplication::aboutToQuit ( QPrivateSignal )
signal

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.

Note
At this point the main event loop is still running, but will not process further events on return except QEvent::DeferredDelete events for objects deleted via deleteLater(). If event processing is needed, use a nested event loop or call QCoreApplication::processEvents() manually.
See also
quit()

Referenced by QSingleShotTimer::startTimerForReceiver().

+ Here is the caller graph for this function:

◆ applicationDirPath()

QString QCoreApplication::applicationDirPath ( )
static

Returns the directory that contains the application executable.

For example, if you have installed Qt in the {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).

Warning
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.
See also
applicationFilePath()

Definition at line 2450 of file qcoreapplication.cpp.

References applicationFilePath(), d, QFileInfo::path(), and qWarning.

Referenced by QQmlImportDatabase::QQmlImportDatabase(), deployQmlImports(), iconThemeSearchPaths(), main(), prefixFromAppDirHelper(), and QTest::qFindTestData().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ applicationFilePath()

QString QCoreApplication::applicationFilePath ( )
static

Returns the file path of the application executable.

For example, if you have installed Qt in the {/usr/local/qt} directory, and you run the {regexp} example, this function will return "/usr/local/qt/examples/tools/regexp/regexp".

Warning
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.
See also
applicationDirPath()

Definition at line 2502 of file qcoreapplication.cpp.

References arguments(), at, QCoreApplicationPrivate::cachedApplicationFilePath, QFileInfo::canonicalFilePath(), QCoreApplicationPrivate::clearApplicationFilePath(), QDir::current(), d, QFile::decodeName(), QStandardPaths::findExecutable(), qAppFileName(), QByteArray(), qWarning, QCoreApplicationPrivate::setApplicationFilePath(), and toLocal8Bit().

Referenced by QHaikuIntegration::QHaikuIntegration(), QCoreApplicationPrivate::appendApplicationPathToLibraryPaths(), applicationDirPath(), sm_performSaveYourself(), and QV4::CompiledData::Unit::verifyHeader().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ applicationName()

static QString QCoreApplication::applicationName ( )
static

◆ applicationNameChanged

void QCoreApplication::applicationNameChanged ( )
signal

Primarily for QML, see organizationNameChanged.

Referenced by Q_TRACE_INSTRUMENT(), and QGuiApplication::setApplicationDisplayName().

+ Here is the caller graph for this function:

◆ applicationPid()

qint64 QCoreApplication::applicationPid ( )
static
Since
4.4

Returns the current process ID for the application.

Definition at line 2561 of file qcoreapplication.cpp.

Referenced by QBluetoothSocketPrivateBluezDBus::connectToServiceHelper(), formatLogMessage(), QLockFilePrivate::lockFileContents(), and QBenchmarkValgrindUtils::outFileBase().

+ Here is the caller graph for this function:

◆ applicationVersion()

static QString QCoreApplication::applicationVersion ( )
static

◆ applicationVersionChanged

void QCoreApplication::applicationVersionChanged ( )
signal

Primarily for QML, see organizationNameChanged.

◆ arguments()

QStringList QCoreApplication::arguments ( )
static
Since
4.1

Returns the list of command-line 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.

Warning
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 \l{https://docs.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getcommandlinea}{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.

See also
applicationFilePath(), QCommandLineParser

Definition at line 2603 of file qcoreapplication.cpp.

References contains(), d, QString::fromLocal8Bit(), QString::fromWCharArray(), i, list, qWarning, and QList< T >::reserve().

Referenced by applicationFilePath(), QQmlApplication::args(), argv0BaseName(), contextFactory(), QCommandLineParserPrivate::helpText(), QDirectFbIntegration::initializeDirectFB(), main(), main(), QSSGLayerRenderData::maybeBakeLightmap(), parseOptions(), parseOptions(), printHelp(), QCommandLineParser::process(), QTest::qRun(), QDBusXmlToCpp::run(), runMoc(), and sm_performSaveYourself().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ closingDown()

◆ compressEvent()

bool QCoreApplication::compressEvent ( QEvent * event,
QObject * receiver,
QPostEventList * postedEvents )
protectedvirtual

Returns true if event was compressed away (possibly deleted) and should not be added to the list.

Reimplemented in QGuiApplication, and QApplication.

Definition at line 1723 of file qcoreapplication.cpp.

References QList< T >::cbegin(), QList< T >::cend(), QObject::event(), it, Q_ASSERT, QEvent::Quit, QEvent::Timer, and QTimerEvent::timerId().

Referenced by QGuiApplication::compressEvent().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ event()

bool QCoreApplication::event ( QEvent * e)
overrideprotectedvirtual

\reimp

Reimplemented from QObject.

Reimplemented in QGuiApplication.

Definition at line 2078 of file qcoreapplication.cpp.

References QObject::event(), exit(), QEvent::Quit, and QEvent::type().

Referenced by QGuiApplication::event(), and QApplication::event().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ eventDispatcher()

QAbstractEventDispatcher * QCoreApplication::eventDispatcher ( )
static

Returns a pointer to the event dispatcher object for the main thread.

If no event dispatcher exists for the thread, this function returns \nullptr.

Definition at line 3264 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::theMainThread.

Referenced by QGstPipelinePrivate::QGstPipelinePrivate(), QQnxWindowGrabber::QQnxWindowGrabber(), QQnxWindowGrabber::~QQnxWindowGrabber(), installNativeEventFilter(), removeNativeEventFilter(), setEventDispatcher(), and QXcbEventQueue::wakeUpDispatcher().

+ Here is the caller graph for this function:

◆ exec()

int QCoreApplication::exec ( )
static

Enters the main event loop and waits until exit() is called.

Returns the value that was passed to exit() (which is 0 if exit() is called via quit()).

It is necessary to call this function to start event handling. The main event loop receives events from the window system and dispatches these to the application widgets.

To make your application perform idle processing (by executing a special function whenever there are no pending events), use a QChronoTimer with 0ns timeout. More advanced idle processing schemes can be achieved using processEvents().

We recommend that you connect clean-up code to the \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your application's {main()} function because on some platforms the exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the {main()} function after the exec() call.

See also
quit(), exit(), processEvents(), QApplication::exec()

Definition at line 1480 of file qcoreapplication.cpp.

References QEventLoop::ApplicationExec, QCoreApplicationPrivate::checkInstance(), QThreadData::current(), QThreadData::eventLoops, QEventLoop::exec(), QList< T >::isEmpty(), QThreadData::quitNow, and qWarning.

Referenced by QGuiApplication::exec().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ exit

void QCoreApplication::exit ( int returnCode = 0)
staticslot

Tells the application to exit with a return code.

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

By convention, a returnCode of 0 means success, and any non-zero value indicates an error.

It's good practice to always connect signals to this slot using a \l{Qt::}{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 \l{QCoreApplication::}{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.

Note that unlike the C library function of the same name, this function does return to the caller – it is event processing that stops.

Note also that this function is not thread-safe. It should be called only from the main thread (the thread that the QCoreApplication object is processing events on). To ask the application to exit from another thread, either use QCoreApplication::quit() or instead call this function from the main thread with QMetaMethod::invokeMethod().

See also
quit(), exec()

Definition at line 1554 of file qcoreapplication.cpp.

References d, emit, QEventLoop::exit(), i, and QThreadData::quitNow.

Referenced by event(), and QQmlApplicationEnginePrivate::init().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ installNativeEventFilter()

void QCoreApplication::installNativeEventFilter ( QAbstractNativeEventFilter * filterObj)

Installs an event filter filterObj for all native events received by the application in the main thread.

The event filter filterObj receives events via its \l {QAbstractNativeEventFilter::}{nativeEventFilter()} function, which is called for all native events received in the main thread.

The 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 \l{QEvent} {event} filtering, e.g. QObject::installEventFilter().

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

Note
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() whenever possible.

See also
QObject::installEventFilter()
Since
5.0

Definition at line 3226 of file qcoreapplication.cpp.

References Qt::AA_PluginApplication, eventDispatcher(), QAbstractEventDispatcher::instance(), qWarning, testAttribute(), and QCoreApplicationPrivate::theMainThread.

+ Here is the call graph for this function:

◆ installTranslator()

bool QCoreApplication::installTranslator ( QTranslator * translationFile)
static

Adds the translation file translationFile to the list of translation files to be used for translations.

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 \l{QEvent::LanguageChange}{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 \QD provide a retranslateUi() function that can be called.

The function returns true on success and false on failure.

Note
QCoreApplication does not take ownership of translationFile.
See also
removeTranslator(), translate(), QTranslator::load(), {Writing Source Code for Translation::Prepare for Dynamic Language Changes}{Prepare for Dynamic Language Changes}

Definition at line 2239 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::checkInstance(), d, QEvent::LanguageChange, and sendEvent().

Referenced by QQmlApplicationEnginePrivate::_q_loadTranslations(), QQmlApplicationEnginePrivate::init(), main(), quick_test_main_with_setup(), and ProxyTranslator::setLanguage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ instance()

static QCoreApplication * QCoreApplication::instance ( )
inlinestaticnoexcept

Returns a pointer to the application's QCoreApplication (or QGuiApplication/QApplication) instance.

If no instance has been allocated, \nullptr is returned.

Definition at line 97 of file qcoreapplication.h.

Referenced by QCupsPrinterSupport::QCupsPrinterSupport(), QEventDispatcherGlibPrivate::QEventDispatcherGlibPrivate(), QEventLoop::QEventLoop(), QEventLoopLocker::QEventLoopLocker(), QHostInfoLookupManager::QHostInfoLookupManager(), QMdiArea::QMdiArea(), QQmlApplication::QQmlApplication(), QQmlPreviewHandler::QQmlPreviewHandler(), QQuickApplication::QQuickApplication(), QQuickGraphicsConfigurationPrivate::QQuickGraphicsConfigurationPrivate(), QSocks5BindStore::QSocks5BindStore(), QTlsBackend::QTlsBackend(), QWindowsKeyMapper::QWindowsKeyMapper(), QEvent::~QEvent(), QTranslator::~QTranslator(), QJSEnginePrivate::addToDebugServer(), animationTimerCallback(), QTextHtmlParserNode::applyBackgroundImage(), QTextHtmlParserNode::applyForegroundImage(), checkForApplicationInstance(), QQuickWindowQmlImpl::classBegin(), QTranslatorPrivate::clear(), QXcbWindow::create(), QPaintEngine::createPixmap(), QPaintEngine::createPixmapFromImage(), QWindowSystemInterface::deferredFlushWindowSystemEvents(), QQmlDelegateModelItem::destroyObject(), QQmlApplication::domain(), doUseNativeMenus(), QTextImageHandler::drawObject(), QScrollArea::event(), QEventLoop::exec(), QWindowSystemInterface::flushWindowSystemEvents(), QPixmap::fromImage(), QPixmap::fromImageInPlace(), QPixmap::fromImageReader(), QWindowSystemHelper< Delivery >::handleEvent(), QQmlApplicationEnginePrivate::init(), QWaylandCompositorPrivate::init(), QPrinterPrivate::init(), QSqlDatabasePrivate::init(), QQuickWindowPrivate::init(), QWidgetPrivate::init(), QGuiApplicationPrivate::inputDeviceManager(), QTestEventLoop::instance(), PressDelayHandler::instance(), QTextImageHandler::intrinsicSize(), keywords(), QDnsLookup::lookup(), mainThreadCoInit(), QQmlApplication::name(), QDesktopServices::openUrl(), QQmlApplication::organization(), QSvgIconEngine::pixmap(), QtGlobalStatic::ApplicationHolder< QAS >::pointer(), prefixFromAppDirHelper(), preRoutineMyDebugTool(), QInputDevice::primaryKeyboard(), QPointingDevice::primaryPointingDevice(), QGuiApplicationPrivate::processApplicationTermination(), QEventDispatcherWin32::processEvents(), QGuiApplicationPrivate::processScreenOrientationChange(), qAddPreRoutine(), qDBusInterfaceFromMetaObject(), qt_defaultDpiX(), qt_defaultDpiY(), qt_pixmap_thread_test(), qt_pixmapcache_thread_test(), QGuiApplicationPrivate::qt_qpa_core_dispatcher(), quick_test_main_with_setup(), QTest::qWait(), QHaikuApplication::RefsReceived(), QMainNfcNewIntentListener::registerListener(), requestFullUpdate(), QCoreApplicationPrivate::sendThroughObjectEventFilters(), QStyleHints::setColorScheme(), QQmlApplication::setDomain(), QQmlApplication::setName(), QQmlApplication::setOrganization(), QOffscreenSurface::setScreen(), QQmlApplication::setVersion(), showParserMessage(), QSingleShotTimer::startTimerForReceiver(), QApplication::style(), QPointingDevicePrivate::tabletDevice(), themeableHint(), themeableHint(), updateWindow(), QWindowsVistaStylePrivate::useVista(), QQC2::QWindowsXPStylePrivate::useXP(), and QQmlApplication::version().

◆ isQuitLockEnabled()

bool QCoreApplication::isQuitLockEnabled ( )
static

Definition at line 1107 of file qcoreapplication.cpp.

References quitLockEnabled.

◆ isSetuidAllowed()

bool QCoreApplication::isSetuidAllowed ( )
static
Since
5.3

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

See also
QCoreApplication::setSetuidAllowed()

Definition at line 1025 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::setuidAllowed.

◆ notify()

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

Sends event to receiver: {receiver}->event(event).

Returns the value that is returned from the receiver's event handler. Note that this function is called for all events sent to any object in any thread.

For certain types of events (e.g. mouse and key events), the event will be propagated to the receiver's parent and so on up to the top-level object if the receiver is not interested in the event (i.e., it returns false).

There are five different ways that events can be processed; reimplementing this virtual function is just one of them. All five approaches are listed below: \list 1

  • Reimplementing \l {QWidget::}{paintEvent()}, \l {QWidget::}{mousePressEvent()} and so on. This is the most common, easiest, and least powerful way.
  • Reimplementing this function. This is very powerful, providing complete control; but only one subclass can be active at a time.
  • 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 \l{QWidget::isEnabled()}{disabled widgets}. Note that application event filters are only called for objects that live in the main thread.
  • Reimplementing 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.
  • 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. \endlist

{Future direction:} This function will not be called for objects that live outside the main thread in Qt 7. 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.

Warning
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.
See also
QObject::event(), installNativeEventFilter()

Reimplemented in QGuiApplication, and QApplication.

Definition at line 1225 of file qcoreapplication.cpp.

References doNotify(), QCoreApplicationPrivate::is_app_closing, QCoreApplicationPrivate::mainThread(), Q_ASSERT, and QObject::thread().

Referenced by QGuiApplication::notify().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ organizationDomain()

static QString QCoreApplication::organizationDomain ( )
static

◆ organizationDomainChanged

void QCoreApplication::organizationDomainChanged ( )
signal

Primarily for QML, see organizationNameChanged.

◆ organizationName()

static QString QCoreApplication::organizationName ( )
static

◆ organizationNameChanged

void QCoreApplication::organizationNameChanged ( )
signal

While not useful from C++ due to how organizationName is normally set once on startup, this is still needed for QML so that bindings are reevaluated after that initial change.

◆ postEvent()

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

Adds the event event, with the object receiver as the receiver of the event, to an event queue and returns immediately.

The event must be allocated on the heap since the post event queue will take ownership of the event and delete it once it has been posted. It is {not safe} to access the event after it has been posted.

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

Events are sorted in descending priority order, i.e. events with a high priority are queued before events with a lower priority. The 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.

\threadsafe

See also
sendEvent(), notify(), sendPostedEvents(), Qt::EventPriority

Definition at line 1674 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::lockThreadPostEventList(), Q_ASSERT_X, Q_TRACE, Q_TRACE_SCOPE, Q_UNUSED, qWarning, and QAbstractEventDispatcher::wakeUp().

Referenced by QAndroidPlatformIntegration::QAndroidPlatformIntegration(), QWaylandCompositorExtension::QWaylandCompositorExtension(), QWaylandCompositorExtension::QWaylandCompositorExtension(), QQuickWorkerScriptEngine::~QQuickWorkerScriptEngine(), QWaylandCompositorPrivate::addPolishObject(), QV4::Promise::ReactionHandler::addReaction(), QV4::Promise::ReactionHandler::addResolveThenable(), QQmlTimerPrivate::animationFinished(), QNetworkReplyImplPrivate::backendNotify(), MFStream::BeginRead(), QTranslatorPrivate::clear(), QObject::deleteLater(), QDBusAbstractInterface::disconnectNotify(), doActivate(), QGuiApplication::event(), QApplication::event(), QEventDispatcherWin32::event(), QBasicDrag::eventFilter(), QGraphicsScene::eventFilter(), QQuickWorkerScriptEngine::executeUrl(), QEglFSKmsVsp2Screen::flip(), QQuickContext2D::flush(), QDBusConnectionPrivate::handleMessage(), QWidgetWindow::handleMouseEvent(), QWidgetPrivate::init(), QGraphicsLayout::invalidate(), QMetaMethodInvoker::invokeImpl(), QQmlTimerPrivate::maybeTick(), QQuickWorkerScriptEnginePrivate::method_sendMessage(), QFutureWatcherBasePrivate::postCallOutEvent(), QQuickPixmapReply::postReply(), QXcbWindow::postSyncWindowRequest(), QQuickContext2D::prepare(), EVRCustomPresenter::presentSample(), ReaderThreadExecutionEnforcer::processJobsOnReaderThreadLater(), qt_fast_timer_proc(), queued_activate(), QCoreApplicationPrivate::quit(), QCoreApplicationPrivate::quitAutomatically(), QHaikuApplication::RefsReceived(), QEventDispatcherWin32Private::registerTimer(), QQmlDelegateModelPrivate::releaseIncubator(), QQuickWorkerScriptEngine::removeWorkerScript(), QQuickWindowPrivate::renderSceneGraph(), requestFullUpdate(), QQmlDelegateModelPrivate::requestMoreIfNecessary(), QSettingsPrivate::requestUpdate(), QQuickDragAttachedPrivate::restartDrag(), QNetworkReplyImplPrivate::resumeNotificationHandling(), QSGRenderThread::run(), QFbScreen::scheduleUpdate(), QQuickWorkerScriptEngine::sendMessage(), QEglFSKmsVsp2Screen::setLayerBuffer(), QWidgetPrivate::setVisible(), QtWaylandClient::QWaylandWlShellSurface::shell_surface_popup_done(), QWidgetPrivate::show_sys(), QQmlData::signalEmitted(), EVRCustomPresenter::startSurface(), QEglFSKmsEventReader::startWaitFlip(), EVRCustomPresenter::stopSurface(), QQmlListModelWorkerAgent::sync(), QSGRenderThread::syncAndRender(), QQuickContext2D::toImage(), QQmlThreadPrivate::triggerMainEvent(), QQmlThreadPrivate::triggerThreadEvent(), QLayout::update(), QWidgetPrivate::update(), QGraphicsWidget::updateGeometry(), QWidgetPrivate::updateGeometry_helper(), QQuickDragAttachedPrivate::updatePosition(), and QWinEventNotifierPrivate::waitCallback().

+ Here is the call graph for this function:

◆ processEvents() [1/3]

void QCoreApplication::processEvents ( QEventLoop::ProcessEventsFlags flags,
int ms )
static

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.Processes pending events for the calling thread for ms milliseconds or until there are no more events to process, whichever is shorter.

This is equivalent to calling:

static void processEvents(QEventLoop::ProcessEventsFlags flags=QEventLoop::AllEvents)
Processes some pending events for the calling thread according to the specified flags.
\inmodule QtCore
GLbitfield flags

Definition at line 1406 of file qcoreapplication.cpp.

References processEvents().

+ Here is the call graph for this function:

◆ processEvents() [2/3]

void QCoreApplication::processEvents ( QEventLoop::ProcessEventsFlags flags,
QDeadlineTimer deadline )
static
Since
6.7 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Processes pending events for the calling thread untile deadline has expired, or until there are no more events to process, whichever happens first.

Use of this function is discouraged. Instead, prefer to move long operations out of the GUI thread into an auxiliary one and to completely avoid nested event loop processing. If event processing is really necessary, consider using \l QEventLoop instead.

Calling this function processes events only for the calling thread.

Note
Unlike the \l{QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags)}{processEvents()} overload, this function also processes events that are posted while the function runs.
All events that were queued before the timeout will be processed, however long it takes.

\threadsafe

See also
exec(), QTimer, QChronoTimer, QEventLoop::processEvents()

Definition at line 1435 of file qcoreapplication.cpp.

References QThreadData::current(), deadline, QDeadlineTimer::hasExpired(), and QEventLoop::WaitForMoreEvents.

+ Here is the call graph for this function:

◆ processEvents() [3/3]

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

Processes some pending events for the calling thread according to the specified flags.

Use of this function is discouraged. Instead, prefer to move long operations out of the GUI thread into an auxiliary one and to completely avoid nested event loop processing. If event processing is really necessary, consider using \l QEventLoop instead.

In the event that you are running a local loop which calls this function continuously, without an event loop, the \l{QEvent::DeferredDelete}{DeferredDelete} events will not be processed. This can affect the behaviour of widgets, e.g. QToolTip, that rely on \l{QEvent::DeferredDelete}{DeferredDelete} events to function properly. An alternative would be to call \l{QCoreApplication::sendPostedEvents()}{sendPostedEvents()} from within that local loop.

Calling this function processes events only for the calling thread, and returns after all available events have been processed. Available events are events queued before the function call. This means that events that are posted while the function runs will be queued until a later round of event processing.

\threadsafe

See also
exec(), QTimer, QChronoTimer, QEventLoop::processEvents(), sendPostedEvents()

Definition at line 1386 of file qcoreapplication.cpp.

References QThreadData::current().

Referenced by QAlsaAudioSink::~QAlsaAudioSink(), QAlsaAudioSource::~QAlsaAudioSource(), QQuickWorkerScriptEngine::~QQuickWorkerScriptEngine(), await(), QTest::QTouchEventSequence::commit(), QTest::QTouchEventWidgetSequence::commit(), QSGSoftwareRenderThread::event(), gc(), QSGRenderThread::invalidateGraphics(), main(), processEvents(), QWindowsOleDropSource::QueryContinueDrag(), QTest::qWait(), QSplashScreen::repaint(), QSGSoftwareRenderThread::run(), QSGRenderThread::run(), QProgressDialog::setValue(), QWidgetPrivate::show_helper(), QGuiApplication::sync(), QNearFieldTargetPrivate::waitForRequestCompleted(), and waitForWidgetMapped().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ quit

void QCoreApplication::quit ( )
staticslot

\threadsafe

Asks the application to quit.

The request may be ignored if the application prevents the quit, for example if one of its windows can't be closed. The application can affect this by handling the QEvent::Quit event on the application level, or QEvent::Close events for the individual windows.

If the quit is not interrupted the application will exit with return code 0 (success).

To exit the application without a chance of being interrupted, call exit() directly. Note that method is not thread-safe.

It's good practice to always connect signals to this slot using a \l{Qt::}{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 \l{QCoreApplication::}{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.

Example:

{Thread-safety note}: this function may be called from any thread to thread-safely cause the currently-running main application loop to exit. However, thread-safety is not guaranteed if the QCoreApplication object is being destroyed at the same time.

See also
exit(), aboutToQuit()

Definition at line 2164 of file qcoreapplication.cpp.

Referenced by TextureSharingExtension::TextureSharingExtension(), QQnxNavigatorEventHandler::handleExit(), QQmlApplicationEnginePrivate::init(), main(), quitQtCoreApplication(), QGuiApplication::setQuitOnLastWindowClosed(), terminateQt(), QtWaylandClient::QWaylandWindowManagerIntegration::windowmanager_quit(), and QWindowsContext::windowsProc().

+ Here is the caller graph for this function:

◆ removeNativeEventFilter()

void QCoreApplication::removeNativeEventFilter ( QAbstractNativeEventFilter * filterObject)

Removes an event 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).

See also
installNativeEventFilter()
Since
5.0

Definition at line 3252 of file qcoreapplication.cpp.

References eventDispatcher(), QAbstractEventDispatcher::instance(), and QCoreApplicationPrivate::theMainThread.

+ Here is the call graph for this function:

◆ removePostedEvents()

void QCoreApplication::removePostedEvents ( QObject * receiver,
int eventType = 0 )
static
Since
4.3

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.

If receiver is \nullptr, 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.

\threadsafe

Definition at line 1982 of file qcoreapplication.cpp.

References QObject::event(), i, j, QCoreApplicationPrivate::lockThreadPostEventList(), QThreadData::postEventList, Q_ASSERT, qDeleteAll(), qSwap(), QPostEvent::receiver, and QList< T >::size().

Referenced by QObjectPrivate::~QObjectPrivate(), QWidget::~QWidget(), QFutureWatcherBasePrivate::callOutInterfaceDisconnected(), QEventLoop::exec(), QWindowPrivate::setVisible(), and QMessageBoxPrivate::updateSize().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ removeTranslator()

bool QCoreApplication::removeTranslator ( QTranslator * translationFile)
static

Removes the translation file translationFile from the list of translation files used by this application.

(It does not delete the translation file from the file system.)

The function returns true on success and false on failure.

See also
installTranslator(), translate(), QObject::tr()

Definition at line 2275 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::checkInstance(), d, QEvent::LanguageChange, and sendEvent().

Referenced by QTranslator::~QTranslator(), QQmlApplicationEnginePrivate::_q_loadTranslations(), and ProxyTranslator::setLanguage().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendEvent()

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

Sends event event directly to receiver receiver, using the notify() function.

Returns the value that was returned from the event handler.

The event is not deleted when the event has been sent. The normal approach is to create the event on the stack, for example:

See also
postEvent(), notify()

Definition at line 1590 of file qcoreapplication.cpp.

References Q_ASSERT_X, and Q_TRACE.

Referenced by QMacStyle::QMacStyle(), QQC2_NAMESPACE::QMacStyle::QMacStyle(), QWhatsThisPrivate::QWhatsThisPrivate(), QWidget::~QWidget(), QGraphicsScenePrivate::_q_polishItems(), QEventDispatcherUNIXPrivate::activateSocketNotifiers(), QTimerInfoList::activateTimers(), QWidget::changeEvent(), QAbstractItemViewPrivate::checkMouseMove(), QWidget::clearFocus(), QQuickDeliveryAgentPrivate::clearFocusInScope(), QGraphicsWidget::close(), QMdiSubWindow::closeEvent(), QApplicationPrivate::closePopup(), QIBusPlatformInputContext::commit(), QtWaylandClient::QWaylandTextInputv1::commit(), QtWaylandClient::QWaylandTextInputv2::commit(), QIBusPlatformInputContext::commitText(), QWindowsInputContext::composition(), QDialog::contextMenuEvent(), QGraphicsView::contextMenuEvent(), QGraphicsProxyWidget::contextMenuEvent(), QOffscreenSurface::create(), QWindowPrivate::create(), QIBusPlatformInputContext::deleteSurroundingText(), QAndroidInputContext::deleteSurroundingText(), QQuickDeliveryAgentPrivate::deliverHoverEventToItem(), QQuickDeliveryAgentPrivate::deliverKeyEvent(), QQuickDeliveryAgentPrivate::deliverMatchingPointsToItem(), QQuickDeliveryAgentPrivate::deliverSinglePointEventUntilAccepted(), QQuickDeliveryAgentPrivate::deliverToPassiveGrabbers(), QQuickDeliveryAgentPrivate::deliverTouchAsMouse(), QPlatformWindow::deliverUpdateRequest(), QOffscreenSurface::destroy(), QWindowPrivate::destroy(), QApplicationPrivate::dispatchEnterLeave(), QAbstractItemView::doAutoScroll(), QQuickTableViewPrivate::editFromKeyEvent(), QWindowsInputContext::endComposition(), QWidget::ensurePolished(), QAction::event(), QWindow::event(), QApplication::event(), QSystemTrayIconSys::event(), QQuickItem::event(), QQuickWindow::event(), QQuickWidget::event(), QEventDispatcherWin32::event(), QProxyStyle::event(), QWindowContainer::event(), QQuickDeliveryAgent::event(), QGraphicsProxyWidget::event(), QGraphicsView::event(), QWidget::event(), QMdiArea::event(), QWhatsThisPrivate::eventFilter(), QCompleter::eventFilter(), QFontDialog::eventFilter(), QComposeInputContext::filterEvent(), QGraphicsView::focusInEvent(), QQuickWidget::focusNextPrevChild(), QGraphicsView::focusOutEvent(), QIBusPlatformInputContext::forwardKeyEvent(), QQuickSwipeDelegatePrivate::forwardMouseEvent(), QWidgetPrivate::handleClose(), QAndroidInputContext::handleLocationChanged(), QGuiApplicationPrivate::handlePaletteChanged(), QApplicationPrivate::handlePaletteChanged(), QWidgetPrivate::hide_helper(), QWidgetPrivate::hideChildren(), QIBusPlatformInputContext::hidePreeditText(), QWaylandCompositorPrivate::init(), QWidgetPrivate::init(), QWindowPrivate::init(), QGraphicsProxyWidget::inputMethodEvent(), QGraphicsView::inputMethodEvent(), QAbstractItemView::inputMethodEvent(), inputMethodQueryRectangle_helper(), QGraphicsWidget::insertAction(), QWidget::insertAction(), installTranslator(), QGraphicsWidget::itemChange(), QQuickKeysAttached::keyPressed(), QMenu::keyPressEvent(), QQuickWidget::keyPressEvent(), QGraphicsView::keyPressEvent(), QQuickKeysAttached::keyReleased(), QQuickWidget::keyReleaseEvent(), QGraphicsView::keyReleaseEvent(), QAndroidInputContext::longPress(), QWidget::lower(), QQuickWidget::mouseDoubleClickEvent(), QGraphicsView::mouseDoubleClickEvent(), QMenuPrivate::mouseEventTaken(), QQuickWidget::mouseMoveEvent(), QHeaderView::mouseMoveEvent(), QGraphicsViewPrivate::mouseMoveEventHandler(), QQuickWidget::mousePressEvent(), QGraphicsView::mousePressEvent(), QWhatsThat::mouseReleaseEvent(), QQuickWidget::mouseReleaseEvent(), QGraphicsView::mouseReleaseEvent(), QQuickFlickable::mouseReleaseEvent(), QQuickVisualTestUtils::moveMouseAway(), QObjectPrivate::moveToThread_helper(), QApplicationPrivate::notifyActiveWindowChange(), QGuiApplicationPrivate::notifyActiveWindowChange(), QGuiApplicationPrivate::notifyLayoutDirectionChange(), QApplicationPrivate::notifyLayoutDirectionChange(), QWhatsThisPrivate::notifyToplevels(), QGuiApplicationPrivate::notifyWindowIconChanged(), QApplicationPrivate::notifyWindowIconChanged(), QInputMethodPrivate::objectAcceptsInputMethod(), QAbstractItemViewPrivate::openEditor(), QApplicationPrivate::openPopup(), QWidget::overrideWindowState(), QGuiApplicationPrivate::processScreenOrientationChange(), QQuickMenuPrivate::propagateKeyEvent(), QWidgetPrivate::propagatePaletteChange(), qSendWindowChangeToTextureChildrenRecursively(), qt_sendShortcutOverrideEvent(), QInputMethod::queryFocusObject(), queryInputMethod(), querySelection(), QCoreApplicationPrivate::quit(), QWidget::raise(), QWindowsInputContext::reconvertString(), QGraphicsWidget::removeAction(), QWidget::removeAction(), QGraphicsProxyWidgetPrivate::removeSubFocusHelper(), removeTranslator(), QQuickFlickablePrivate::replayDelayedPress(), QWindowsInputContext::reset(), QWidgetPrivate::scrollChildren(), sendChangeRecursively(), QActionPrivate::sendDataChanged(), QGraphicsScenePrivate::sendEvent(), QQuickDeliveryAgentPrivate::sendHoverEvent(), QApplicationPrivate::sendMouseEvent(), QWidgetPrivate::sendPendingMoveAndResizeEvents(), QCoreApplicationPrivate::sendPostedEvents(), sendResizeEvents(), QAndroidInputContext::sendShortcut(), QEventDispatcherWin32Private::sendTimerEvent(), QPointingDevicePrivate::sendTouchCancelEvent(), QGraphicsProxyWidgetPrivate::sendWidgetKeyEvent(), QGraphicsScenePrivate::setActivePanelHelper(), QApplicationPrivate::setActiveWindow(), QWidget::setAttribute(), QAndroidInputContext::setComposingText(), QGraphicsWidget::setContentsMargins(), QMenuBarPrivate::setCurrentAction(), QWidget::setCursor(), QWindowPrivate::setCursor(), QWidgetPrivate::setEnabled_helper(), QGraphicsScene::setFocus(), QWidget::setFocus(), QQuickDeliveryAgentPrivate::setFocusInScope(), QQnxInputContext::setFocusObject(), QApplicationPrivate::setFocusWidget(), QGuiApplication::setFont(), QApplication::setFont(), QWidgetPrivate::setGeometry_sys(), QGraphicsWidgetPrivate::setLayoutDirection_helper(), QWidgetPrivate::setLayoutDirection_helper(), QWidgetPrivate::setLocale_helper(), QWidget::setParent(), QObjectPrivate::setParent_helper(), QAbstractSpinBox::setReadOnly(), QPlainTextEdit::setReadOnly(), QTextEdit::setReadOnly(), QLineEdit::setReadOnly(), QGraphicsView::setScene(), QAndroidInputContext::setSelection(), QPlatformInputContext::setSelectionOnFocusObject(), QApplication::setStyle(), QGraphicsScene::setStyle(), QGraphicsWidget::setStyle(), QWidgetPrivate::setStyle_helper(), QWindowPrivate::setVisible(), QDialogPrivate::setVisible(), QWidgetPrivate::setVisible(), QWidgetPrivate::setWindowIcon_helper(), QWidget::setWindowIconText(), QWidget::setWindowModified(), QWidget::setWindowState(), QWidget::setWindowTitle(), QWidgetPrivate::setWinId(), QWizard::setWizardStyle(), QWidgetPrivate::show_helper(), QGuiApplicationPrivate::showModalWindow(), QIBusPlatformInputContext::showPreeditText(), QActionPrivate::showStatusText(), socketNotifierSourceDispatch(), QWidget::stackUnder(), QtWaylandClient::QWaylandTextInputMethod::text_input_method_v1_end_input_method_event(), QtWaylandClient::QWaylandTextInputMethod::text_input_method_v1_key(), QMacPanGestureRecognizer::timerEvent(), QQuickFlickable::touchEvent(), QApplicationPrivate::translateRawTouchEvent(), QWidget::unsetCursor(), ImeState::update(), QIBusPlatformInputContext::update(), QtWaylandClient::QWaylandInputMethodContext::update(), updateBlockedStatusRecursion(), QWidgetPrivate::updateContentsRect(), QWindowPrivate::updateDevicePixelRatio(), QWidgetPrivate::updateFont(), QGraphicsScenePrivate::updateFont(), QGraphicsWidgetPrivate::updateFont(), QGraphicsScenePrivate::updatePalette(), QGraphicsWidgetPrivate::updatePalette(), QIBusPlatformInputContext::updatePreeditText(), QAndroidInputContext::updateSelectionHandles(), QtWaylandClient::QWaylandTextInputv1::updateState(), QtWaylandClient::QWaylandTextInputv2::updateState(), QtWaylandClient::QWaylandTextInputv3::updateState(), QStyleAnimation::updateTarget(), QHeaderView::viewportEvent(), QGraphicsView::viewportEvent(), QAbstractItemView::viewportEvent(), QtWaylandClient::QWaylandTextInputv1::zwp_text_input_v1_commit_string(), QtWaylandClient::QWaylandTextInputv1::zwp_text_input_v1_preedit_string(), QtWaylandClient::QWaylandTextInputv2::zwp_text_input_v2_commit_string(), QtWaylandClient::QWaylandTextInputv2::zwp_text_input_v2_preedit_string(), and QtWaylandClient::QWaylandTextInputv3::zwp_text_input_v3_done().

◆ sendPostedEvents()

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

Immediately dispatches all events which have been previously queued with QCoreApplication::postEvent() and which are for the object receiver and have the event type event_type.

Events from the window system are not dispatched by this function, but by processEvents().

If receiver is \nullptr, the events of event_type are sent for all objects. If event_type is 0, all the events are sent for receiver.

Note
This method must be called from the thread in which its QObject parameter, receiver, lives.
See also
postEvent()

Definition at line 1780 of file qcoreapplication.cpp.

References QThreadData::current(), and QCoreApplicationPrivate::sendPostedEvents().

Referenced by QAbstractItemView::closeEditor(), QGraphicsViewPrivate::dispatchPendingUpdateRequests(), QSGSoftwareRenderThread::event(), QCoreApplicationPrivate::execCleanup(), gc(), QSGRenderThread::invalidateGraphics(), postEventSourceDispatch(), QEventDispatcherWasm::processPostedEvents(), QCocoaEventDispatcherPrivate::processPostedEvents(), qFadeEffect(), qScrollEffect(), QTest::qWait(), QSGSoftwareRenderThread::sync(), QSGRenderThread::sync(), QDBusPendingCallWatcher::waitForFinished(), and waitForWidgetMapped().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setApplicationName()

void QCoreApplication::setApplicationName ( const QString & application)
static

Definition at line 2754 of file qcoreapplication.cpp.

References emit, and QString::isEmpty().

Referenced by main(), main(), and snippet_ctor2().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setApplicationVersion()

void QCoreApplication::setApplicationVersion ( const QString & version)
static

Definition at line 2807 of file qcoreapplication.cpp.

References applicationVersion, emit, and QString::isEmpty().

Referenced by main(), main(), runMoc(), runRcc(), and runUic().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setAttribute()

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

Sets the attribute attribute if on is true; otherwise clears the attribute.

[95]

Note
Some application attributes must be set before creating a QCoreApplication instance. Refer to the Qt::ApplicationAttribute documentation for more information.
See also
testAttribute()

[96]

Definition at line 1040 of file qcoreapplication.cpp.

References Qt::AA_AttributeCount, Qt::AA_PluginApplication, Qt::AA_ShareOpenGLContexts, Qt::AA_UseDesktopOpenGL, Qt::AA_UseOpenGLES, Qt::AA_UseSoftwareOpenGL, QCoreApplicationPrivate::attribs, QCoreApplicationPrivate::is_app_running, Q_UNLIKELY, qApp, and qWarning.

Referenced by init_platform(), QApplicationPrivate::initialize(), QWindowsIntegrationPrivate::parseOptions(), and QGuiApplicationPrivate::setPalette().

+ Here is the caller graph for this function:

◆ setEventDispatcher()

void QCoreApplication::setEventDispatcher ( QAbstractEventDispatcher * eventDispatcher)
static

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 has been instantiated. This method takes ownership of the object.

Definition at line 3277 of file qcoreapplication.cpp.

References QThread::currentThread(), eventDispatcher(), mainThread, and QCoreApplicationPrivate::theMainThread.

+ Here is the call graph for this function:

◆ setOrganizationDomain()

void QCoreApplication::setOrganizationDomain ( const QString & orgDomain)
static

Definition at line 2716 of file qcoreapplication.cpp.

References emit.

Referenced by snippet_ctor2().

+ Here is the caller graph for this function:

◆ setOrganizationName()

void QCoreApplication::setOrganizationName ( const QString & orgName)
static

[11]

[12]

Definition at line 2679 of file qcoreapplication.cpp.

References emit.

Referenced by snippet_ctor2().

+ Here is the caller graph for this function:

◆ setQuitLockEnabled()

void QCoreApplication::setQuitLockEnabled ( bool enabled)
static

Definition at line 1114 of file qcoreapplication.cpp.

References enabled, and quitLockEnabled.

Referenced by QuitLockDisabler::QuitLockDisabler(), and QuitLockDisabler::~QuitLockDisabler().

+ Here is the caller graph for this function:

◆ setSetuidAllowed()

void QCoreApplication::setSetuidAllowed ( bool allow)
static
Since
5.3

Allows the application to run setuid on UNIX platforms if allow is true.

If 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.

Note
It is strongly recommended not to enable this option since it introduces security risks. If this application does enable the flag and starts child processes, it should drop the privileges as early as possible by calling {setuid(2)} for itself, or at the latest by using the QProcess::UnixProcessParameters::ResetIds flag.

Definition at line 1012 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::setuidAllowed.

◆ startingUp()

bool QCoreApplication::startingUp ( )
static

Returns true if an application object has not been created yet; otherwise returns false.

See also
closingDown()

Definition at line 1339 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::is_app_running.

Referenced by QCursor::QCursor(), QGuiApplicationPrivate::processScreenGeometryChange(), QGuiApplicationPrivate::processScreenLogicalDotsPerInchChange(), QGuiApplicationPrivate::processScreenOrientationChange(), and QGuiApplicationPrivate::processScreenRefreshRateChange().

+ Here is the caller graph for this function:

◆ testAttribute()

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

Returns true if attribute attribute is set; otherwise returns false.

See also
setAttribute()

Definition at line 1081 of file qcoreapplication.cpp.

References QCoreApplicationPrivate::testAttribute().

Referenced by QCocoaIntegration::QCocoaIntegration(), QOpenGLProgramBinarySupportCheck::QOpenGLProgramBinarySupportCheck(), QWidgetWindow::QWidgetWindow(), QCocoaIntegration::~QCocoaIntegration(), QDialogPrivate::canBeNativeDialog(), QColorDialogPrivate::canBeNativeDialog(), QFileDialogPrivate::canBeNativeDialog(), QFontDialogPrivate::canBeNativeDialog(), QMessageBoxPrivate::canBeNativeDialog(), QQuickDeliveryAgentPrivate::deliverMatchingPointsToItem(), QQuickDeliveryAgentPrivate::deliverTouchAsMouse(), QStyleHelper::dpi(), QQC2::QStyleHelper::dpi(), QQuickLayout::effectiveSizePolicy_helper(), QOpenGLWidget::event(), QQuickDeliveryAgent::event(), QMenuBarPrivate::init(), initializeRHI(), installNativeEventFilter(), QAction::isIconVisibleInMenu(), QAction::isShortcutVisibleInContextMenu(), QQuickLayoutAttached::itemForSizePolicy(), QWidgetPrivate::naturalWidgetFont(), QWidgetPrivate::naturalWidgetPalette(), QWindowsIntegrationPrivate::parseOptions(), platformSurfaceType(), QWidgetPrivate::propagatePaletteChange(), qt_redirectNSApplicationSendEvent(), qt_resetNSApplicationSendEvent(), QWindowsOpenGLTester::requestedRenderer(), QQuickDeliveryAgentPrivate::sendFilteredPointerEventImpl(), QWidget::setAttribute(), QWidgetPrivate::setFocus_sys(), QAction::setIconVisibleInMenu(), QWidget::setParent(), QAction::setShortcutVisibleInContextMenu(), swapModifiersIfNeeded(), QQuickDeliveryAgentPrivate::touchToMouseEvent(), QWindowsPointerHandler::translatePointerEvent(), QWidgetPrivate::updateFont(), QQuickLabsPlatformDialog::useNativeDialog(), and QQuickAbstractDialog::useNativeDialog().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ translate()

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

\threadsafe

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 \nullptr.

See the \l QTranslator and \l 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() for details.

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 \l QTranslator.

See also
QObject::tr(), installTranslator(), removeTranslator(), {Internationalization and Translations}

Definition at line 2357 of file qcoreapplication.cpp.

References QSet< T >::constBegin(), QSet< T >::constEnd(), context, d, QString::fromUtf8(), it, and replacePercentN().

Referenced by QtFontStyle::Key::Key(), QAbstractPrintDialog::QAbstractPrintDialog(), QAbstractPrintDialog::QAbstractPrintDialog(), QNetworkReplyDataImpl::QNetworkReplyDataImpl(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), QPageSetupDialog::QPageSetupDialog(), QPageSetupDialog::QPageSetupDialog(), QPrintPreviewDialogPrivate::_q_print(), QNetworkReplyImplPrivate::_q_startOperation(), addKey(), QMimerSQLDriver::beginTransaction(), QOCIDriver::beginTransaction(), checkRegistration(), QT_BEGIN_NAMESPACE::checkUsageTerms(), QMimerSQLDriver::commitTransaction(), QOCIDriver::commitTransaction(), QWindowsDirect2DIntegration::create(), QMimerSQLResult::data(), QKeySequencePrivate::decodeString(), QPlatformPrintDevice::defaultInputSlot(), QFileDialogOptions::defaultNameFilterString(), QPlatformPrintDevice::defaultOutputBin(), QPlatformTheme::defaultStandardButtonText(), detectMenuRole(), QStandardPaths::displayName(), QKeySequencePrivate::encodeString(), QHttpNetworkConnectionPrivate::errorDetail(), QJsonParseError::errorString(), QRegularExpression::errorString(), QSslDiffieHellmanParameters::errorString(), QDB2Result::exec(), QIBaseResult::exec(), QMimerSQLResult::exec(), QMYSQLResult::exec(), QOCIResult::exec(), QODBCResult::exec(), QPSQLResult::exec(), QSQLiteResult::exec(), QMimerSQLResult::execBatch(), QOCICols::execBatch(), f(), QDB2Result::fetch(), QMimerSQLResult::fetch(), QMYSQLResult::fetch(), QODBCResult::fetch(), QDB2Result::fetchFirst(), QMimerSQLResult::fetchFirst(), QODBCResult::fetchFirst(), QMimerSQLResult::fetchLast(), QODBCResult::fetchLast(), QDB2Result::fetchNext(), QMimerSQLResult::fetchNext(), QMYSQLResult::fetchNext(), QODBCResult::fetchNext(), QPSQLResult::fetchNext(), QSQLiteResultPrivate::fetchNext(), QODBCResult::fetchPrevious(), QQmlJS::Dom::fileTypeForPath(), QmlIR::IRBuilder::generateFromQml(), QAbstractFileIconProviderPrivate::getFileType(), getFontWeight(), QOCIResult::gotoNext(), QHttp2Connection::handleConnectionClosure(), QHttp2ProtocolHandler::handleConnectionClosure(), QPrintPreviewDialogPrivate::init(), QIBaseDriverPrivate::isError(), QIBaseResultPrivate::isError(), QMimerSQLResult::isNull(), QKeySequencePrivate::keyName(), QHostInfoAgent::lookup(), main(), main(), QMediaMetaData::metaDataKeyToString(), msgCouldNotGet(), msgCouldNotSet(), msgImperialPageSizeInch(), msgType2i18nString(), QPageSize::name(), QDB2Result::nextResult(), QMYSQLResult::nextResult(), QODBCResult::nextResult(), QNetworkReplyHttpImplPrivate::onRedirected(), QNetworkFile::open(), QNetworkAccessCacheBackend::open(), QNetworkAccessFileBackend::open(), QMimerSQLDriver::open(), QDB2Result::prepare(), QMimerSQLResult::prepare(), QOCIResult::prepare(), QODBCResult::prepare(), QPSQLResult::prepare(), QSQLiteResult::prepare(), QMYSQLResult::prepare(), QPSQLResultPrivate::processResults(), qMakeError(), qt_mac_applicationmenu_string(), qt_nameForCustomSize(), qtTrId(), QNetworkAccessFileBackend::read(), QNetworkReplyHttpImpl::readData(), QNetworkReplyHttpImplPrivate::replyDownloadData(), QNetworkReplyHttpImplPrivate::replyDownloadMetaData(), QDB2Result::reset(), QMYSQLResult::reset(), QODBCResult::reset(), QPSQLResult::reset(), QMimerSQLDriver::rollbackTransaction(), QOCIDriver::rollbackTransaction(), PragmaParser< Argument >::run(), QQmlJS::Lexer::scanDirectives(), QQmlJS::Lexer::scanRegExp(), QDecompressHelper::setEncoding(), QQmlXmlListModel::setQuery(), QPrintPreviewDialogPrivate::setupActions(), QQmlPropertyCache::signalParameterStringForJS(), QGnomeTheme::standardButtonText(), QAndroidPlatformTheme::standardButtonText(), QCocoaTheme::standardButtonText(), standardLibraryErrorString(), styleStringHelper(), QMetaObject::tr(), tr(), QQmlTranslation::QsTrData::translate(), QV4::ExecutableCompilationUnit::translateFrom(), QDeclarativeSearchModelBase::update(), QDeclarativeSupportedCategoriesModel::update(), QNetworkAccessFileBackend::uploadReadyReadSlot(), QmlIR::IRBuilder::visit(), QmlIR::IRBuilder::visit(), QmlIR::IRBuilder::visit(), QmlIR::IRBuilder::visit(), and QFontDatabase::writingSystemName().

+ Here is the call graph for this function:

Friends And Related Symbol Documentation

◆ qAddPostRoutine()

void qAddPostRoutine ( QtCleanUpFunction ptr)
related

\macro Q_COREAPP_STARTUP_FUNCTION(QtStartUpFunction ptr)

Since
5.1

\reentrant

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);
}

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.

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

Note
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.

\threadsafe

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 = nullptr;
static void cleanup_ptr()
{
delete [] global_ptr;
global_ptr = nullptr;
}
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:

{
public:
{
if (!p)
return p;
}
{
// cleanup goes here
}
private:
{
// initialization goes here
}
};

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

Note
This function has been thread-safe since Qt 5.10.
See also
qRemovePostRoutine()

Definition at line 282 of file qcoreapplication.cpp.

References globalRoutinesMutex, list, and QList< T >::prepend().

+ Here is the call graph for this function:

◆ QApplication

friend class QApplication
friend

Definition at line 234 of file qcoreapplication.h.

◆ QApplicationPrivate

friend class QApplicationPrivate
friend

Definition at line 235 of file qcoreapplication.h.

Referenced by QLineEdit::mousePressEvent().

◆ qAppName

Q_CORE_EXPORT QString qAppName ( )
friend

Definition at line 574 of file qcoreapplication.cpp.

◆ QCocoaEventDispatcherPrivate

friend class QCocoaEventDispatcherPrivate
friend

Definition at line 243 of file qcoreapplication.h.

◆ QCommandLineParserPrivate

friend class QCommandLineParserPrivate
friend

Definition at line 247 of file qcoreapplication.h.

◆ QEventDispatcherUNIXPrivate

friend class QEventDispatcherUNIXPrivate
friend

Definition at line 242 of file qcoreapplication.h.

◆ QEventLoopLocker

friend class QEventLoopLocker
friend

Definition at line 63 of file qcoreapplication.h.

◆ QGuiApplication

friend class QGuiApplication
friend

Definition at line 236 of file qcoreapplication.h.

◆ QGuiApplicationPrivate

friend class QGuiApplicationPrivate
friend

Definition at line 237 of file qcoreapplication.h.

◆ qRemovePostRoutine()

void qRemovePostRoutine ( QtCleanUpFunction ptr)
related

\threadsafe

Since
5.3

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.

Note
This function has been thread-safe since Qt 5.10.
See also
qAddPostRoutine()

Definition at line 291 of file qcoreapplication.cpp.

References globalRoutinesMutex, list, and QList< T >::removeAll().

+ Here is the call graph for this function:

◆ qt_sendSpontaneousEvent

bool qt_sendSpontaneousEvent ( QObject * ,
QEvent *  )
friend

◆ QWidget

friend class QWidget
friend

Definition at line 238 of file qcoreapplication.h.

◆ QWidgetPrivate

friend class QWidgetPrivate
friend

Definition at line 240 of file qcoreapplication.h.

◆ QWidgetWindow

friend class QWidgetWindow
friend

Definition at line 239 of file qcoreapplication.h.

◆ resolveInterface()

void * resolveInterface ( const char * name,
int revision ) const
related

\macro Q_DECLARE_TR_FUNCTIONS(context)

The Q_DECLARE_TR_FUNCTIONS() macro declares and implements the translation function tr() with this signature:

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

This macro is useful if you want to use QObject::tr() 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:}). For example:

class MyMfcView : public CView
{
public:
...
};
static MyPrivateInitStuff * initStuff(QObject *parent)
static bool sendEvent(QObject *receiver, QEvent *event)
Sends event event directly to receiver receiver, using the notify() function.
static void quit()
\threadsafe
@ MouseButtonPress
Definition qcoreevent.h:60
\inmodule QtGui
Definition qevent.h:196
void qAddPostRoutine(QtCleanUpFunction p)
#define Q_COREAPP_STARTUP_FUNCTION(AFUNC)
#define Q_DECLARE_TR_FUNCTIONS(context)
QMouseEvent event(QEvent::MouseButtonPress, pos, 0, 0, 0)
[0]
static int * global_ptr
[3]
static void cleanup_ptr()
QPushButton * quitButton
[0]
static void preRoutineMyDebugTool()
[1]

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

See also
Q_OBJECT, QObject::tr()

Definition at line 3396 of file qcoreapplication.cpp.

References Q_UNUSED.

Property Documentation

◆ applicationName

QString QCoreApplication::applicationName
readwrite

the name of this application

The application name is used in various Qt classes and modules, most prominently in \l{QSettings} when it is constructed using the default constructor. Other uses are in formatted logging output (see \l{qSetMessagePattern()}), in output by \l{QCommandLineParser}, in \l{QTemporaryDir} and \l{QTemporaryFile} default paths, and in some file locations of \l{QStandardPaths}. \l{Qt D-Bus}, \l{Accessibility}, and the XCB platform integration make use of the application name, too.

If not set, the application name defaults to the executable name.

See also
organizationName, organizationDomain, applicationVersion, applicationFilePath()

Definition at line 51 of file qcoreapplication.h.

Referenced by QT_BEGIN_NAMESPACE::appendOrganizationAndApp(), appendOrganizationAndApp(), appendOrganizationAndApp(), appendOrganizationAndApp(), QBluetoothSocketPrivateBluezDBus::connectToServiceHelper(), formatLogMessage(), QPlatformWindow::formatWindowTitle(), QQuickWidgetPrivate::handleContextCreationFailure(), QSGRenderLoop::handleContextCreationFailure(), QStatusNotifierItemAdaptor::id(), init_platform(), QBasicPlatformVulkanInstance::initInstance(), QQmlSettingsPrivate::instance(), QCommandLineParser::process(), QErrorMessage::qtHandler(), QXcbConnection::qtSelectionOwner(), QGuiApplication::setApplicationDisplayName(), QDBusTrayIcon::showMessage(), showParserMessage(), QCommandLineParser::showVersion(), QStatusNotifierItemAdaptor::title(), and QXcbIntegration::wmClass().

◆ applicationVersion

QString QCoreApplication::applicationVersion
readwrite

the version of this application

Since
4.4

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

\table \header

  • Platform
  • Source \row
  • Windows (classic desktop)
  • PRODUCTVERSION parameter of the VERSIONINFO resource \row
  • macOS, iOS, tvOS, watchOS
  • CFBundleVersion property of the information property list \row
  • Android
  • android:versionName property of the AndroidManifest.xml manifest element \endtable

On other platforms, the default is the empty string.

See also
applicationName, organizationName, organizationDomain

Definition at line 53 of file qcoreapplication.h.

Referenced by setApplicationVersion(), and QCommandLineParser::showVersion().

◆ organizationDomain

QString QCoreApplication::organizationDomain
readwrite

the Internet domain of the organization that wrote this application

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

On Mac, QSettings uses 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.

See also
organizationName, applicationName, applicationVersion

Definition at line 57 of file qcoreapplication.h.

Referenced by QQmlSettingsPrivate::instance().

◆ organizationName

QString QCoreApplication::organizationName
readwrite

the name of the organization that wrote this application

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

On Mac, QSettings uses \l {QCoreApplication::}{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.

See also
organizationDomain, applicationName

Definition at line 55 of file qcoreapplication.h.

Referenced by QT_BEGIN_NAMESPACE::appendOrganizationAndApp(), appendOrganizationAndApp(), appendOrganizationAndApp(), appendOrganizationAndApp(), and QQmlSettingsPrivate::instance().

◆ quitLockEnabled

QCoreApplication::quitLockEnabled
readwrite

Whether the use of the QEventLoopLocker feature can cause the application to quit.

When this property is true the release of the last remaining QEventLoopLocker operating on the application will attempt to quit the application.

Note that attempting a quit may not necessarily result in the application quitting, for example if there still are open windows, or the QEvent::Quit event is ignored.

The default is true.

See also
QEventLoopLocker

Definition at line 59 of file qcoreapplication.h.

Referenced by QCoreApplicationPrivate::deref(), isQuitLockEnabled(), and setQuitLockEnabled().


The documentation for this class was generated from the following files: