Qt 4.8
Public Types | Public Slots | Signals | Public Functions | Static Public Functions | Protected Functions | Private Functions | Static Private Functions | Properties | Static Private Attributes | Friends | Related Functions | List of all members
QCoreApplication Class Reference

The QCoreApplication class provides an event loop for console Qt applications. More...

#include <qcoreapplication.h>

Inheritance diagram for QCoreApplication:
QObject QApplication

Public Types

enum  { ApplicationFlags }
 
enum  Encoding { CodecForTr, UnicodeUTF8, DefaultCodec = CodecForTr }
 This enum type defines the 8-bit encoding of character string arguments to translate(): More...
 
typedef bool(* EventFilter) (void *message, long *result)
 A function with the following signature that can be used as an event filter: More...
 

Public Slots

static void quit ()
 Tells the application to exit with return code 0 (success). More...
 
- Public Slots inherited from QObject
void deleteLater ()
 Schedules this object for deletion. More...
 

Signals

void aboutToQuit ()
 This signal is emitted when the application is about to quit the main event loop, e. More...
 
void unixSignal (int)
 This signal is emitted whenever a Unix signal is received by the application. More...
 
- Signals inherited from QObject
void destroyed (QObject *=0)
 This signal is emitted immediately before the object obj is destroyed, and can not be blocked. More...
 

Public Functions

bool filterEvent (void *message, long *result)
 Sends message through the event filter that was set by setEventFilter(). More...
 
virtual bool notify (QObject *, QEvent *)
 Sends event to receiver: {receiver}->event(event). More...
 
 QCoreApplication (int &argc, char **argv)
 Constructs a Qt kernel application. More...
 
EventFilter setEventFilter (EventFilter filter)
 Replaces the event filter function for the QCoreApplication with filter and returns the pointer to the replaced event filter function. More...
 
virtual bool winEventFilter (MSG *message, long *result)
 The message procedure calls this function for every message received. More...
 
 ~QCoreApplication ()
 Destroys the QCoreApplication object. More...
 
- Public Functions inherited from QObject
bool blockSignals (bool b)
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). More...
 
const QObjectListchildren () const
 Returns a list of child objects. More...
 
bool connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=0, const QObject *receiver=0, const char *member=0)
 
bool disconnect (const QObject *receiver, const char *member=0)
 
void dumpObjectInfo ()
 Dumps information about signal connections, etc. More...
 
void dumpObjectTree ()
 Dumps a tree of children to the debug output. More...
 
QList< QByteArraydynamicPropertyNames () const
 Returns the names of all properties that were dynamically added to the object using setProperty(). More...
 
virtual bool eventFilter (QObject *, QEvent *)
 Filters events if this object has been installed as an event filter for the watched object. More...
 
template<typename T >
findChild (const QString &aName=QString()) const
 Returns the child of this object that can be cast into type T and that is called name, or 0 if there is no such object. More...
 
template<typename T >
QList< T > findChildren (const QString &aName=QString()) 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. More...
 
template<typename T >
QList< T > findChildren (const QRegExp &re) const
 
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. More...
 
void installEventFilter (QObject *)
 Installs an event filter filterObj on this object. More...
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false. More...
 
void killTimer (int id)
 Kills the timer with timer identifier, id. More...
 
virtual const QMetaObjectmetaObject () const
 Returns a pointer to the meta-object of this object. More...
 
void moveToThread (QThread *thread)
 Changes the thread affinity for this object and its children. More...
 
QString objectName () const
 
QObjectparent () const
 Returns a pointer to the parent object. More...
 
QVariant property (const char *name) const
 Returns the value of the object's name property. More...
 
Q_INVOKABLE QObject (QObject *parent=0)
 Constructs an object with parent object parent. More...
 
void removeEventFilter (QObject *)
 Removes an event filter object obj from this object. More...
 
void setObjectName (const QString &name)
 
void setParent (QObject *)
 Makes the object a child of parent. More...
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value. More...
 
void setUserData (uint id, QObjectUserData *data)
 
bool signalsBlocked () const
 Returns true if signals are blocked; otherwise returns false. More...
 
int startTimer (int interval)
 Starts a timer and returns a timer identifier, or returns zero if it could not start a timer. More...
 
QThreadthread () const
 Returns the thread in which the object lives. More...
 
QObjectUserDatauserData (uint id) const
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects. More...
 

Static Public Functions

static void addLibraryPath (const QString &)
 Prepends path to the beginning of the library path list, ensuring that it is searched for libraries first. More...
 
static QString applicationDirPath ()
 Returns the directory that contains the application executable. More...
 
static QString applicationFilePath ()
 Returns the file path of the application executable. More...
 
static QString applicationName ()
 
static qint64 applicationPid ()
 Returns the current process ID for the application. More...
 
static QString applicationVersion ()
 
static QT_DEPRECATED int argc ()
 Use arguments(). More...
 
static QStringList arguments ()
 Returns the list of command-line arguments. More...
 
static QT_DEPRECATED char ** argv ()
 Use arguments() instead. More...
 
static bool closingDown ()
 Returns true if the application objects are being destroyed; otherwise returns false. More...
 
static int exec ()
 Enters the main event loop and waits until exit() is called. More...
 
static void exit (int retcode=0)
 Tells the application to exit with a return code. More...
 
static void flush ()
 Flushes the platform specific event queues. More...
 
static bool hasPendingEvents ()
 This function returns true if there are pending events; otherwise returns false. More...
 
static void installTranslator (QTranslator *messageFile)
 Adds the translation file translationFile to the list of translation files to be used for translations. More...
 
static QCoreApplicationinstance ()
 Returns a pointer to the application's QCoreApplication (or QApplication) instance. More...
 
static QStringList libraryPaths ()
 Returns a list of paths that the application will search when dynamically loading libraries. More...
 
static QString organizationDomain ()
 
static QString organizationName ()
 
static void postEvent (QObject *receiver, QEvent *event)
 Adds the event event, with the object receiver as the receiver of the event, to an event queue and returns immediately. More...
 
static void postEvent (QObject *receiver, QEvent *event, int priority)
 
static void processEvents (QEventLoop::ProcessEventsFlags flags=QEventLoop::AllEvents)
 Processes all pending events for the calling thread according to the specified flags until there are no more events to process. More...
 
static void processEvents (QEventLoop::ProcessEventsFlags flags, int maxtime)
 
static void removeLibraryPath (const QString &)
 Removes path from the library path list. More...
 
static void removePostedEvents (QObject *receiver)
 Removes all events posted using postEvent() for receiver. More...
 
static void removePostedEvents (QObject *receiver, int eventType)
 
static void removeTranslator (QTranslator *messageFile)
 Removes the translation file translationFile from the list of translation files used by this application. More...
 
static bool sendEvent (QObject *receiver, QEvent *event)
 Sends event event directly to receiver receiver, using the notify() function. More...
 
static void sendPostedEvents (QObject *receiver, int event_type)
 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. More...
 
static void sendPostedEvents ()
 
static void setApplicationName (const QString &application)
 
static void setApplicationVersion (const QString &version)
 
static void setAttribute (Qt::ApplicationAttribute attribute, bool on=true)
 Sets the attribute attribute if on is true; otherwise clears the attribute. More...
 
static void setLibraryPaths (const QStringList &)
 Sets the list of directories to search when loading libraries to paths. More...
 
static void setOrganizationDomain (const QString &orgDomain)
 
static void setOrganizationName (const QString &orgName)
 
static bool startingUp ()
 Returns true if an application object has not been created yet; otherwise returns false. More...
 
static bool testAttribute (Qt::ApplicationAttribute attribute)
 Returns true if attribute attribute is set; otherwise returns false. More...
 
static QString translate (const char *context, const char *key, const char *disambiguation=0, Encoding encoding=CodecForTr)
 
static QString translate (const char *context, const char *key, const char *disambiguation, Encoding encoding, int n)
 Returns the translation text for sourceText, by querying the installed translation files. More...
 
static void watchUnixSignal (int signal, bool watch)
 
- Static Public Functions inherited from QObject
static bool connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 Creates a connection of the given type from the signal in the sender object to the method in the receiver object. More...
 
static bool connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 Disconnects signal in object sender from method in object receiver. More...
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static uint registerUserData ()
 
static QString tr (const char *sourceText, const char *comment=0, int n=-1)
 
static QString trUtf8 (const char *sourceText, const char *comment=0, int n=-1)
 

Protected Functions

virtual bool compressEvent (QEvent *, QObject *receiver, QPostEventList *)
 Returns true if event was compressed away (possibly deleted) and should not be added to the list. More...
 
bool event (QEvent *)
 This virtual function receives events to an object and should return true if the event e was recognized and processed. More...
 
 QCoreApplication (QCoreApplicationPrivate &p)
 
- Protected Functions inherited from QObject
virtual void childEvent (QChildEvent *)
 This event handler can be reimplemented in a subclass to receive child events. More...
 
virtual void connectNotify (const char *signal)
 This virtual function is called when something has been connected to signal in this object. More...
 
virtual void customEvent (QEvent *)
 This event handler can be reimplemented in a subclass to receive custom events. More...
 
virtual void disconnectNotify (const char *signal)
 This virtual function is called when something has been disconnected from signal in this object. More...
 
 QObject (QObjectPrivate &dd, QObject *parent=0)
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal. More...
 
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns 0. More...
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *)
 This event handler can be reimplemented in a subclass to receive timer events for the object. More...
 

Private Functions

void init ()
 
bool notifyInternal (QObject *receiver, QEvent *event)
 

Static Private Functions

static bool sendSpontaneousEvent (QObject *receiver, QEvent *event)
 

Properties

QString applicationName
 the name of this application More...
 
QString applicationVersion
 the version of this application More...
 
QString organizationDomain
 the Internet domain of the organization that wrote this application More...
 
QString organizationName
 the name of the organization that wrote this application More...
 

Static Private Attributes

static QCoreApplicationself = 0
 

Friends

class Q3AccelManager
 
class QApplication
 
class QApplicationPrivate
 
Q_CORE_EXPORT QString qAppName ()
 
class QClassFactory
 
class QETWidget
 
class QEventDispatcherUNIXPrivate
 
class QShortcutMap
 
bool qt_sendSpontaneousEvent (QObject *, QEvent *)
 
class QWidget
 
class QWidgetPrivate
 

Related Functions

(Note that these are not member functions.)

void qAddPostRoutine (QtCleanUpFunction ptr)
 Adds a global routine that will be called from the QApplication destructor. More...
 
 removePostedEvents
 Removes all events of the given eventType that were posted using postEvent() for receiver. More...
 

Additional Inherited Members

- Static Public Variables inherited from QObject
static const QMetaObject staticMetaObject
 This variable stores the meta-object for the class. More...
 
- Protected Variables inherited from QObject
QScopedPointer< QObjectDatad_ptr
 
- Static Protected Variables inherited from QObject
static const QMetaObject staticQtMetaObject
 

Detailed Description

The QCoreApplication class provides an event loop for console Qt applications.

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

The Event Loop and Event Handling

The event loop is started with a call to exec(). Long running operations can call processEvents() to keep the application responsive.

In general, we recommend that you create a QCoreApplication or a QApplication object in your main() function as early as possible. exec() will not return until the event loop exits; e.g., when quit() is called.

Several static convenience functions are also provided. The QCoreApplication object is available from instance(). Events can be sent or posted using sendEvent(), postEvent(), and sendPostedEvents(). Pending events can be removed with removePostedEvents() or flushed with flush().

The class provides a quit() slot and an aboutToQuit() signal.

Application and Library Paths

An application has an applicationDirPath() and an applicationFilePath(). Library paths (see QLibrary) can be retrieved with libraryPaths() and manipulated by setLibraryPaths(), addLibraryPath(), and removeLibraryPath().

Internationalization and Translations

Translation files can be added or removed using installTranslator() and removeTranslator(). Application strings can be translated using translate(). The QObject::tr() and QObject::trUtf8() functions are implemented in terms of translate().

Accessing Command Line Arguments

The command line arguments which are passed to QCoreApplication's constructor should be accessed using the arguments() function. Note that some arguments supplied by the user may have been processed and removed by QCoreApplication.

In cases where command line arguments need to be obtained using the argv() function, you must convert them from the local string encoding using QString::fromLocal8Bit().

Locale Settings

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 or QCoreApplication to reset the locale that is used for number formatting to "C"-locale.

See also
QApplication, QAbstractEventDispatcher, QEventLoop, {Semaphores Example}, {Wait Conditions Example}

Definition at line 71 of file qcoreapplication.h.

Typedefs

◆ EventFilter

