Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

QCoreApplication Class

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

 #include <QCoreApplication>

Inherits: QObject.

Inherited by: QGuiApplication.

Public Types

typedef EventFilter
enum Type { Tty, GuiClient, GuiServer }

Properties

  • 1 property inherited from QObject

Public Functions

QCoreApplication(int & argc, char ** argv, int _internal = ApplicationFlags)
~QCoreApplication()
bool filterEvent(void * message, long * result)
virtual bool notify(QObject * receiver, QEvent * event)
EventFilter setEventFilter(EventFilter filter)
virtual bool winEventFilter(MSG * msg, long * result)
  • 31 public functions inherited from QObject

Public Slots

void quit()
  • 1 public slot inherited from QObject

Signals

void aboutToQuit()

Static Public Members

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

Reimplemented Protected Functions

virtual bool event(QEvent * e)
  • 9 protected functions inherited from QObject

Related Non-Members

void qAddPostRoutine(QtCleanUpFunction ptr)

Macros

Q_DECLARE_TR_FUNCTIONS( context)

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, and Wait Conditions Example.

Member Type Documentation

typedef 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().

enum QCoreApplication::Type

ConstantValueDescription
QCoreApplication::Tty0a console application
QCoreApplication::GuiClient1a GUI application
QCoreApplication::GuiServer2Deprecated. this value is only left for compatibility.

Property Documentation

applicationName : QString

This property holds 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.

If not set, the application name defaults to the executable name (since 5.0).

Access functions:

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

See also organizationName, organizationDomain, applicationVersion, and applicationFilePath.

applicationVersion : QString

This property holds the version of this application.

This property was introduced in Qt 4.4.

Access functions:

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

See also applicationName, organizationName, and organizationDomain.

organizationDomain : QString

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

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

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.

Access functions:

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

See also organizationName, applicationName, and applicationVersion.

organizationName : QString

This property holds 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.

Access functions:

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

See also organizationDomain and applicationName.

quitLockEnabled : bool

Access functions:

bool isQuitLockEnabled()
void setQuitLockEnabled(bool enabled)

Member Function Documentation

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

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.

QCoreApplication::~QCoreApplication()

Destroys the QCoreApplication object.

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

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.

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

QString QCoreApplication::applicationDirPath() [static]

Returns the directory that contains the application executable.

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

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

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

qint64 QCoreApplication::applicationPid() [static]

Returns the current process ID for the application.

This function was introduced in Qt 4.4.

QStringList QCoreApplication::arguments() [static]

Returns the list of command-line arguments.

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

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

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

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

This function was introduced in Qt 4.1.

See also applicationFilePath().

bool QCoreApplication::closingDown() [static]

Returns true if the application objects are being destroyed; otherwise returns false.

See also startingUp().

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

Reimplemented from QObject::event().

QAbstractEventDispatcher * QCoreApplication::eventDispatcher() [static]

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

See also setEventDispatcher().

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 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(), and QApplication::exec().

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() and exec().

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

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

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

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

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

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

Installing or removing a QTranslator, or changing an installed QTranslator generates a 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.

The function returns true on success and false on failure.

See also removeTranslator(), translate(), QTranslator::load(), and Dynamic Translation.

QCoreApplication * QCoreApplication::instance() [static]

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

If no instance has been allocated, null is returned.

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 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, and How to Create Qt Plugins.

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() and installEventFilter().

void QCoreApplication::postEvent(QObject * receiver, QEvent * event, int priority = Qt::NormalEventPriority) [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 sorted in descending priority order, i.e. events with a high priority are queued before events with a lower priority. The priority can be any integer value, i.e. between INT_MAX and INT_MIN, inclusive; see Qt::EventPriority for more details. Events with equal priority will be processed in the order posted.

Note: This function is thread-safe.

This function was introduced in Qt 4.3.

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

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 function is thread-safe.

See also exec(), QTimer, QEventLoop::processEvents(), flush(), and sendPostedEvents().

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

This function overloads processEvents().

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

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

Calling this function processes events only for the calling thread.

Note: This function is thread-safe.

See also exec(), QTimer, and QEventLoop::processEvents().

void QCoreApplication::quit() [static slot]

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(), and QApplication::lastWindowClosed().

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(), and setLibraryPaths().

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

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

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

If receiver is null, the events of eventType are removed for all objects. If eventType is 0, all the events are removed for receiver. You should never call this function with eventType of 0. If you do call it in this way, be aware that killing events may cause receiver to break one or more invariants.

Note: This function is thread-safe.

This function was introduced in Qt 4.3.

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

Removes the translation file translationFile from the list of translation files used by this application. (It does not delete the translation file from the file system.)

The function returns true on success and false on failure.

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

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

Sends event event directly to receiver receiver, using the notify() function. Returns the value that was returned from the event handler.

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

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

See also postEvent() and notify().

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

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

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

If receiver is 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() and postEvent().

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

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

Sets the event dispatcher for the main thread to eventDispatcher. This is only possible as long as there is no event dispatcher installed yet. That is, before QCoreApplication has been instantiated. This method takes ownership of the object.

See also eventDispatcher().

EventFilter QCoreApplication::setEventFilter(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().

Note: 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() and QAbstractEventDispatcher::setEventFilter().

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.

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

bool QCoreApplication::startingUp() [static]

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

See also closingDown().

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

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

See also setAttribute().

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

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

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

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

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

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

n is used in conjunction with %n to support plural forms. See QObject::tr() for details.

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

This function is not virtual. You can use alternative translation techniques by subclassing 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.

Note: This function is reentrant.

See also QObject::tr() and installTranslator().

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

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

Related Non-Members

void qAddPostRoutine(QtCleanUpFunction ptr)

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.

Macro Documentation

Q_DECLARE_TR_FUNCTIONS( context)

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

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

This macro is useful if you want to use QObject::tr() or QObject::trUtf8() in classes that don't inherit from QObject.

Q_DECLARE_TR_FUNCTIONS() must appear at the very top of the class definition (before the first public: or protected:). For example:

 class MyMfcView : public CView
 {
     Q_DECLARE_TR_FUNCTIONS(MyMfcView)

 public:
     MyMfcView();
     ...
 };

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

See also Q_OBJECT, QObject::tr(), and QObject::trUtf8().

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 5.0-snapshot
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web