QCoreApplication::EventFilter

A function with the following signature that can be used as an event filter:

bool myEventFilter(void *message, long *result);
See also
setEventFilter()

Definition at line 188 of file qcoreapplication.h.

Enumerations

◆ anonymous enum

anonymous enum
Enumerator
ApplicationFlags 

Definition at line 81 of file qcoreapplication.h.

82 #if !defined(QT3_SUPPORT)
83  | 0x01000000
84 #endif
85  };
#define QT_VERSION
This macro expands a numeric value of the form 0xMMNNPP (MM = major, NN = minor, PP = patch) that spe...
Definition: qglobal.h:51

◆ Encoding

This enum type defines the 8-bit encoding of character string arguments to translate():

  • UnicodeUTF8 UTF-8.
  • DefaultCodec (Obsolete) Use CodecForTr instead.
See also
QObject::tr(), QObject::trUtf8(), QString::fromUtf8()
Enumerator
CodecForTr 
UnicodeUTF8 
DefaultCodec 

Definition at line 154 of file qcoreapplication.h.

Constructors and Destructors

◆ QCoreApplication() [1/2]

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

Constructs a Qt kernel application.

Kernel applications are applications without a graphical user interface. These type of 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 710 of file qcoreapplication.cpp.

Referenced by QApplication::QApplication().

711  : QObject(*new QCoreApplicationPrivate(argc, argv, 0x040000))
712 {
713  init();
715 #if defined(Q_OS_SYMBIAN) && !defined(QT_NO_LIBRARY)
716  // Refresh factoryloader, as text codecs are requested during lib path
717  // resolving process and won't be therefore properly loaded.
718  // Unknown if this is symbian specific issue.
720 #endif
721 
722 #if defined(Q_OS_SYMBIAN) && !defined(QT_NO_SYSTEMLOCALE)
723  d_func()->symbianInit();
724 #endif
725 }
static QT_DEPRECATED int argc()
Use arguments().
static void refreshAll()
static QT_DEPRECATED char ** argv()
Use arguments() instead.
static QAbstractEventDispatcher * eventDispatcher
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753
friend class QCoreApplicationPrivate
Definition: qobject.h:328

◆ ~QCoreApplication()

QCoreApplication::~QCoreApplication ( )

Destroys the QCoreApplication object.

Definition at line 840 of file qcoreapplication.cpp.

841 {
843 
844  self = 0;
847 
848 #if !defined(QT_NO_THREAD)
849 #if !defined(QT_NO_CONCURRENT)
850  // Synchronize and stop the global thread pool threads.
851  QThreadPool *globalThreadPool = 0;
852  QT_TRY {
853  globalThreadPool = QThreadPool::globalInstance();
854  } QT_CATCH (...) {
855  // swallow the exception, since destructors shouldn't throw
856  }
857  if (globalThreadPool)
858  globalThreadPool->waitForDone();
859 #endif
861 #endif
862 
863  d_func()->threadData->eventDispatcher = 0;
867 
868 #ifndef QT_NO_LIBRARY
869  delete coreappdata()->app_libpaths;
870  coreappdata()->app_libpaths = 0;
871 #endif
872 }
static void cleanup()
Cleans up the QThread system.
Definition: qthread.cpp:661
void Q_CORE_EXPORT qt_call_post_routines()
The QThreadPool class manages a collection of QThreads.
Definition: qthreadpool.h:58
void waitForDone()
Waits for each thread to exit and removes all threads from the thread pool.
#define QT_CATCH(A)
Definition: qglobal.h:1537
static QAbstractEventDispatcher * eventDispatcher
static QThreadPool * globalInstance()
Returns the global QThreadPool instance.
#define QT_TRY
Definition: qglobal.h:1536

◆ QCoreApplication() [2/2]

QCoreApplication::QCoreApplication ( QCoreApplicationPrivate p)
protected
Warning
This function is not part of the public interface.

Definition at line 671 of file qcoreapplication.cpp.

672  : QObject(p, 0)
673 {
674  init();
675  // note: it is the subclasses' job to call
676  // QCoreApplicationPrivate::eventDispatcher->startingUp();
677 }
Q_INVOKABLE QObject(QObject *parent=0)
Constructs an object with parent object parent.
Definition: qobject.cpp:753

Functions

◆ aboutToQuit

void QCoreApplication::aboutToQuit ( )
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 users 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.

See also
quit()

Referenced by exec().

◆ addLibraryPath()

void QCoreApplication::addLibraryPath ( const QString path)
static

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

In Symbian this function is only useful for adding paths for finding Qt extension plugin stubs, since the OS can only load libraries from the /sys/bin directory.

See also
removeLibraryPath(), libraryPaths(), setLibraryPaths()

Definition at line 2649 of file qcoreapplication.cpp.

Referenced by QPlatformIntegrationFactory::create(), QPlatformIntegrationFactory::keys(), QApplicationPrivate::qt_mac_apply_settings(), and QApplicationPrivate::x11_apply_settings().

2650 {
2651  if (path.isEmpty())
2652  return;
2653 
2654  QMutexLocker locker(libraryPathMutex());
2655 
2656  // make sure that library paths is initialized
2657  libraryPaths();
2658 
2659  QString canonicalPath = QDir(path).canonicalPath();
2660  if (!canonicalPath.isEmpty()
2661  && !coreappdata()->app_libpaths->contains(canonicalPath)) {
2662  coreappdata()->app_libpaths->prepend(canonicalPath);
2663  locker.unlock();
2665  }
2666 }
The QDir class provides access to directory structures and their contents.
Definition: qdir.h:58
static void refreshAll()
QString & prepend(QChar c)
Definition: qstring.h:261
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
static QStringList libraryPaths()
Returns a list of paths that the application will search when dynamically loading libraries...
QString canonicalPath() const
Returns the canonical path, i.e.
Definition: qdir.cpp:642

◆ applicationDirPath()

QString QCoreApplication::applicationDirPath ( )
static

Returns the directory that contains the application executable.

For example, if you have installed Qt in the C:/Trolltech/Qt directory, and you run the regexp example, this function will return "C:/Trolltech/Qt/examples/tools/regexp".

On Mac OS X this will point to the directory actually containing the executable, which may be inside of 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.

In Symbian this function will return the application private directory, not the path to executable itself, as those are always in {/sys/bin}. If the application is in a read only drive, i.e. ROM, then the private path on the system drive will be returned.

See also
applicationFilePath()

Definition at line 2060 of file qcoreapplication.cpp.

Referenced by QmlApplicationViewerPrivate::adjustPath(), QCoreApplicationPrivate::appendApplicationPathToLibraryPaths(), QLibraryInfoPrivate::findConfiguration(), isDirPath(), QTranslator::load(), QLibraryInfo::location(), QDeclarativeImportDatabase::QDeclarativeImportDatabase(), and QDeclarativeImportDatabase::resolvePlugin().

2061 {
2062  if (!self) {
2063  qWarning("QCoreApplication::applicationDirPath: Please instantiate the QApplication object first");
2064  return QString();
2065  }
2066 
2067  QCoreApplicationPrivate *d = self->d_func();
2069 #if defined(Q_OS_SYMBIAN)
2070  {
2071  QString appPath;
2072  RFs& fs = qt_s60GetRFs();
2073  TChar driveChar;
2074  QChar qDriveChar;
2075  driveChar = (RProcess().FileName())[0];
2076 
2077  //Check if the process is installed in a read only drive (typically ROM),
2078  //and use the system drive (typically C:) if so.
2079  TInt drive;
2080  TDriveInfo driveInfo;
2081  TInt err = fs.CharToDrive(driveChar, drive);
2082  if (err == KErrNone) {
2083  err = fs.Drive(driveInfo, drive);
2084  }
2085  if (err != KErrNone || (driveInfo.iDriveAtt & KDriveAttRom) || (driveInfo.iMediaAtt
2086  & KMediaAttWriteProtected)) {
2087  drive = fs.GetSystemDrive();
2088  fs.DriveToChar(drive, driveChar);
2089  }
2090 
2091  qDriveChar = QChar(QLatin1Char(driveChar)).toUpper();
2092 
2093  TFileName privatePath;
2094  fs.PrivatePath(privatePath);
2095  appPath = qt_TDesC2QString(privatePath);
2096  appPath.prepend(QLatin1Char(':')).prepend(qDriveChar);
2097 
2098  d->cachedApplicationDirPath = QFileInfo(appPath).path();
2099  }
2100 #else
2102 #endif
2103  return d->cachedApplicationDirPath;
2104 }
double d
Definition: qnumeric_p.h:62
static QString applicationFilePath()
Returns the file path of the application executable.
QString & prepend(QChar c)
Definition: qstring.h:261
The QString class provides a Unicode character string.
Definition: qstring.h:83
The QChar class provides a 16-bit Unicode character.
Definition: qchar.h:72
Q_CORE_EXPORT void qWarning(const char *,...)
QChar toUpper() const
Returns the uppercase equivalent if the character is lowercase or titlecase; otherwise returns the ch...
Definition: qchar.cpp:1287
bool isNull() const
Returns true if this string is null; otherwise returns false.
Definition: qstring.h:505
QString path() const
Returns the file&#39;s path.
Definition: qfileinfo.cpp:615
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ 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 2121 of file qcoreapplication.cpp.

Referenced by QCoreApplicationPrivate::appendApplicationPathToLibraryPaths(), applicationDirPath(), QPatternist::XPathHelper::normalizeQueryURI(), and QAccessibleApplication::text().

2122 {
2123  if (!self) {
2124  qWarning("QCoreApplication::applicationFilePath: Please instantiate the QApplication object first");
2125  return QString();
2126  }
2127 
2128  QCoreApplicationPrivate *d = self->d_func();
2130  return d->cachedApplicationFilePath;
2131 
2132 #if defined(Q_WS_WIN)
2134  return d->cachedApplicationFilePath;
2135 #elif defined(Q_OS_BLACKBERRY)
2136  if (!arguments().isEmpty()) { // args is never empty, but the navigator can change behaviour some day
2137  QFileInfo fileInfo(arguments().at(0));
2138  const bool zygotized = fileInfo.exists();
2139  if (zygotized) {
2140  // Handle the zygotized case:
2141  d->cachedApplicationFilePath = QDir::cleanPath(fileInfo.absoluteFilePath());
2142  return d->cachedApplicationFilePath;
2143  }
2144  }
2145 
2146  // Handle the non-zygotized case:
2147  const size_t maximum_path = static_cast<size_t>(pathconf("/",_PC_PATH_MAX));
2148  char buff[maximum_path+1];
2149  if (_cmdname(buff)) {
2151  return d->cachedApplicationFilePath;
2152  } else {
2153  qWarning("QCoreApplication::applicationFilePath: _cmdname() failed");
2154  // _cmdname() won't fail, but just in case, fallback to the old method
2155  QDir dir(QLatin1String("./app/native/"));
2156  QStringList executables = dir.entryList(QDir::Executable | QDir::Files);
2157  if (!executables.empty()) {
2158  //We assume that there is only one executable in the folder
2159  d->cachedApplicationFilePath = dir.absoluteFilePath(executables.first());
2160  return d->cachedApplicationFilePath;
2161  } else {
2162  return QString();
2163  }
2164  }
2165 #elif defined(Q_WS_MAC)
2166  QString qAppFileName_str = qAppFileName();
2167  if(!qAppFileName_str.isEmpty()) {
2168  QFileInfo fi(qAppFileName_str);
2169  d->cachedApplicationFilePath = fi.exists() ? fi.canonicalFilePath() : QString();
2170  return d->cachedApplicationFilePath;
2171  }
2172 #endif
2173 #if defined(Q_OS_SYMBIAN)
2174  QString appPath;
2175  RProcess proc;
2176  TInt err = proc.Open(proc.Id());
2177  if (err == KErrNone) {
2178  TFileName procName = proc.FileName();
2179  appPath.append(QString(reinterpret_cast<const QChar*>(procName.Ptr()), procName.Length()));
2180  proc.Close();
2181  }
2182 
2183  d->cachedApplicationFilePath = appPath;
2184  return d->cachedApplicationFilePath;
2185 
2186 #elif defined( Q_OS_UNIX )
2187 # ifdef Q_OS_LINUX
2188  // Try looking for a /proc/<pid>/exe symlink first which points to
2189  // the absolute path of the executable
2190  QFileInfo pfi(QString::fromLatin1("/proc/%1/exe").arg(getpid()));
2191  if (pfi.exists() && pfi.isSymLink()) {
2192  d->cachedApplicationFilePath = pfi.canonicalFilePath();
2193  return d->cachedApplicationFilePath;
2194  }
2195 # endif
2196 
2197  QString argv0 = QFile::decodeName(QByteArray(argv()[0]));
2198  QString absPath;
2199 
2200  if (!argv0.isEmpty() && argv0.at(0) == QLatin1Char('/')) {
2201  /*
2202  If argv0 starts with a slash, it is already an absolute
2203  file path.
2204  */
2205  absPath = argv0;
2206  } else if (argv0.contains(QLatin1Char('/'))) {
2207  /*
2208  If argv0 contains one or more slashes, it is a file path
2209  relative to the current directory.
2210  */
2211  absPath = QDir::current().absoluteFilePath(argv0);
2212  } else {
2213  /*
2214  Otherwise, the file path has to be determined using the
2215  PATH environment variable.
2216  */
2217  QByteArray pEnv = qgetenv("PATH");
2218  QDir currentDir = QDir::current();
2220  for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) {
2221  if ((*p).isEmpty())
2222  continue;
2223  QString candidate = currentDir.absoluteFilePath(*p + QLatin1Char('/') + argv0);
2224  QFileInfo candidate_fi(candidate);
2225  if (candidate_fi.exists() && !candidate_fi.isDir()) {
2226  absPath = candidate;
2227  break;
2228  }
2229  }
2230  }
2231 
2232  absPath = QDir::cleanPath(absPath);
2233 
2234  QFileInfo fi(absPath);
2235  d->cachedApplicationFilePath = fi.exists() ? fi.canonicalFilePath() : QString();
2236  return d->cachedApplicationFilePath;
2237 #endif
2238 }
The QDir class provides access to directory structures and their contents.
Definition: qdir.h:58
QBool contains(QChar c, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Definition: qstring.h:904
double d
Definition: qnumeric_p.h:62
Q_CORE_EXPORT QByteArray qgetenv(const char *varName)
static QString fromLocal8Bit(const char *, int size=-1)
Returns a QString initialized with the first size characters of the 8-bit string str.
Definition: qstring.cpp:4245
QString absoluteFilePath(const QString &fileName) const
Returns the absolute path name of a file in the directory.
Definition: qdir.cpp:701
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
#define at(className, varName)
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
#define Q_WS_WIN
Defined on Windows.
Definition: qglobal.h:921
bool empty() const
This function is provided for STL compatibility.
Definition: qlist.h:304
const_iterator constBegin() const
Returns a const STL-style iterator pointing to the first item in the list.
Definition: qlist.h:269
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
The QString class provides a Unicode character string.
Definition: qstring.h:83
static QT_DEPRECATED char ** argv()
Use arguments() instead.
QString qAppFileName()
static QString decodeName(const QByteArray &localFileName)
This does the reverse of QFile::encodeName() using localFileName.
Definition: qfile.cpp:552
friend class const_iterator
Definition: qlist.h:264
static bool isEmpty(const char *str)
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
static QDir current()
Returns the application&#39;s current directory.
Definition: qdir.h:209
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
Q_CORE_EXPORT void qWarning(const char *,...)
static void split(QT_FT_Vector *b)
static QString cleanPath(const QString &path)
Removes all multiple directory separators "/" and resolves any "."s or ".."s found in the path...
Definition: qdir.cpp:2082
T & first()
Returns a reference to the first item in the list.
Definition: qlist.h:282
const char * constData() const
Returns a pointer to the data stored in the byte array.
Definition: qbytearray.h:433
bool isNull() const
Returns true if this string is null; otherwise returns false.
Definition: qstring.h:505
QString & append(QChar c)
Definition: qstring.cpp:1777
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
static QStringList arguments()
Returns the list of command-line arguments.
The QFileInfo class provides system-independent file information.
Definition: qfileinfo.h:60
QString filePath() const
Returns the file name, including the path (which may be absolute or relative).
Definition: qfileinfo.cpp:707
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the list...
Definition: qlist.h:272

◆ applicationName()

static QString QCoreApplication::applicationName ( )
static

◆ applicationPid()

qint64 QCoreApplication::applicationPid ( )
static

Returns the current process ID for the application.

Since
4.4

Definition at line 2248 of file qcoreapplication.cpp.

Referenced by createFileFromTemplate(), QBBBpsEventFilter::handleNavigatorEvent(), and QBenchmarkValgrindUtils::outFileBase().

2249 {
2250 #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
2251  return GetCurrentProcessId();
2252 #elif defined(Q_OS_VXWORKS)
2253  return (pid_t) taskIdCurrent;
2254 #else
2255  return getpid();
2256 #endif
2257 }

◆ applicationVersion()

static QString QCoreApplication::applicationVersion ( )
static

Referenced by setApplicationVersion().

◆ argc()

int QCoreApplication::argc ( )
static

Use arguments().

size() instead.

Definition at line 2267 of file qcoreapplication.cpp.

Referenced by QApplication::QApplication().

2268 {
2269  if (!self) {
2270  qWarning("QCoreApplication::argc: Please instantiate the QApplication object first");
2271  return 0;
2272  }
2273  return self->d_func()->argc;
2274 }
Q_CORE_EXPORT void qWarning(const char *,...)

◆ arguments()

QStringList QCoreApplication::arguments ( )
static

Returns the list of command-line arguments.

Since
4.1

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 NT-based Windows, this limitation does not apply either. On Windows, the arguments() are not built from the contents of argv/argc, as the content does not support Unicode. Instead, 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.

For Symbian applications started with RApaLsSession::StartApp one can specify arguments using CApaCommandLine::SetTailEndL function. Such arguments are only available via this method; they will not be passed to main function. Also note that only 8-bit string data set with CApaCommandLine::SetTailEndL is supported by this function.

See also
applicationFilePath()

Definition at line 2333 of file qcoreapplication.cpp.

Referenced by applicationFilePath(), QDirectFBScreen::connect(), QDirectFbIntegration::initializeDirectFB(), and QTest::qExec().

2334 {
2335  QStringList list;
2336 
2337  if (!self) {
2338  qWarning("QCoreApplication::arguments: Please instantiate the QApplication object first");
2339  return list;
2340  }
2341 #ifdef Q_OS_WIN
2342  QString cmdline = QString::fromWCharArray(GetCommandLine());
2343 
2344 #if defined(Q_OS_WINCE)
2345  wchar_t tempFilename[MAX_PATH+1];
2346  if (GetModuleFileName(0, tempFilename, MAX_PATH)) {
2347  tempFilename[MAX_PATH] = 0;
2348  cmdline.prepend(QLatin1Char('\"') + QString::fromWCharArray(tempFilename) + QLatin1String("\" "));
2349  }
2350 #endif // Q_OS_WINCE
2351 
2352  list = qWinCmdArgs(cmdline);
2353  if (self->d_func()->application_type) { // GUI app? Skip known - see qapplication.cpp
2355  for (int a = 0; a < list.count(); ++a) {
2356  QString arg = list.at(a);
2357  QByteArray l1arg = arg.toLatin1();
2358  if (l1arg == "-qdevel" ||
2359  l1arg == "-qdebug" ||
2360  l1arg == "-reverse" ||
2361  l1arg == "-stylesheet" ||
2362  l1arg == "-widgetcount")
2363  ;
2364  else if (l1arg.startsWith("-style=") ||
2365  l1arg.startsWith("-qmljsdebugger="))
2366  ;
2367  else if (l1arg == "-style" ||
2368  l1arg == "-qmljsdebugger" ||
2369  l1arg == "-session" ||
2370  l1arg == "-graphicssystem" ||
2371  l1arg == "-testability")
2372  ++a;
2373  else
2374  stripped += arg;
2375  }
2376  list = stripped;
2377  }
2378 #else
2379  const int ac = self->d_func()->argc;
2380  char ** const av = self->d_func()->argv;
2381  for (int a = 0; a < ac; ++a) {
2382  list << QString::fromLocal8Bit(av[a]);
2383  }
2384 #endif
2385 
2386  return list;
2387 }
static QString fromWCharArray(const wchar_t *, int size=-1)
Returns a copy of the string, where the encoding of string depends on the size of wchar...
Definition: qstring.cpp:1019
static QString fromLocal8Bit(const char *, int size=-1)
Returns a QString initialized with the first size characters of the 8-bit string str.
Definition: qstring.cpp:4245
static QStringList qWinCmdArgs(QString cmdLine)
static glyph_t stripped(glyph_t glyph)
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
QString & prepend(QChar c)
Definition: qstring.h:261
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
long ASN1_INTEGER_get ASN1_INTEGER * a
int count(const T &t) const
Returns the number of occurrences of value in the list.
Definition: qlist.h:891
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool startsWith(const QByteArray &a) const
Returns true if this byte array starts with byte array ba; otherwise returns false.
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
Q_CORE_EXPORT void qWarning(const char *,...)
QByteArray toLatin1() const Q_REQUIRED_RESULT
Returns a Latin-1 representation of the string as a QByteArray.
Definition: qstring.cpp:3993
static QCoreApplication * self
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55

◆ argv()

char ** QCoreApplication::argv ( )
static

Use arguments() instead.

Definition at line 2285 of file qcoreapplication.cpp.

Referenced by applicationFilePath(), and QApplication::QApplication().

2286 {
2287  if (!self) {
2288  qWarning("QCoreApplication::argv: Please instantiate the QApplication object first");
2289  return 0;
2290  }
2291  return self->d_func()->argv;
2292 }
Q_CORE_EXPORT void qWarning(const char *,...)

◆ closingDown()

bool QCoreApplication::closingDown ( )
static

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

Warning
This function is not part of the public interface.

Reimplemented in QApplication.

Definition at line 1418 of file qcoreapplication.cpp.

Referenced by QApplication::compressEvent(), and QApplication::isLeftToRight().

1419 {
1420 #ifdef Q_WS_WIN
1421  Q_ASSERT(event);
1422  Q_ASSERT(receiver);
1423  Q_ASSERT(postedEvents);
1424 
1425  // compress posted timers to this object.
1426  if (event->type() == QEvent::Timer && receiver->d_func()->postedEvents > 0) {
1427  int timerId = ((QTimerEvent *) event)->timerId();
1428  for (int i=0; i<postedEvents->size(); ++i) {
1429  const QPostEvent &e = postedEvents->at(i);
1430  if (e.receiver == receiver && e.event && e.event->type() == QEvent::Timer
1431  && ((QTimerEvent *) e.event)->timerId() == timerId) {
1432  delete event;
1433  return true;
1434  }
1435  }
1436  } else
1437 #endif
1438  if ((event->type() == QEvent::DeferredDelete
1439  || event->type() == QEvent::Quit)
1440  && receiver->d_func()->postedEvents > 0) {
1441  for (int i = 0; i < postedEvents->size(); ++i) {
1442  const QPostEvent &cur = postedEvents->at(i);
1443  if (cur.receiver != receiver
1444  || cur.event == 0
1445  || cur.event->type() != event->type())
1446  continue;
1447  // found an event for this receiver
1448  delete event;
1449  return true;
1450  }
1451  }
1452  return false;
1453 }
bool event(QEvent *)
This virtual function receives events to an object and should return true if the event e was recogniz...
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
QEvent * event
Definition: qthread_p.h:78
QObject * receiver
Definition: qthread_p.h:77
The QTimerEvent class contains parameters that describe a timer event.
Definition: qcoreevent.h:341
int size() const
Returns the number of items in the list.
Definition: qlist.h:137
Type type() const
Returns the event type.
Definition: qcoreevent.h:303

◆ event()

bool QCoreApplication::event ( QEvent e)
protectedvirtual

This virtual function receives events to an object and should return true if the event e was recognized and processed.

The event() function can be reimplemented to customize the behavior of an object.

See also
installEventFilter(), timerEvent(), QApplication::sendEvent(), QApplication::postEvent(), QWidget::event()

Reimplemented from QObject.

Reimplemented in QApplication.

Definition at line 1777 of file qcoreapplication.cpp.

Referenced by compressEvent(), QApplication::event(), QApplication::isLeftToRight(), notifyInternal(), postEvent(), removePostedEvents(), and QCoreApplicationPrivate::sendPostedEvents().

1778 {
1779  if (e->type() == QEvent::Quit) {
1780  quit();
1781  return true;
1782  }
1783  return QObject::event(e);
1784 }
virtual bool event(QEvent *)
This virtual function receives events to an object and should return true if the event e was recogniz...
Definition: qobject.cpp:1200
static void quit()
Tells the application to exit with return code 0 (success).
Type type() const
Returns the event type.
Definition: qcoreevent.h:303

◆ exec()

int QCoreApplication::exec ( )
static

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

Returns the value that was set 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 (i.e. executing a special function whenever there are no pending events), use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().

We recommend that you connect clean-up code to the QCoreApplication::aboutToQuit() signal, instead of putting it in your application's main() function because on some platforms the QCoreApplication::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 QCoreApplication::exec() call.

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

Definition at line 1212 of file qcoreapplication.cpp.

Referenced by QApplication::exec(), and QApplication::isLeftToRight().

1213 {
1215  return -1;
1216 
1217  QThreadData *threadData = self->d_func()->threadData;
1218  if (threadData != QThreadData::current()) {
1219  qWarning("%s::exec: Must be called from the main thread", self->metaObject()->className());
1220  return -1;
1221  }
1222  if (!threadData->eventLoops.isEmpty()) {
1223  qWarning("QCoreApplication::exec: The event loop is already running");
1224  return -1;
1225  }
1226 
1227  threadData->quitNow = false;
1228  QEventLoop eventLoop;
1229  self->d_func()->in_exec = true;
1230  self->d_func()->aboutToQuitEmitted = false;
1231  int returnCode = eventLoop.exec();
1232  threadData->quitNow = false;
1233  if (self) {
1234  self->d_func()->in_exec = false;
1235  if (!self->d_func()->aboutToQuitEmitted)
1236  emit self->aboutToQuit();
1237  self->d_func()->aboutToQuitEmitted = true;
1239  }
1240 
1241  return returnCode;
1242 }
static bool checkInstance(const char *method)
The QEventLoop class provides a means of entering and leaving an event loop.
Definition: qeventloop.h:55
#define emit
Definition: qobjectdefs.h:76
Q_CORE_EXPORT void qWarning(const char *,...)
static void sendPostedEvents()
bool quitNow
Definition: qthread_p.h:262
void aboutToQuit()
This signal is emitted when the application is about to quit the main event loop, e...
const char * className() const
Returns the class name.
Definition: qobjectdefs.h:491
static QThreadData * current()
static QCoreApplication * self
bool isEmpty() const
Returns true if the vector has size 0; otherwise returns false.
Definition: qvector.h:139
int exec(ProcessEventsFlags flags=AllEvents)
Enters the main event loop and waits until exit() is called.
Definition: qeventloop.cpp:181
virtual const QMetaObject * metaObject() const
Returns a pointer to the meta-object of this object.
QStack< QEventLoop * > eventLoops
Definition: qthread_p.h:265

◆ exit()

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

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.

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

See also
quit(), exec()

Definition at line 1262 of file qcoreapplication.cpp.

Referenced by quit().

1263 {
1264  if (!self)
1265  return;
1266  QThreadData *data = self->d_func()->threadData;
1267  data->quitNow = true;
1268  for (int i = 0; i < data->eventLoops.size(); ++i) {
1269  QEventLoop *eventLoop = data->eventLoops.at(i);
1270  eventLoop->exit(returnCode);
1271  }
1272 }
The QEventLoop class provides a means of entering and leaving an event loop.
Definition: qeventloop.h:55
static const char * data(const QByteArray &arr)
bool quitNow
Definition: qthread_p.h:262
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
void exit(int returnCode=0)
Tells the event loop to exit with a return code.
Definition: qeventloop.cpp:288
int size() const
Returns the number of items in the vector.
Definition: qvector.h:137
QStack< QEventLoop * > eventLoops
Definition: qthread_p.h:265

◆ filterEvent()

bool QCoreApplication::filterEvent ( void *  message,
long *  result 
)

Sends message through the event filter that was set by setEventFilter().

If no event filter has been set, this function returns false; otherwise, this function returns the result of the event filter function in the result parameter.

See also
setEventFilter()

Definition at line 2788 of file qcoreapplication.cpp.

Referenced by QApplicationPrivate::globalEventProcessor(), and qt_internal_proc().

2789 {
2791  if (result)
2792  *result = 0;
2793  if (d->eventFilter)
2794  return d->eventFilter(message, result);
2795 #ifdef Q_OS_WIN
2796  return winEventFilter(reinterpret_cast<MSG *>(message), result);
2797 #else
2798  return false;
2799 #endif
2800 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QCoreApplication class provides an event loop for console Qt applications.
virtual bool winEventFilter(MSG *message, long *result)
The message procedure calls this function for every message received.

◆ flush()

void QCoreApplication::flush ( )
static

Flushes the platform specific event queues.

If you are doing graphical changes inside a loop that does not return to the event loop on asynchronous window systems like X11 or double buffered window systems like Mac OS X, and you want to visualize these changes immediately (e.g. Splash Screens), call this function.

See also
sendPostedEvents()

Definition at line 690 of file qcoreapplication.cpp.

Referenced by QAbstractButton::animateClick(), QAbstractButtonPrivate::click(), QX11Data::dndEnable(), QWindowsStyle::drawComplexControl(), flush(), QApplication::isLeftToRight(), QAbstractButton::keyPressEvent(), QAbstractButton::mouseMoveEvent(), QAbstractButton::mousePressEvent(), qt_mac_mouse_inside_answer_rect(), qt_x11_wait_for_window_manager(), QSplashScreen::repaint(), and QProgressDialog::setValue().

691 {
692  if (self && self->d_func()->eventDispatcher)
693  self->d_func()->eventDispatcher->flush();
694 }
static QCoreApplication * self
static void flush()
Flushes the platform specific event queues.

◆ hasPendingEvents()

bool QCoreApplication::hasPendingEvents ( )
static

This function returns true if there are pending events; otherwise returns false.

Pending events can be either from the window system or posted events using postEvent().

See also
QAbstractEventDispatcher::hasPendingEvents()

Definition at line 2809 of file qcoreapplication.cpp.

2810 {
2812  if (eventDispatcher)
2813  return eventDispatcher->hasPendingEvents();
2814  return false;
2815 }
static QAbstractEventDispatcher * instance(QThread *thread=0)
Returns a pointer to the event dispatcher object for the specified thread.
virtual bool hasPendingEvents()=0
Returns true if there is an event waiting; otherwise returns false.
The QAbstractEventDispatcher class provides an interface to manage Qt&#39;s event queue.

◆ init()

void QCoreApplication::init ( )
private

Definition at line 747 of file qcoreapplication.cpp.

Referenced by QCoreApplication().

748 {
750 
751 #ifdef Q_OS_UNIX
752  setlocale(LC_ALL, ""); // use correct char set mapping
753  qt_locale_initialized = true;
754 #endif
755 
756  Q_ASSERT_X(!self, "QCoreApplication", "there should be only one application object");
757  QCoreApplication::self = this;
758 
759 #ifdef Q_OS_SYMBIAN
760  //ensure temp and working directories exist
763 #endif
764 
765 #ifndef QT_NO_THREAD
767 #endif
768 
769  // use the event dispatcher created by the app programmer (if any)
771  QCoreApplicationPrivate::eventDispatcher = d->threadData->eventDispatcher;
772  // otherwise we create one
774  d->createEventDispatcher();
776 
779 
780  d->threadData->eventDispatcher = QCoreApplicationPrivate::eventDispatcher;
781 
782 #if !defined(QT_NO_LIBRARY) && !defined(QT_NO_SETTINGS)
783  if (!coreappdata()->app_libpaths) {
784  // make sure that library paths is initialized
785  libraryPaths();
786  } else {
787  d->appendApplicationPathToLibraryPaths();
788  }
789 #endif
790 
791 #if defined(Q_OS_UNIX) && !(defined(QT_NO_PROCESS))
792  // Make sure the process manager thread object is created in the main
793  // thread.
795 #endif
796 
797 #ifdef QT_EVAL
798  extern void qt_core_eval_init(uint);
799  qt_core_eval_init(d->application_type);
800 #endif
801 
802 #if defined(Q_OS_SYMBIAN) \
803  && defined(Q_CC_NOKIAX86) \
804  && defined(QT_DEBUG)
805 
814  {
815  RLoader loader;
816  CleanupClosePushL(loader);
817  User::LeaveIfError(loader.Connect());
818  User::LeaveIfError(loader.CancelLazyDllUnload());
819  CleanupStack::PopAndDestroy(&loader);
820  }
821 #endif
822 
823  d->processCommandLineArguments();
824 
825  qt_startup_hook();
826 }
double d
Definition: qnumeric_p.h:62
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
#define Q_D(Class)
Definition: qglobal.h:2482
static QFileSystemEntry currentPath()
static void initializeProcessManager()
unsigned int uint
Definition: qglobal.h:996
void moveToThread(QThread *thread)
Changes the thread affinity for this object and its children.
Definition: qobject.cpp:1458
static bool createDirectory(const QFileSystemEntry &entry, bool createParents)
The QCoreApplication class provides an event loop for console Qt applications.
#define Q_ASSERT_X(cond, where, what)
Definition: qglobal.h:1837
static QAbstractEventDispatcher * eventDispatcher
void Q_CORE_EXPORT qt_startup_hook()
static QStringList libraryPaths()
Returns a list of paths that the application will search when dynamically loading libraries...
QObject * parent() const
Returns a pointer to the parent object.
Definition: qobject.h:273
static void initialize()
Definition: qthread.cpp:643
static QCoreApplication * self
Q_CORE_EXPORT bool qt_locale_initialized

◆ installTranslator()

void 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 LanguageChange event for the QCoreApplication instance. A QApplication instance will propagate the event to all toplevel windows, 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.

See also
removeTranslator() translate() QTranslator::load() {Dynamic Translation}

Definition at line 1865 of file qcoreapplication.cpp.

1866 {
1867  if (!translationFile)
1868  return;
1869 
1870  if (!QCoreApplicationPrivate::checkInstance("installTranslator"))
1871  return;
1872  QCoreApplicationPrivate *d = self->d_func();
1873  d->translators.prepend(translationFile);
1874 
1875 #ifndef QT_NO_TRANSLATION_BUILDER
1876  if (translationFile->isEmpty())
1877  return;
1878 #endif
1879 
1881  QCoreApplication::sendEvent(self, &ev);
1882 }
double d
Definition: qnumeric_p.h:62
static bool checkInstance(const char *method)
void prepend(const T &t)
Inserts value at the beginning of the list.
Definition: qlist.h:541
static bool sendEvent(QObject *receiver, QEvent *event)
Sends event event directly to receiver receiver, using the notify() function.
virtual bool isEmpty() const
Returns true if this translator is empty, otherwise returns false.
The QEvent class is the base class of all event classes.
Definition: qcoreevent.h:56

◆ instance()

static QCoreApplication * QCoreApplication::instance ( )
inlinestatic

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

If no instance has been allocated, null is returned.

Definition at line 118 of file qcoreapplication.h.

Referenced by QScriptEngine::availableExtensions(), QDBusConnectionPrivate::checkThread(), QTranslatorPrivate::clear(), QClassFactory::CreateInstanceHelper(), QApplicationPrivate::dispatchEnterLeave(), QEventDispatcherUNIXPrivate::doSelect(), QScrollArea::event(), QEventLoop::exec(), QLibraryInfoPrivate::findConfiguration(), QApplicationPrivate::graphicsSystem(), QScriptEngine::importExtension(), QSqlDatabasePrivate::init(), QDeclarativeEnginePrivate::init(), QBBSystemLocaleData::installSocketNotifiers(), QTestEventLoop::instance(), QFontDatabasePrivate::invalidate(), QAction::isIconVisibleInMenu(), QMenuBar::isNativeMenuBar(), QLibraryInfo::location(), QMenuBarPrivate::macCreateMenuBar(), qAppInstance(), qAppName(), QBBInputContext::QBBInputContext(), qDBusAddTimeout(), qDBusAddWatch(), QDBusDefaultConnection::QDBusDefaultConnection(), qDBusGenerateMetaObjectXml(), qDBusInterfaceFromMetaObject(), qDBusRealAddWatch(), qDBusRemoveTimeout(), qDBusRemoveWatch(), qDBusToggleWatch(), QEventDispatcherGlibPrivate::QEventDispatcherGlibPrivate(), QEventLoop::QEventLoop(), QHostInfoLookupManager::QHostInfoLookupManager(), QMdiArea::QMdiArea(), QNativeWifiEngine::QNativeWifiEngine(), QScriptEnginePrivate::QScriptEnginePrivate(), QSocks5BindStore::QSocks5BindStore(), qt_internal_proc(), qt_mac_set_menubar_icons(), qt_mac_set_native_menubar(), QTest::qWait(), QWSTtyKbPrivate::QWSTtyKbPrivate(), QX11EmbedContainer::QX11EmbedContainer(), QX11EmbedWidget::QX11EmbedWidget(), QDnotifySignalThread::run(), QDBusConnectionPrivate::sendWithReply(), QColor::setColorFromString(), QApplication::setFont(), QAction::setIconVisibleInMenu(), QApplicationPrivate::setPalette_helper(), QScriptEngineDebugger::standardWindow(), QMeeGoGraphicsSystem::switchToMeeGo(), QMeeGoGraphicsSystem::switchToRaster(), QCoreFuriCuri::timerEvent(), QWindowsXPStylePrivate::useXP(), QBBInputContext::~QBBInputContext(), QEvent::~QEvent(), and QTranslator::~QTranslator().

118 { return self; }

◆ libraryPaths()

QStringList QCoreApplication::libraryPaths ( )
static

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

Qt provides default library paths, but they can also be set using a Using qt.conf{qt.conf} file. Paths specified in this file will override default values.

This 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 directory of the application executable (NOT the working directory) is always added, as well as the colon separated entries of the QT_PLUGIN_PATH environment variable.

If you want to iterate over the list, you can use the foreach pseudo-keyword:

foreach (const QString &path, app.libraryPaths())
do_something(path);
See also
setLibraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary, {How to Create Qt Plugins}

Definition at line 2566 of file qcoreapplication.cpp.

Referenced by addLibraryPath(), QScriptEngine::availableExtensions(), getTransformationFunction(), QScriptEngine::importExtension(), init(), QDeclarativeDebugServerPrivate::loadConnectionPlugin(), QDeclarativeInspectorService::loadInspectorPlugin(), removeLibraryPath(), and QFactoryLoader::update().

2567 {
2568  QMutexLocker locker(libraryPathMutex());
2569  if (!coreappdata()->app_libpaths) {
2570  QStringList *app_libpaths = coreappdata()->app_libpaths = new QStringList;
2572 #if defined(Q_OS_SYMBIAN)
2573  if (installPathPlugins.at(1) != QChar(QLatin1Char(':'))) {
2574  qt_symbian_installLibraryPaths(installPathPlugins, *app_libpaths);
2575  }
2576 #else
2577  if (QFile::exists(installPathPlugins)) {
2578  // Make sure we convert from backslashes to slashes.
2579  installPathPlugins = QDir(installPathPlugins).canonicalPath();
2580  if (!app_libpaths->contains(installPathPlugins))
2581  app_libpaths->append(installPathPlugins);
2582  }
2583 #endif
2584 
2585  // If QCoreApplication is not yet instantiated,
2586  // make sure we add the application path when we construct the QCoreApplication
2587  if (self) self->d_func()->appendApplicationPathToLibraryPaths();
2588 
2589  const QByteArray libPathEnv = qgetenv("QT_PLUGIN_PATH");
2590  if (!libPathEnv.isEmpty()) {
2591 #if defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)
2592  QLatin1Char pathSep(';');
2593 #else
2594  QLatin1Char pathSep(':');
2595 #endif
2596  QStringList paths = QString::fromLatin1(libPathEnv).split(pathSep, QString::SkipEmptyParts);
2597  for (QStringList::const_iterator it = paths.constBegin(); it != paths.constEnd(); ++it) {
2598  QString canonicalPath = QDir(*it).canonicalPath();
2599  if (!canonicalPath.isEmpty()
2600  && !app_libpaths->contains(canonicalPath)) {
2601  app_libpaths->append(canonicalPath);
2602  }
2603  }
2604  }
2605  }
2606  return *(coreappdata()->app_libpaths);
2607 }
The QDir class provides access to directory structures and their contents.
Definition: qdir.h:58
Q_CORE_EXPORT QByteArray qgetenv(const char *varName)
const QChar at(int i) const
Returns the character at the given index position in the string.
Definition: qstring.h:698
#define it(className, varName)
The QByteArray class provides an array of bytes.
Definition: qbytearray.h:135
const_iterator constBegin() const
Returns a const STL-style iterator pointing to the first item in the list.
Definition: qlist.h:269
The QString class provides a Unicode character string.
Definition: qstring.h:83
The QChar class provides a 16-bit Unicode character.
Definition: qchar.h:72
bool exists() const
Returns true if the file specified by fileName() exists; otherwise returns false. ...
Definition: qfile.cpp:626
friend class const_iterator
Definition: qlist.h:264
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
QBool contains(const QString &str, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the list contains the string str; otherwise returns false.
Definition: qstringlist.h:172
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
static QString location(LibraryLocation)
Returns the location specified by loc.
QString canonicalPath() const
Returns the canonical path, i.e.
Definition: qdir.cpp:642
bool isEmpty() const
Returns true if the byte array has size 0; otherwise returns false.
Definition: qbytearray.h:421
QStringList split(const QString &sep, SplitBehavior behavior=KeepEmptyParts, Qt::CaseSensitivity cs=Qt::CaseSensitive) const Q_REQUIRED_RESULT
Splits the string into substrings wherever sep occurs, and returns the list of those strings...
Definition: qstring.cpp:6526
The QLatin1Char class provides an 8-bit ASCII/Latin-1 character.
Definition: qchar.h:55
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the list...
Definition: qlist.h:272

◆ 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:

  1. Reimplementing paintEvent(), mousePressEvent() and so on. This is the commonest, 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. 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.

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

Reimplemented in QApplication.

Definition at line 1016 of file qcoreapplication.cpp.

Referenced by QApplication::isLeftToRight(), and notifyInternal().

1017 {
1019  // no events are delivered after ~QCoreApplication() has started
1021  return true;
1022 
1023  if (receiver == 0) { // serious error
1024  qWarning("QCoreApplication::notify: Unexpected null receiver");
1025  return true;
1026  }
1027 
1028 #ifndef QT_NO_DEBUG
1029  d->checkReceiverThread(receiver);
1030 #endif
1031 
1032  return receiver->isWidgetType() ? false : d->notify_helper(receiver, event);
1033 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
Q_CORE_EXPORT void qWarning(const char *,...)
The QCoreApplication class provides an event loop for console Qt applications.
bool isWidgetType() const
Returns true if the object is a widget; otherwise returns false.
Definition: qobject.h:146

◆ notifyInternal()

bool QCoreApplication::notifyInternal ( QObject receiver,
QEvent event 
)
private
Warning
This function is not part of the public interface.

This function is here to make it possible for Qt extensions to hook into event notification without subclassing QApplication

Definition at line 928 of file qcoreapplication.cpp.

Referenced by sendEvent().

929 {
930  // Make it possible for Qt Jambi and QSA to hook into events even
931  // though QApplication is subclassed...
932  bool result = false;
933  void *cbdata[] = { receiver, event, &result };
935  return result;
936  }
937 
938  // Qt enforces the rule that events can only be sent to objects in
939  // the current thread, so receiver->d_func()->threadData is
940  // equivalent to QThreadData::current(), just without the function
941  // call overhead.
942  QObjectPrivate *d = receiver->d_func();
943  QThreadData *threadData = d->threadData;
944  ++threadData->loopLevel;
945 
946 #ifdef QT_JAMBI_BUILD
947  int deleteWatch = 0;
948  int *oldDeleteWatch = QObjectPrivate::setDeleteWatch(d, &deleteWatch);
949 
950  bool inEvent = d->inEventHandler;
951  d->inEventHandler = true;
952 #endif
953 
954  bool returnValue;
955  QT_TRY {
956  returnValue = notify(receiver, event);
957  } QT_CATCH (...) {
958  --threadData->loopLevel;
959  QT_RETHROW;
960  }
961 
962 #ifdef QT_JAMBI_BUILD
963  // Restore the previous state if the object was not deleted..
964  if (!deleteWatch) {
965  d->inEventHandler = inEvent;
966  }
967  QObjectPrivate::resetDeleteWatch(d, oldDeleteWatch, deleteWatch);
968 #endif
969  --threadData->loopLevel;
970  return returnValue;
971 }
double d
Definition: qnumeric_p.h:62
bool event(QEvent *)
This virtual function receives events to an object and should return true if the event e was recogniz...
QThreadData * threadData
Definition: qobject_p.h:195
#define QT_RETHROW
Definition: qglobal.h:1539
virtual bool notify(QObject *, QEvent *)
Sends event to receiver: {receiver}->event(event).
int loopLevel
Definition: qthread_p.h:263
static bool activateCallbacks(Callback, void **)
Definition: qglobal.cpp:3653
#define QT_CATCH(A)
Definition: qglobal.h:1537
uint inEventHandler
Definition: qobject.h:102
#define QT_TRY
Definition: qglobal.h:1536

◆ organizationDomain()

static QString QCoreApplication::organizationDomain ( )
static

Referenced by setOrganizationDomain().

◆ organizationName()

static QString QCoreApplication::organizationName ( )
static

◆ postEvent() [1/2]

void QCoreApplication::postEvent ( QObject receiver,
QEvent event 
)
static

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 processed in the order posted. For more control over the processing order, use the postEvent() overload below, which takes a priority argument. This function posts all event with a Qt::NormalEventPriority.

Note
This class or function is threadsafe.
See also
sendEvent(), notify(), sendPostedEvents()

Definition at line 1315 of file qcoreapplication.cpp.

Referenced by QMetaObject::activate(), QEventDispatcherMacPrivate::activateTimer(), QNetworkReplyImplPrivate::backendNotify(), QTranslatorPrivate::clear(), QAxWidget::createHostWindow(), QObject::deleteLater(), QApplicationPrivate::emitLastWindowClosed(), QEventDispatcherWin32::event(), QApplication::event(), QDeclarativeSystemPalette::eventFilter(), QGraphicsScene::eventFilter(), QDeclarativeWorkerScriptEngine::executeUrl(), QWidgetPrivate::init(), QGraphicsLayout::invalidate(), QMetaMethod::invoke(), QWidgetPrivate::isBackgroundInherited(), QFutureWatcherBasePrivate::postCallOutEvent(), QScriptDebuggerFrontendPrivate::postEvent(), QScriptDebuggerBackendPrivate::postEvent(), QDBusConnectionPrivate::postEventToThread(), QDeclarativePixmapReply::postReply(), QDeclarativePixmapReaderThreadObject::processJobs(), QDeclarativeXmlQueryThreadObject::processJobs(), qt_fast_timer_proc(), qt_mac_display_change_callbk(), qt_post_window_change_event(), QtWndProc(), queued_activate(), QEventDispatcherWin32Private::registerTimer(), QDeclarativeWorkerScriptEngine::removeWorkerScript(), QDeclarativeWorkerScriptEnginePrivate::reportScriptException(), QSettingsPrivate::requestUpdate(), QDialogPrivate::resetModalitySetByOpen(), QNetworkReplyImplPrivate::resumeNotificationHandling(), QDnotifySignalThread::run(), QDeclarativePathViewPrivate::scheduleLayout(), QDeclarativeGridViewPrivate::scheduleLayout(), QDeclarativeListViewPrivate::scheduleLayout(), QSoftKeyManager::sendKeyEvent(), QDeclarativeWorkerScriptEngine::sendMessage(), QDeclarativeWorkerScriptEnginePrivate::sendMessage(), sendUpdateRequest(), QWidget::setParent(), QObjectPrivate::setParent_helper(), QWidget::setVisible(), QDeclarativeListModelWorkerAgent::sync(), QDeclarativeFlickable::timerEvent(), QETWidget::translateConfigEvent(), QLayout::update(), QWidget::update(), QGraphicsWidget::updateGeometry(), QWidgetPrivate::updateGeometry_helper(), QSoftKeyManager::updateSoftKeys(), QX11Data::xdndHandleBadwindow(), and QDeclarativeWorkerScriptEngine::~QDeclarativeWorkerScriptEngine().

1316 {
1317  postEvent(receiver, event, Qt::NormalEventPriority);
1318 }
static void postEvent(QObject *receiver, QEvent *event)
Adds the event event, with the object receiver as the receiver of the event, to an event queue and re...

◆ postEvent() [2/2]

void QCoreApplication::postEvent ( QObject receiver,
QEvent event,
int  priority 
)
static

Definition at line 1350 of file qcoreapplication.cpp.

1351 {
1352  if (receiver == 0) {
1353  qWarning("QCoreApplication::postEvent: Unexpected null receiver");
1354  delete event;
1355  return;
1356  }
1357 
1358  QThreadData * volatile * pdata = &receiver->d_func()->threadData;
1359  QThreadData *data = *pdata;
1360  if (!data) {
1361  // posting during destruction? just delete the event to prevent a leak
1362  delete event;
1363  return;
1364  }
1365 
1366  // lock the post event mutex
1367  data->postEventList.mutex.lock();
1368 
1369  // if object has moved to another thread, follow it
1370  while (data != *pdata) {
1371  data->postEventList.mutex.unlock();
1372 
1373  data = *pdata;
1374  if (!data) {
1375  // posting during destruction? just delete the event to prevent a leak
1376  delete event;
1377  return;
1378  }
1379 
1380  data->postEventList.mutex.lock();
1381  }
1382 
1383  QMutexUnlocker locker(&data->postEventList.mutex);
1384 
1385  // if this is one of the compressible events, do compression
1386  if (receiver->d_func()->postedEvents
1387  && self && self->compressEvent(event, receiver, &data->postEventList)) {
1388  return;
1389  }
1390 
1391  if (event->type() == QEvent::DeferredDelete && data == QThreadData::current()) {
1392  // remember the current running eventloop for DeferredDelete
1393  // events posted in the receiver's thread
1394  event->d = reinterpret_cast<QEventPrivate *>(quintptr(data->loopLevel));
1395  }
1396 
1397  // delete the event on exceptions to protect against memory leaks till the event is
1398  // properly owned in the postEventList
1399  QScopedPointer<QEvent> eventDeleter(event);
1400  data->postEventList.addEvent(QPostEvent(receiver, event, priority));
1401  eventDeleter.take();
1402  event->posted = true;
1403  ++receiver->d_func()->postedEvents;
1404  data->canWait = false;
1405  locker.unlock();
1406 
1407  if (data->eventDispatcher)
1408  data->eventDispatcher->wakeUp();
1409 }
QIntegerForSizeof< void * >::Unsigned quintptr
Definition: qglobal.h:986
void lock()
Locks the mutex.
Definition: qmutex.cpp:151
bool event(QEvent *)
This virtual function receives events to an object and should return true if the event e was recogniz...
The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon dest...
QMutex mutex
Definition: qthread_p.h:109
Q_CORE_EXPORT void qWarning(const char *,...)
static const char * data(const QByteArray &arr)
QPostEventList postEventList
Definition: qthread_p.h:266
void unlock()
Unlocks the mutex.
Definition: qmutex.cpp:296
static QThreadData * current()
Type type() const
Returns the event type.
Definition: qcoreevent.h:303

◆ processEvents() [1/2]

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

Processes all pending events for the calling thread according to the specified flags until there are no more events to process.

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

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

Calling this function processes events only for the calling thread.

Note
This class or function is threadsafe.
See also
exec(), QTimer, QEventLoop::processEvents(), flush(), sendPostedEvents()

Definition at line 1136 of file qcoreapplication.cpp.

Referenced by Maemo::IcdPrivate::addrinfo(), QIBaseDriver::close(), QScript::TimeoutCheckerProxy::didTimeOut(), QScriptDebuggerPrivate::executeConsoleCommand(), QScriptDebuggerAgent::positionChange(), QPlatformEventLoopIntegration::processEvents(), QOleDropSource::QueryContinueDrag(), QTest::qWait(), QTest::qWaitForWindowShown(), Maemo::IcdPrivate::scan(), QProgressDialog::setValue(), QWidgetPrivate::show_helper(), Maemo::IcdPrivate::state(), Maemo::IcdPrivate::statistics(), QAudioInputPrivate::~QAudioInputPrivate(), and QAudioOutputPrivate::~QAudioOutputPrivate().

1137 {
1139  if (!data->eventDispatcher)
1140  return;
1141  if (flags & QEventLoop::DeferredDeletion)
1143  data->eventDispatcher->processEvents(flags);
1144 }
static const char * data(const QByteArray &arr)
static void sendPostedEvents()
virtual bool processEvents(QEventLoop::ProcessEventsFlags flags)=0
Processes pending events that match flags until there are no more events to process.
static QThreadData * current()
QAbstractEventDispatcher * eventDispatcher
Definition: qthread_p.h:264

◆ processEvents() [2/2]

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

Definition at line 1165 of file qcoreapplication.cpp.

1166 {
1168  if (!data->eventDispatcher)
1169  return;
1170  QElapsedTimer start;
1171  start.start();
1172  if (flags & QEventLoop::DeferredDeletion)
1175  if (start.elapsed() > maxtime)
1176  break;
1177  if (flags & QEventLoop::DeferredDeletion)
1179  }
1180 }
The QElapsedTimer class provides a fast way to calculate elapsed times.
Definition: qelapsedtimer.h:53
qint64 elapsed() const
Returns the number of milliseconds since this QElapsedTimer was last started.
static const char * data(const QByteArray &arr)
static void sendPostedEvents()
virtual bool processEvents(QEventLoop::ProcessEventsFlags flags)=0
Processes pending events that match flags until there are no more events to process.
static QThreadData * current()
QAbstractEventDispatcher * eventDispatcher
Definition: qthread_p.h:264
void start()
Starts this timer.

◆ quit

void QCoreApplication::quit ( )
staticslot

Tells the application to exit with return code 0 (success).

Equivalent to calling QCoreApplication::exit(0).

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

Example:

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, SIGNAL(clicked()), &app, SLOT(quit()));
See also
exit(), aboutToQuit(), QApplication::lastWindowClosed()

Definition at line 1818 of file qcoreapplication.cpp.

Referenced by QWidgetPrivate::close_helper(), event(), QApplicationPrivate::globalAppleEventProcessor(), QApplicationPrivate::globalEventProcessor(), QBBNavigatorEventHandler::handleExit(), QtWndProc(), QCoreFuriCuri::timerEvent(), and QWidget::~QWidget().

1819 {
1820  exit(0);
1821 }
static void exit(int retcode=0)
Tells the application to exit with a return code.

◆ removeLibraryPath()

void QCoreApplication::removeLibraryPath ( const QString path)
static

Removes path from the library path list.

If path is empty or not in the path list, the list is not changed.

See also
addLibraryPath(), libraryPaths(), setLibraryPaths()

Definition at line 2674 of file qcoreapplication.cpp.

2675 {
2676  if (path.isEmpty())
2677  return;
2678 
2679  QMutexLocker locker(libraryPathMutex());
2680 
2681  // make sure that library paths is initialized
2682  libraryPaths();
2683 
2684  QString canonicalPath = QDir(path).canonicalPath();
2685  coreappdata()->app_libpaths->removeAll(canonicalPath);
2687 }
The QDir class provides access to directory structures and their contents.
Definition: qdir.h:58
static void refreshAll()
The QString class provides a Unicode character string.
Definition: qstring.h:83
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
static QStringList libraryPaths()
Returns a list of paths that the application will search when dynamically loading libraries...
QString canonicalPath() const
Returns the canonical path, i.e.
Definition: qdir.cpp:642

◆ removePostedEvents() [1/2]

void QCoreApplication::removePostedEvents ( QObject receiver)
static

Removes all events 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.

Note
This class or function is threadsafe.

Definition at line 1642 of file qcoreapplication.cpp.

1643 {
1644  removePostedEvents(receiver, 0);
1645 }
removePostedEvents
Removes all events of the given eventType that were posted using postEvent() for receiver.

◆ removePostedEvents() [2/2]

void QCoreApplication::removePostedEvents ( QObject receiver,
int  eventType 
)
static

Definition at line 1669 of file qcoreapplication.cpp.

1670 {
1671 #ifdef QT3_SUPPORT
1672  if (eventType == QEvent::ChildInserted)
1673  eventType = QEvent::ChildInsertedRequest;
1674 #endif
1675 
1676  QThreadData *data = receiver ? receiver->d_func()->threadData : QThreadData::current();
1677  QMutexLocker locker(&data->postEventList.mutex);
1678 
1679  // the QObject destructor calls this function directly. this can
1680  // happen while the event loop is in the middle of posting events,
1681  // and when we get here, we may not have any more posted events
1682  // for this object.
1683  if (receiver && !receiver->d_func()->postedEvents)
1684  return;
1685 
1686  //we will collect all the posted events for the QObject
1687  //and we'll delete after the mutex was unlocked
1688  QVarLengthArray<QEvent*> events;
1689  int n = data->postEventList.size();
1690  int j = 0;
1691 
1692  for (int i = 0; i < n; ++i) {
1693  const QPostEvent &pe = data->postEventList.at(i);
1694 
1695  if ((!receiver || pe.receiver == receiver)
1696  && (pe.event && (eventType == 0 || pe.event->type() == eventType))) {
1697  --pe.receiver->d_func()->postedEvents;
1698 #ifdef QT3_SUPPORT
1699  if (pe.event->type() == QEvent::ChildInsertedRequest)
1700  pe.receiver->d_func()->pendingChildInsertedEvents.clear();
1701 #endif
1702  pe.event->posted = false;
1703  events.append(pe.event);
1704  const_cast<QPostEvent &>(pe).event = 0;
1705  } else if (!data->postEventList.recursion) {
1706  if (i != j)
1707  data->postEventList.swap(i, j);
1708  ++j;
1709  }
1710  }
1711 
1712 #ifdef QT_DEBUG
1713  if (receiver && eventType == 0) {
1714  Q_ASSERT(!receiver->d_func()->postedEvents);
1715  }
1716 #endif
1717 
1718  if (!data->postEventList.recursion) {
1719  // truncate list
1720  data->postEventList.erase(data->postEventList.begin() + j, data->postEventList.end());
1721  }
1722 
1723  locker.unlock();
1724  for (int i = 0; i < events.count(); ++i) {
1725  delete events[i];
1726  }
1727 }
iterator begin()
Returns an STL-style iterator pointing to the first item in the list.
Definition: qlist.h:267
bool event(QEvent *)
This virtual function receives events to an object and should return true if the event e was recogniz...
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
void append(const T &t)
QMutex mutex
Definition: qthread_p.h:109
iterator end()
Returns an STL-style iterator pointing to the imaginary item after the last item in the list...
Definition: qlist.h:270
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
static const char * data(const QByteArray &arr)
QPostEventList postEventList
Definition: qthread_p.h:266
ushort posted
Definition: qcoreevent.h:319
int count() const
QEvent * event
Definition: qthread_p.h:78
iterator erase(iterator pos)
Removes the item associated with the iterator pos from the list, and returns an iterator to the next ...
Definition: qlist.h:464
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101
QObject * receiver
Definition: qthread_p.h:77
int size() const
Returns the number of items in the list.
Definition: qlist.h:137
static QThreadData * current()
Type type() const
Returns the event type.
Definition: qcoreevent.h:303
void swap(QList< T > &other)
Swaps list other with this list.
Definition: qlist.h:129

◆ removeTranslator()

void 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.)

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

Definition at line 1892 of file qcoreapplication.cpp.

Referenced by QTranslator::~QTranslator().

1893 {
1894  if (!translationFile)
1895  return;
1896  if (!QCoreApplicationPrivate::checkInstance("removeTranslator"))
1897  return;
1898  QCoreApplicationPrivate *d = self->d_func();
1899  if (d->translators.removeAll(translationFile) && !self->closingDown()) {
1901  QCoreApplication::sendEvent(self, &ev);
1902  }
1903 }
double d
Definition: qnumeric_p.h:62
static bool checkInstance(const char *method)
static bool sendEvent(QObject *receiver, QEvent *event)
Sends event event directly to receiver receiver, using the notify() function.
The QEvent class is the base class of all event classes.
Definition: qcoreevent.h:56
int removeAll(const T &t)
Removes all occurrences of value in the list and returns the number of entries removed.
Definition: qlist.h:770

◆ sendEvent()

bool QCoreApplication::sendEvent ( QObject receiver,
QEvent event 
)
inlinestatic

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 230 of file qcoreapplication.h.

Referenced by QGraphicsScenePrivate::_q_polishItems(), QEventDispatcherWin32Private::activateEventNotifier(), QEventDispatcherUNIX::activateSocketNotifiers(), QTimerInfoList::activateTimers(), axc_FilterProc(), QAbstractItemViewPrivate::checkMouseMove(), QGraphicsWidget::close(), QWidgetPrivate::close_helper(), QMdiSubWindow::closeEvent(), QDeclarativeTextEdit::closeSoftwareInputPanel(), QDeclarativeTextInput::closeSoftwareInputPanel(), QGraphicsProxyWidget::contextMenuEvent(), QDialog::contextMenuEvent(), QGraphicsView::contextMenuEvent(), QGestureManager::deliverEvents(), QApplicationPrivate::dispatchEnterLeave(), QShortcutMap::dispatchEvent(), do_size_hints(), QGraphicsProxyWidget::dragEnterEvent(), QGraphicsView::dragEnterEvent(), QOleDropTarget::DragLeave(), QGraphicsProxyWidget::dragLeaveEvent(), QGraphicsView::dragLeaveEvent(), QGraphicsProxyWidget::dragMoveEvent(), QGraphicsView::dragMoveEvent(), QOleDropTarget::DragOver(), QOleDropTarget::Drop(), QGraphicsProxyWidget::dropEvent(), QGraphicsView::dropEvent(), effectiveState(), QWidget::ensurePolished(), QWorkspaceTitleBar::enterEvent(), QApplicationPrivate::enterModal(), QGraphicsProxyWidget::event(), QEventDispatcherWin32::event(), QMenuBar::event(), QMdiArea::event(), QSystemTrayIconSys::event(), QGraphicsView::event(), QApplication::event(), QWidget::event(), QCompleter::eventFilter(), QWhatsThisPrivate::eventFilter(), QGraphicsView::focusInEvent(), QGraphicsView::focusOutEvent(), QApplicationPrivate::globalEventProcessor(), handle_xdnd_position(), QWidgetPrivate::handleSoftwareInputPanel(), QWidgetPrivate::hide_helper(), QWidgetPrivate::hideChildren(), QWidgetPrivate::init(), QGraphicsView::inputMethodEvent(), QGraphicsWidget::insertAction(), QWidget::insertAction(), installTranslator(), QAxServerBase::internalCreate(), QGraphicsWidget::itemChange(), QMenu::keyPressEvent(), QGraphicsView::keyPressEvent(), QGraphicsView::keyReleaseEvent(), QApplicationPrivate::leaveModal(), QWidget::lower(), QX11Data::motifdndHandle(), QGraphicsView::mouseDoubleClickEvent(), QMenuPrivate::mouseEventTaken(), QGraphicsViewPrivate::mouseMoveEventHandler(), QGraphicsView::mousePressEvent(), QWhatsThat::mouseReleaseEvent(), QGraphicsView::mouseReleaseEvent(), QObjectPrivate::moveToThread_helper(), QApplication::notify(), QWhatsThisPrivate::notifyToplevels(), QAbstractItemViewPrivate::openEditor(), QDeclarativeTextEdit::openSoftwareInputPanel(), QDeclarativeTextInput::openSoftwareInputPanel(), QWidget::overrideWindowState(), QWidgetPrivate::propagatePaletteChange(), qstring_to_xtp(), qt_grab_cursor(), qt_internal_proc(), qt_mac_mouse_inside_answer_rect(), qt_mac_send_posted_gl_updates(), qt_mac_socket_callback(), QAxClientSite::qt_metacall(), qt_tablet_cleanup_wce(), qt_try_modal(), qt_x11_recreateWidget(), QtWndProc(), QWhatsThisPrivate::QWhatsThisPrivate(), QApplication::qwsProcessEvent(), QWidget::raise(), QGraphicsWidget::removeAction(), QWidget::removeAction(), QGraphicsProxyWidgetPrivate::removeSubFocusHelper(), removeTranslator(), QETWidget::repolishStyle(), QWidget::resetInputContext(), QWidgetPrivate::scroll_sys(), QWidgetPrivate::scrollChildren(), QActionPrivate::sendDataChanged(), QOleDropTarget::sendDragEnterEvent(), QInputContext::sendEvent(), QGraphicsScenePrivate::sendEvent(), QDeclarativeFlickable::sendMouseEvent(), QApplicationPrivate::sendMouseEvent(), QWidgetPrivate::sendPendingMoveAndResizeEvents(), QCoreApplicationPrivate::sendPostedEvents(), sendResizeEvents(), QEventDispatcherWin32Private::sendTimerEvent(), sendUpdateRequest(), QGraphicsProxyWidgetPrivate::sendWidgetKeyEvent(), QGraphicsScenePrivate::setActivePanelHelper(), QWidget::setAttribute(), QGraphicsWidget::setContentsMargins(), QWidget::setContentsMargins(), QMenuBarPrivate::setCurrentAction(), QWidget::setCursor(), QWidgetPrivate::setEnabled_helper(), QGraphicsScene::setFocus(), QWidget::setFocus(), QApplicationPrivate::setFocusWidget(), QApplication::setFont(), QGraphicsWidget::setGeometry(), QWidgetPrivate::setGeometry_sys(), QApplication::setLayoutDirection(), QGraphicsWidgetPrivate::setLayoutDirection_helper(), QWidgetPrivate::setLayoutDirection_helper(), QWidgetPrivate::setLocale_helper(), QWidgetPrivate::setModal_sys(), QApplicationPrivate::setPalette_helper(), QWidget::setParent(), QObjectPrivate::setParent_helper(), QObject::setProperty(), QGraphicsView::setScene(), QGraphicsWidget::setStyle(), QApplication::setStyle(), QGraphicsScene::setStyle(), QWidgetPrivate::setStyle_helper(), QWidget::setToolTip(), QDialog::setVisible(), QWidget::setVisible(), QApplication::setWindowIcon(), QWidgetPrivate::setWindowIcon_helper(), QWidget::setWindowIconText(), QWidget::setWindowModified(), QWidget::setWindowState(), QWidget::setWindowTitle(), QWidgetPrivate::setWinId(), QWidgetPrivate::show_helper(), QMdiSubWindowPrivate::showButtonsInMenuBar(), QActionPrivate::showStatusText(), sm_dieCallback(), socketNotifierSourceDispatch(), QWidget::stackUnder(), QAccessibleHeader::text(), QAxServerBase::TranslateAcceleratorW(), QETWidget::translateConfigEvent(), QShortcutMap::tryShortcutEvent(), QWidget::unsetCursor(), update_toolbar_style(), QGraphicsWidgetPrivate::updateFont(), QGraphicsScenePrivate::updateFont(), QWidgetPrivate::updateFont(), QMenuBarPrivate::updateGeometries(), QGraphicsWidgetPrivate::updatePalette(), QGraphicsScenePrivate::updatePalette(), QStyleSheetStyle::updateStyleSheetFont(), QGtkStyleUpdateScheduler::updateTheme(), updateWidgets(), QHeaderView::viewportEvent(), QGraphicsView::viewportEvent(), QAbstractItemView::viewportEvent(), QAbstractScrollArea::wheelEvent(), QSystemTrayIconSys::wheelEvent(), QGraphicsView::wheelEvent(), QX11EmbedWidget::x11Event(), QApplication::x11ProcessEvent(), QX11Data::xdndHandleDrop(), QX11Data::xdndHandleLeave(), QApplication::~QApplication(), QObjectPrivate::~QObjectPrivate(), and QWidget::~QWidget().

231 { if (event) event->spont = false; return self ? self->notifyInternal(receiver, event) : false; }

◆ sendPostedEvents() [1/2]

void QCoreApplication::sendPostedEvents ( QObject receiver,
int  event_type 
)
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 null, 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 same thread as its QObject parameter, receiver.
See also
flush(), postEvent()

Definition at line 1481 of file qcoreapplication.cpp.

1482 {
1484 
1485  QCoreApplicationPrivate::sendPostedEvents(receiver, event_type, data);
1486 }
static void sendPostedEvents(QObject *receiver, int event_type, QThreadData *data)
static const char * data(const QByteArray &arr)
static QThreadData * current()

◆ sendPostedEvents() [2/2]

void QCoreApplication::sendPostedEvents ( )
inlinestatic

◆ sendSpontaneousEvent()

bool QCoreApplication::sendSpontaneousEvent ( QObject receiver,
QEvent event 
)
inlinestaticprivate

◆ setApplicationName()

void QCoreApplication::setApplicationName ( const QString application)
static

Definition at line 2468 of file qcoreapplication.cpp.

2469 {
2470  coreappdata()->application = application;
2471 }

◆ setApplicationVersion()

void QCoreApplication::setApplicationVersion ( const QString version)
static

Definition at line 2499 of file qcoreapplication.cpp.

2500 {
2501  coreappdata()->applicationVersion = version;
2502 }

◆ setAttribute()

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

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

One of the attributes that can be set with this method is Qt::AA_ImmediateWidgetCreation. It tells Qt to create toplevel windows immediately. Normally, resources for widgets are allocated on demand to improve efficiency and minimize resource usage. Therefore, if it is important to minimize resource consumption, do not set this attribute.

See also
testAttribute()

Definition at line 888 of file qcoreapplication.cpp.

Referenced by QMenuBarPrivate::init(), QMenuBarPrivate::macCreateMenuBar(), qt_mac_set_menubar_icons(), and qt_mac_set_native_menubar().

889 {
890  if (on)
891  QCoreApplicationPrivate::attribs |= 1 << attribute;
892  else
893  QCoreApplicationPrivate::attribs &= ~(1 << attribute);
894 #ifdef Q_OS_MAC
895  // Turn on the no native menubar here, since we used to
896  // do this implicitly. We DO NOT flip it off if someone sets
897  // it to false.
898  // Ideally, we'd have magic that would be something along the lines of
899  // "follow MacPluginApplication" unless explicitly set.
900  // Considering this attribute isn't only at the beginning
901  // it's unlikely it will ever be a problem, but I want
902  // to have the behavior documented here.
903  if (attribute == Qt::AA_MacPluginApplication && on
906  }
907 #endif
908 }
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.

◆ setEventFilter()

QCoreApplication::EventFilter QCoreApplication::setEventFilter ( QCoreApplication::EventFilter  filter)

Replaces the event filter function for the QCoreApplication with filter and returns the pointer to the replaced event filter function.

Only the current event filter function is called. If you want to use both filter functions, save the replaced EventFilter in a place where yours can call it.

The event filter function set here is called for all messages received by all threads meant for all Qt objects. It is not called for messages that are not meant for Qt objects.

The event filter function should return true if the message should be filtered, (i.e. stopped). It should return false to allow processing the message to continue.

By default, no event filter function is set (i.e., this function returns a null EventFilter the first time it is called).

Note
The filter function set here receives native messages, i.e. MSG or XEvent structs, that are going to Qt objects. It is called by QCoreApplication::filterEvent(). If the filter function returns false to indicate the message should be processed further, the native message can then be translated into a QEvent and handled by the standard Qt event filering, e.g. QObject::installEventFilter().
The filter function set here is different form the filter function set via QAbstractEventDispatcher::setEventFilter(), which gets all messages received by its thread, even messages meant for objects that are not handled by Qt.
See also
QObject::installEventFilter(), QAbstractEventDispatcher::setEventFilter()

Definition at line 2772 of file qcoreapplication.cpp.

Referenced by QX11EmbedContainer::QX11EmbedContainer().

2773 {
2775  EventFilter old = d->eventFilter;
2776  d->eventFilter = filter;
2777  return old;
2778 }
double d
Definition: qnumeric_p.h:62
#define Q_D(Class)
Definition: qglobal.h:2482
The QCoreApplication class provides an event loop for console Qt applications.
bool(* EventFilter)(void *message, long *result)
A function with the following signature that can be used as an event filter:
QFuture< void > filter(Sequence &sequence, FilterFunction filterFunction)

◆ setLibraryPaths()

void QCoreApplication::setLibraryPaths ( const QStringList paths)
static

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.

In Symbian this function is only useful for setting paths for finding Qt extension plugin stubs, since the OS can only load libraries from the /sys/bin directory.

See also
libraryPaths(), addLibraryPath(), removeLibraryPath(), QLibrary

Definition at line 2623 of file qcoreapplication.cpp.

2624 {
2625  QMutexLocker locker(libraryPathMutex());
2626  if (!coreappdata()->app_libpaths)
2627  coreappdata()->app_libpaths = new QStringList;
2628  *(coreappdata()->app_libpaths) = paths;
2629  locker.unlock();
2631 }
static void refreshAll()
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
The QMutexLocker class is a convenience class that simplifies locking and unlocking mutexes...
Definition: qmutex.h:101

◆ setOrganizationDomain()

void QCoreApplication::setOrganizationDomain ( const QString orgDomain)
static

Definition at line 2442 of file qcoreapplication.cpp.

2443 {
2444  coreappdata()->orgDomain = orgDomain;
2445 }

◆ setOrganizationName()

void QCoreApplication::setOrganizationName ( const QString orgName)
static

Definition at line 2411 of file qcoreapplication.cpp.

2412 {
2413  coreappdata()->orgName = orgName;
2414 }

◆ 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 1096 of file qcoreapplication.cpp.

Referenced by QCursor::QCursor(), qt_cleanup(), qt_mac_update_os_settings(), QtWndProc(), and QApplicationPrivate::x11_apply_settings().

1097 {
1099 }

◆ testAttribute()

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

◆ translate() [1/2]

QString QCoreApplication::translate ( const char *  context,
const char *  key,
const char *  disambiguation = 0,
Encoding  encoding = CodecForTr 
)
static

Definition at line 1908 of file qcoreapplication.cpp.

Referenced by QNetworkReplyImplPrivate::_q_networkSessionFailed(), QPrintPreviewDialogPrivate::_q_print(), QNetworkReplyImplPrivate::_q_startOperation(), QOCIDriver::beginTransaction(), QOCIDriver::commitTransaction(), QAxServerBase::createMenu(), QHttpNetworkConnectionPrivate::errorDetail(), QMessageBox::event(), QDB2Result::exec(), QOCIResult::exec(), QSQLiteResult::exec(), QSymSQLResult::exec(), QODBCResult::exec(), QOCICols::execBatch(), QDB2Result::fetch(), QMYSQLResult::fetch(), QODBCResult::fetch(), QDB2Result::fetchFirst(), QODBCResult::fetchFirst(), QODBCResult::fetchLast(), QDB2Result::fetchNext(), QMYSQLResult::fetchNext(), QODBCResult::fetchNext(), QSQLiteResultPrivate::fetchNext(), QSymSQLResultPrivate::fetchNext(), QODBCResult::fetchPrevious(), QSQLite2ResultPrivate::finalize(), QHostInfoAgent::fromName(), fromScriptValue(), QScript::functionQsTr(), QScript::functionQsTranslate(), getFontWeight(), QOCIResult::gotoNext(), QScriptDebuggerStackModel::headerData(), QScriptDebuggerLocalsModel::headerData(), QScriptBreakpointsModel::headerData(), QPPDOptionsModel::headerData(), QMessageBoxPrivate::hideSpecial(), QDirModel::index(), QPrintPreviewDialogPrivate::init(), QSymSQLResultPrivate::initColumns(), QIBaseDriverPrivate::isError(), QIBaseResultPrivate::isError(), QtFontStyle::Key::Key(), QDeclarativeJS::Lexer::lex(), QNetworkAccessFileBackend::loadFileInfo(), QHostInfo::lookupHost(), QDB2Result::nextResult(), QMYSQLResult::nextResult(), QODBCResult::nextResult(), QNetworkAccessCacheBackend::open(), QNetworkAccessFileBackend::open(), QDB2Result::prepare(), QOCIResult::prepare(), QSQLiteResult::prepare(), QSymSQLResult::prepare(), QPSQLResult::prepare(), QODBCResult::prepare(), QPSQLResultPrivate::processResults(), QAbstractPageSetupDialog::QAbstractPageSetupDialog(), QAbstractPrintDialog::QAbstractPrintDialog(), QDisabledNetworkReply::QDisabledNetworkReply(), QNetworkReplyDataImpl::QNetworkReplyDataImpl(), QNetworkReplyFileImpl::QNetworkReplyFileImpl(), qtTrId(), QNetworkAccessFileBackend::readMoreFromFile(), QDB2Result::reset(), QSQLite2Result::reset(), QMYSQLResult::reset(), QODBCResult::reset(), QOCIDriver::rollbackTransaction(), QDeclarativeVME::run(), QDeclarativeCompiledBindingsPrivate::run(), QDeclarativeJS::Lexer::scanRegExp(), sendPostedEvents(), QSystemSemaphorePrivate::setErrorString(), QDeclarativeXmlListModel::setQuery(), QPrintPreviewDialogPrivate::setupActions(), styleStringHelper(), QMetaObject::tr(), QMetaObject::trUtf8(), QFileIconProvider::type(), QMenuBarPrivate::updateCornerWidgetToolBar(), QNetworkAccessFileBackend::uploadReadyReadSlot(), QMYSQLResult::virtual_hook(), and QFontDatabase::writingSystemName().

1910 {
1911  return translate(context, sourceText, disambiguation, encoding, -1);
1912 }
static QString translate(const char *context, const char *key, const char *disambiguation=0, Encoding encoding=CodecForTr)

◆ translate() [2/2]

QString QCoreApplication::translate ( const char *  context,
const char *  sourceText,
const char *  disambiguation,
Encoding  encoding,
int  n 
)
static

Returns the translation text for sourceText, by querying the installed translation files.

Note
This class or function is reentrant.
Since
4.5

The translation files are searched from the most recently installed file back to the first installed file.

QObject::tr() and QObject::trUtf8() provide 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.

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

encoding indicates the 8-bit encoding of character strings.

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. The encoding of sourceText is specified by encoding; it defaults to CodecForTr.

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

Warning
This method is reentrant only if all translators are installed before calling this method. Installing or removing translators while performing translations is not supported. Doing so will most likely result in crashes or other undesirable behavior.
See also
QObject::tr() installTranslator() QTextCodec::codecForTr()

Definition at line 1986 of file qcoreapplication.cpp.

1988 {
1989  QString result;
1990 
1991  if (!sourceText)
1992  return result;
1993 
1994  if (self && !self->d_func()->translators.isEmpty()) {
1996  QTranslator *translationFile;
1997  for (it = self->d_func()->translators.constBegin(); it != self->d_func()->translators.constEnd(); ++it) {
1998  translationFile = *it;
1999  result = translationFile->translate(context, sourceText, disambiguation, n);
2000  if (!result.isEmpty())
2001  break;
2002  }
2003  }
2004 
2005  if (result.isEmpty()) {
2006 #ifdef QT_NO_TEXTCODEC
2007  Q_UNUSED(encoding)
2008 #else
2009  if (encoding == UnicodeUTF8)
2010  result = QString::fromUtf8(sourceText);
2011  else if (QTextCodec::codecForTr() != 0)
2012  result = QTextCodec::codecForTr()->toUnicode(sourceText);
2013  else
2014 #endif
2015  result = QString::fromLatin1(sourceText);
2016  }
2017 
2018  replacePercentN(&result, n);
2019  return result;
2020 }
#define it(className, varName)
The QString class provides a Unicode character string.
Definition: qstring.h:83
static void replacePercentN(QString *result, int n)
bool isEmpty() const
Returns true if the string has no characters; otherwise returns false.
Definition: qstring.h:704
static QString fromUtf8(const char *, int size=-1)
Returns a QString initialized with the first size bytes of the UTF-8 string str.
Definition: qstring.cpp:4302
static QTextCodec * codecForTr()
Returns the codec used by QObject::tr() on its argument.
Definition: qtextcodec.h:155
The QTranslator class provides internationalization support for text output.
Definition: qtranslator.h:59
QString toUnicode(const QByteArray &) const
Converts a from the encoding of this codec to Unicode, and returns the result in a QString...
virtual QString translate(const char *context, const char *sourceText, const char *disambiguation=0) const
Returns the translation for the key (context, sourceText, disambiguation).
static QString fromLatin1(const char *, int size=-1)
Returns a QString initialized with the first size characters of the Latin-1 string str...
Definition: qstring.cpp:4188
static QCoreApplication * self
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
The QList class is a template class that provides lists.
Definition: qdatastream.h:62
const_iterator constEnd() const
Returns a const STL-style iterator pointing to the imaginary item after the last item in the list...
Definition: qlist.h:272

◆ unixSignal

void QCoreApplication::unixSignal ( int  number)
signal

This signal is emitted whenever a Unix signal is received by the application.

Warning
This function is not part of the public interface.

The Unix signal received is specified by its number.

Referenced by QEventDispatcherUNIXPrivate::doSelect().

◆ watchUnixSignal()

void QCoreApplication::watchUnixSignal ( int  signal,
bool  watch 
)
static

Definition at line 975 of file qeventdispatcher_unix.cpp.

Referenced by QWSTtyKbPrivate::QWSTtyKbPrivate().

976 {
977  if (sig < NSIG) {
978  struct sigaction sa;
979  sigemptyset(&(sa.sa_mask));
980  sa.sa_flags = 0;
981  if (watch)
982  sa.sa_handler = signalHandler;
983  else
984  sa.sa_handler = SIG_DFL;
985  sigaction(sig, &sa, 0);
986  }
987 }
int sigaction(int, const struct sigaction *, struct sigaction *)
static void signalHandler(int sig)

◆ winEventFilter()

bool QCoreApplication::winEventFilter ( MSG msg,
long *  result 
)
virtual

The message procedure calls this function for every message received.

Reimplement this function if you want to process window messages msg that are not processed by Qt. If you don't want the event to be processed by Qt, then return true and set result to the value that the window procedure should return. Otherwise return false.

It is only directly addressed messages that are filtered. To handle system wide messages, such as messages from a registered hot key, you need to install an event filter on the event dispatcher, which is returned from QAbstractEventDispatcher::instance().

Definition at line 214 of file qcoreapplication_win.cpp.

Referenced by filterEvent().

215 {
216  Q_UNUSED(msg);
217  Q_UNUSED(result);
218  return false;
219 }
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729

Friends and Related Functions

◆ Q3AccelManager

friend class Q3AccelManager
friend

Definition at line 221 of file qcoreapplication.h.

◆ qAddPostRoutine()

void qAddPostRoutine ( QtCleanUpFunction  ptr)
related

Adds a global routine that will be called from the QApplication destructor.

This function is normally used to add cleanup routines for program-wide functionality.

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 QApplication destructor is called.

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.

Definition at line 273 of file qcoreapplication.cpp.

Referenced by qt_mac_create_menu_event_handler(), qt_mac_updateScrap(), qt_tablet_init(), qt_tablet_init_wce(), and setupOwner().

274 {
275  QVFuncList *list = postRList();
276  if (!list)
277  return;
278  list->prepend(p);
279 }
void prepend(const T &t)
Inserts value at the beginning of the list.
Definition: qlist.h:541
The QList class is a template class that provides lists.
Definition: qdatastream.h:62

◆ QApplication

friend class QApplication
friend

Definition at line 218 of file qcoreapplication.h.

Referenced by QApplication::isLeftToRight().

◆ QApplicationPrivate

friend class QApplicationPrivate
friend

Definition at line 219 of file qcoreapplication.h.

Referenced by QApplication::QApplication().

◆ qAppName

Q_CORE_EXPORT QString qAppName ( )
friend

Definition at line 575 of file qcoreapplication.cpp.

576 {
578  return QString();
579  return QCoreApplication::instance()->d_func()->appName();
580 }
static bool checkInstance(const char *method)
The QString class provides a Unicode character string.
Definition: qstring.h:83
static QCoreApplication * instance()
Returns a pointer to the application&#39;s QCoreApplication (or QApplication) instance.

◆ QClassFactory

friend class QClassFactory
friend

Definition at line 227 of file qcoreapplication.h.

◆ QETWidget

friend class QETWidget
friend

Definition at line 220 of file qcoreapplication.h.

◆ QEventDispatcherUNIXPrivate

Definition at line 217 of file qcoreapplication.h.

◆ QShortcutMap

friend class QShortcutMap
friend

Definition at line 222 of file qcoreapplication.h.

◆ qt_sendSpontaneousEvent

bool qt_sendSpontaneousEvent ( QObject ,
QEvent  
)
friend

Definition at line 5779 of file qapplication.cpp.

5780 {
5781  return QCoreApplication::sendSpontaneousEvent(receiver, event);
5782 }
static bool sendSpontaneousEvent(QObject *receiver, QEvent *event)

◆ QWidget

friend class QWidget
friend

Definition at line 223 of file qcoreapplication.h.

◆ QWidgetPrivate

friend class QWidgetPrivate
friend

Definition at line 224 of file qcoreapplication.h.

◆ removePostedEvents()

removePostedEvents ( )
related

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

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Since
4.3

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 null, the events of eventType are removed for all objects. If eventType is 0, all the events are removed for receiver.

Note
This class or function is threadsafe.

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

Properties

◆ applicationName

QString QCoreApplication::applicationName
private

the name of 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.

On BlackBerry this property is read-only. It is obtained from the BAR application descriptor file.

See also
organizationName organizationDomain applicationVersion

Definition at line 74 of file qcoreapplication.h.

◆ applicationVersion

QString QCoreApplication::applicationVersion
private

the version of this application

Since
4.4

On BlackBerry this property is read-only. It is obtained from the BAR application descriptor file.

See also
applicationName organizationName organizationDomain

Definition at line 75 of file qcoreapplication.h.

◆ organizationDomain

QString QCoreApplication::organizationDomain
private

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.

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 77 of file qcoreapplication.h.

Referenced by qDBusGenerateMetaObjectXml(), and qDBusInterfaceFromMetaObject().

◆ organizationName

QString QCoreApplication::organizationName
private

the name 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.

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.

On BlackBerry this property is read-only. It is obtained from the BAR application descriptor file.

See also
organizationDomain applicationName

Definition at line 76 of file qcoreapplication.h.

◆ self

QCoreApplication * QCoreApplication::self = 0
staticprivate

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