
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQCoreApplication class provides an event loop for console Qt applications.More...
| Header: | #include <QCoreApplication> |
| Inherits: | QObject |
| Inherited By: |
| enum | Encoding { CodecForTr, UnicodeUTF8, DefaultCodec } |
| typedef | EventFilter |
| QCoreApplication(int & argc, char ** argv) | |
| ~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) |
| void | quit() |
| void | aboutToQuit() |
| void | addLibraryPath(const QString & path) |
| QString | applicationDirPath() |
| QString | applicationFilePath() |
| QString | applicationName() |
| qint64 | applicationPid() |
| QString | applicationVersion() |
| QStringList | arguments() |
| bool | closingDown() |
| int | exec() |
| void | exit(int returnCode = 0) |
| void | flush() |
| bool | hasPendingEvents() |
| void | installTranslator(QTranslator * translationFile) |
| QCoreApplication * | instance() |
| QStringList | libraryPaths() |
| QString | organizationDomain() |
| QString | organizationName() |
| void | postEvent(QObject * receiver, QEvent * event) |
| void | postEvent(QObject * receiver, QEvent * event, int priority) |
| void | processEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents) |
| void | processEvents(QEventLoop::ProcessEventsFlags flags, int maxtime) |
| void | removeLibraryPath(const QString & path) |
| void | removePostedEvents(QObject * receiver) |
| void | removePostedEvents(QObject * receiver, int eventType) |
| void | removeTranslator(QTranslator * translationFile) |
| bool | sendEvent(QObject * receiver, QEvent * event) |
| void | sendPostedEvents(QObject * receiver, int event_type) |
| void | sendPostedEvents() |
| void | setApplicationName(const QString & application) |
| void | setApplicationVersion(const QString & version) |
| void | setAttribute(Qt::ApplicationAttribute attribute, bool on = true) |
| void | setLibraryPaths(const QStringList & paths) |
| void | setOrganizationDomain(const QString & orgDomain) |
| void | setOrganizationName(const QString & orgName) |
| bool | startingUp() |
| bool | testAttribute(Qt::ApplicationAttribute attribute) |
| QString | translate(const char * context, const char * sourceText, const char * disambiguation, Encoding encoding, int n) |
| QString | translate(const char * context, const char * sourceText, const char * disambiguation = 0, Encoding encoding = CodecForTr) |
| virtual bool | event(QEvent * e) |
| void | qAddPostRoutine(QtCleanUpFunction ptr) |
| Q_DECLARE_TR_FUNCTIONS( context) |
TheQCoreApplication 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 oneQCoreApplication object. For GUI applications, seeQApplication.
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 is started with a call toexec(). Long running operations can callprocessEvents() to keep the application responsive.
In general, we recommend that you create aQCoreApplication or aQApplication object in yourmain() function as early as possible.exec() will not return until the event loop exits; e.g., whenquit() is called.
Several static convenience functions are also provided. TheQCoreApplication object is available frominstance(). Events can be sent or posted usingsendEvent(),postEvent(), andsendPostedEvents(). Pending events can be removed withremovePostedEvents() or flushed withflush().
The class provides aquit() slot and anaboutToQuit() signal.
An application has anapplicationDirPath() and anapplicationFilePath(). Library paths (seeQLibrary) can be retrieved withlibraryPaths() and manipulated bysetLibraryPaths(),addLibraryPath(), andremoveLibraryPath().
Translation files can be added or removed usinginstallTranslator() andremoveTranslator(). Application strings can be translated usingtranslate(). TheQObject::tr() andQObject::trUtf8() functions are implemented in terms oftranslate().
The command line arguments which are passed toQCoreApplication's constructor should be accessed using thearguments() function. Note that some arguments supplied by the user may have been processed and removed byQCoreApplication.
In cases where command line arguments need to be obtained using the argv() function, you must convert them from the local string encoding usingQString::fromLocal8Bit().
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 functionsetlocale(LC_NUMERIC,"C") right after initializingQApplication orQCoreApplication to reset the locale that is used for number formatting to "C"-locale.
See alsoQApplication,QAbstractEventDispatcher,QEventLoop,Semaphores Example, andWait Conditions Example.
This enum type defines the 8-bit encoding of character string arguments totranslate():
| Constant | Value | Description |
|---|---|---|
QCoreApplication::CodecForTr | 0 | The encoding specified byQTextCodec::codecForTr() (Latin-1 if none has been set). |
QCoreApplication::UnicodeUTF8 | 1 | UTF-8. |
QCoreApplication::DefaultCodec | CodecForTr | (Obsolete) Use CodecForTr instead. |
See alsoQObject::tr(),QObject::trUtf8(), andQString::fromUtf8().
A function with the following signature that can be used as an event filter:
bool myEventFilter(void*message,long*result);
See alsosetEventFilter().
This property holds the name of this application.
The value is used by theQSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time aQSettings object is created.
On BlackBerry this property is read-only. It is obtained from the BAR application descriptor file.
Access functions:
| QString | applicationName() |
| void | setApplicationName(const QString & application) |
See alsoorganizationName,organizationDomain, andapplicationVersion.
This property holds the version of this application.
On BlackBerry this property is read-only. It is obtained from the BAR application descriptor file.
This property was introduced in Qt 4.4.
Access functions:
| QString | applicationVersion() |
| void | setApplicationVersion(const QString & version) |
See alsoapplicationName,organizationName, andorganizationDomain.
This property holds the Internet domain of the organization that wrote this application.
The value is used by theQSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time aQSettings object is created.
On Mac,QSettings uses organizationDomain() as the organization if it's not an empty string; otherwise it usesorganizationName(). On all other platforms,QSettings usesorganizationName() as the organization.
Access functions:
| QString | organizationDomain() |
| void | setOrganizationDomain(const QString & orgDomain) |
See alsoorganizationName,applicationName, andapplicationVersion.
This property holds the name of the organization that wrote this application.
The value is used by theQSettings class when it is constructed using the empty constructor. This saves having to repeat this information each time aQSettings object is created.
On Mac,QSettings usesorganizationDomain() 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.
Access functions:
| QString | organizationName() |
| void | setOrganizationName(const QString & orgName) |
See alsoorganizationDomain andapplicationName.
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.
Theargc andargv arguments are processed by the application, and made available in a more convenient form by thearguments() function.
Warning: The data referred to byargc andargv must stay valid for the entire lifetime of theQCoreApplication object. In addition,argc must be greater than zero andargv must contain at least one valid character string.
Destroys theQCoreApplication object.
[signal]void QCoreApplication::aboutToQuit()This signal is emitted when the application is about to quit the main event loop, e.g. when the event loop level drops to zero. This may happen either after a call toquit() 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 alsoquit().
[static]void QCoreApplication::addLibraryPath(constQString & path)Prependspath to the beginning of the library path list, ensuring that it is searched for libraries first. Ifpath 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 isINSTALL/plugins, whereINSTALL 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 alsoremoveLibraryPath(),libraryPaths(), andsetLibraryPaths().
[static]QString QCoreApplication::applicationDirPath()Returns the directory that contains the application executable.
For example, if you have installed Qt in theC:\Trolltech\Qt directory, and you run theregexp 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 thatargv[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 alsoapplicationFilePath().
[static]QString QCoreApplication::applicationFilePath()Returns the file path of the application executable.
For example, if you have installed Qt in the/usr/local/qt directory, and you run theregexp 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 thatargv[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 alsoapplicationDirPath().
[static]qint64 QCoreApplication::applicationPid()Returns the current process ID for the application.
This function was introduced in Qt 4.4.
[static]QStringList QCoreApplication::arguments()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 usingQString::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 ofGetCommandLine(). 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 withRApaLsSession::StartApp one can specify arguments usingCApaCommandLine::SetTailEndL function. Such arguments are only available via this method; they will not be passed tomain function. Also note that only 8-bit string data set withCApaCommandLine::SetTailEndL is supported by this function.
This function was introduced in Qt 4.1.
See alsoapplicationFilePath().
[static]bool QCoreApplication::closingDown()Returns true if the application objects are being destroyed; otherwise returns false.
See alsostartingUp().
[virtual protected]bool QCoreApplication::event(QEvent * e)Reimplemented fromQObject::event().
[static]int QCoreApplication::exec()Enters the main event loop and waits untilexit() is called. Returns the value that was set toexit() (which is 0 ifexit() is called viaquit()).
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 aQTimer with 0 timeout. More advanced idle processing schemes can be achieved usingprocessEvents().
We recommend that you connect clean-up code to theaboutToQuit() signal, instead of putting it in your application'smain() 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 themain() function after the QCoreApplication::exec() call.
See alsoquit(),exit(),processEvents(), andQApplication::exec().
[static]void QCoreApplication::exit(int returnCode = 0)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 toexec(). Theexec() function returnsreturnCode. If the event loop is not running, this function does nothing.
By convention, areturnCode of 0 means success, and any non-zero value indicates an error.
Note that unlike the C library function of the same name, this functiondoes return to the caller -- it is event processing that stops.
Sendsmessage through the event filter that was set bysetEventFilter(). If no event filter has been set, this function returns false; otherwise, this function returns the result of the event filter function in theresult parameter.
See alsosetEventFilter().
[static]void QCoreApplication::flush()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 alsosendPostedEvents().
[static]bool QCoreApplication::hasPendingEvents()This function returns true if there are pending events; otherwise returns false. Pending events can be either from the window system or posted events usingpostEvent().
See alsoQAbstractEventDispatcher::hasPendingEvents().
[static]void QCoreApplication::installTranslator(QTranslator * translationFile)Adds the translation filetranslationFile 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 aQTranslator, or changing an installedQTranslator generates aLanguageChange event for theQCoreApplication instance. AQApplication 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 thetr() function to the respective property setters. User-interface classes generated byQt Designer provide aretranslateUi() function that can be called.
See alsoremoveTranslator(),translate(),QTranslator::load(), andDynamic Translation.
[static]QCoreApplication * QCoreApplication::instance()Returns a pointer to the application'sQCoreApplication (orQApplication) instance.
If no instance has been allocated,null is returned.
[static]QStringList QCoreApplication::libraryPaths()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 aqt.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 isINSTALL/plugins, whereINSTALL 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 theforeach pseudo-keyword:
See alsosetLibraryPaths(),addLibraryPath(),removeLibraryPath(),QLibrary, andHow to Create Qt Plugins.
[virtual]bool QCoreApplication::notify(QObject * receiver,QEvent * event)Sendsevent toreceiver: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:
See alsoQObject::event() andinstallEventFilter().
[static]void QCoreApplication::postEvent(QObject * receiver,QEvent * event)Adds the eventevent, with the objectreceiver 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 isnot 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 thenotify() 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 aQt::NormalEventPriority.
Note: This function isthread-safe.
See alsosendEvent(),notify(), andsendPostedEvents().
[static]void QCoreApplication::postEvent(QObject * receiver,QEvent * event,int priority)This function overloadspostEvent().
Adds the eventevent, with the objectreceiver 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 isnot 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 thenotify() function.
Events are sorted in descendingpriority order, i.e. events with a highpriority are queued before events with a lowerpriority. Thepriority can be any integer value, i.e. between INT_MAX and INT_MIN, inclusive; seeQt::EventPriority for more details. Events with equalpriority will be processed in the order posted.
Note: This function isthread-safe.
This function was introduced in Qt 4.3.
See alsosendEvent(),notify(),sendPostedEvents(), andQt::EventPriority.
[static]void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags = QEventLoop::AllEvents)Processes all pending events for the calling thread according to the specifiedflags 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, theDeferredDelete events will not be processed. This can affect the behaviour of widgets, e.g.QToolTip, that rely onDeferredDelete events to function properly. An alternative would be to callsendPostedEvents() from within that local loop.
Calling this function processes events only for the calling thread.
Note: This function isthread-safe.
See alsoexec(),QTimer,QEventLoop::processEvents(),flush(), andsendPostedEvents().
[static]void QCoreApplication::processEvents(QEventLoop::ProcessEventsFlags flags,int maxtime)This function overloadsprocessEvents().
Processes pending events for the calling thread formaxtime 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 isthread-safe.
See alsoexec(),QTimer, andQEventLoop::processEvents().
[static slot]void QCoreApplication::quit()Tells the application to exit with return code 0 (success). Equivalent to callingQCoreApplication::exit(0).
It's common to connect theQApplication::lastWindowClosed() signal to quit(), and you also often connect e.g.QAbstractButton::clicked() or signals inQAction,QMenu, orQMenuBar to it.
Example:
QPushButton*quitButton=newQPushButton("Quit");connect(quitButton, SIGNAL(clicked()),&app, SLOT(quit()));
See alsoexit(),aboutToQuit(), andQApplication::lastWindowClosed().
[static]void QCoreApplication::removeLibraryPath(constQString & path)Removespath from the library path list. Ifpath is empty or not in the path list, the list is not changed.
See alsoaddLibraryPath(),libraryPaths(), andsetLibraryPaths().
[static]void QCoreApplication::removePostedEvents(QObject * receiver)Removes all events posted usingpostEvent() forreceiver.
The events arenot 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 causereceiver to break one or more invariants.
Note: This function isthread-safe.
[static]void QCoreApplication::removePostedEvents(QObject * receiver,int eventType)This function overloadsremovePostedEvents().
Removes all events of the giveneventType that were posted usingpostEvent() forreceiver.
The events arenot 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 causereceiver to break one or more invariants.
Ifreceiver is null, the events ofeventType are removed for all objects. IfeventType is 0, all the events are removed forreceiver.
Note: This function isthread-safe.
This function was introduced in Qt 4.3.
[static]void QCoreApplication::removeTranslator(QTranslator * translationFile)Removes the translation filetranslationFile from the list of translation files used by this application. (It does not delete the translation file from the file system.)
See alsoinstallTranslator(),translate(), andQObject::tr().
[static]bool QCoreApplication::sendEvent(QObject * receiver,QEvent * event)Sends eventevent directly to receiverreceiver, using thenotify() function. Returns the value that was returned from the event handler.
The event isnot deleted when the event has been sent. The normal approach is to create the event on the stack, for example:
QMouseEventevent(QEvent::MouseButtonPress, pos,0,0,0);QApplication::sendEvent(mainWindow,&event);
See alsopostEvent() andnotify().
[static]void QCoreApplication::sendPostedEvents(QObject * receiver,int event_type)Immediately dispatches all events which have been previously queued withQCoreApplication::postEvent() and which are for the objectreceiver and have the event typeevent_type.
Events from the window system arenot dispatched by this function, but byprocessEvents().
Ifreceiver is null, the events ofevent_type are sent for all objects. Ifevent_type is 0, all the events are sent forreceiver.
Note:This method must be called from the same thread as itsQObject parameter,receiver.
See alsoflush() andpostEvent().
[static]void QCoreApplication::sendPostedEvents()This function overloadssendPostedEvents().
Dispatches all posted events, i.e. empties the event queue.
[static]void QCoreApplication::setAttribute(Qt::ApplicationAttribute attribute,bool on = true)Sets the attributeattribute ifon is true; otherwise clears the attribute.
One of the attributes that can be set with this method isQt::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 alsotestAttribute().
Replaces the event filter function for theQCoreApplication withfilter 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 replacedEventFilter 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 isnot 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 nullEventFilter 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 byQCoreApplication::filterEvent(). If the filter function returns false to indicate the message should be processed further, the native message can then be translated into aQEvent and handled by the standard Qtevent filering, e.g.QObject::installEventFilter().
Note:The filter function set here is different form the filter function set viaQAbstractEventDispatcher::setEventFilter(), which gets all messages received by its thread, even messages meant for objects that are not handled by Qt.
See alsoQObject::installEventFilter() andQAbstractEventDispatcher::setEventFilter().
[static]void QCoreApplication::setLibraryPaths(constQStringList & paths)Sets the list of directories to search when loading libraries topaths. All existing paths will be deleted and the path list will consist of the paths given inpaths.
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 alsolibraryPaths(),addLibraryPath(),removeLibraryPath(), andQLibrary.
[static]bool QCoreApplication::startingUp()Returns true if an application object has not been created yet; otherwise returns false.
See alsoclosingDown().
[static]bool QCoreApplication::testAttribute(Qt::ApplicationAttribute attribute)Returns true if attributeattribute is set; otherwise returns false.
See alsosetAttribute().
[static]QString QCoreApplication::translate(constchar * context, constchar * sourceText, constchar * disambiguation,Encoding encoding,int n)Returns the translation text forsourceText, 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() andQObject::trUtf8() provide this functionality more conveniently.
context is typically a class name (e.g., "MyDialog") andsourceText is either English text or a short identifying text.
disambiguation is an identifying string, for when the samesourceText is used in different roles within the same context. By default, it is null.
See theQTranslator andQObject::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. SeeQObject::tr() for details.
If none of the translation files contain a translation forsourceText incontext, this function returns aQString equivalent ofsourceText. The encoding ofsourceText is specified byencoding; it defaults toCodecForTr.
This function is not virtual. You can use alternative translation techniques by subclassingQTranslator.
Warning: This method is reentrant only if all translators are installedbefore 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 isreentrant.
This function was introduced in Qt 4.5.
See alsoQObject::tr(),installTranslator(), andQTextCodec::codecForTr().
[static]QString QCoreApplication::translate(constchar * context, constchar * sourceText, constchar * disambiguation = 0,Encoding encoding = CodecForTr)This function overloadstranslate().
[virtual]bool QCoreApplication::winEventFilter(MSG * msg,long * result)The message procedure calls this function for every message received. Reimplement this function if you want to process window messagesmsg that are not processed by Qt. If you don't want the event to be processed by Qt, then return true and setresult 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 fromQAbstractEventDispatcher::instance().
Adds a global routine that will be called from theQApplication destructor. This function is normally used to add cleanup routines for program-wide functionality.
The function specified byptr should take no arguments and should return nothing. For example:
staticint*global_ptr=0;staticvoid cleanup_ptr(){delete[] global_ptr; global_ptr=0;}void init_ptr(){ global_ptr=newint[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 theQApplication 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 :publicQObject{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.
The Q_DECLARE_TR_FUNCTIONS() macro declares and implements two translation functions,tr() andtrUtf8(), with these signatures:
staticinlineQString tr(constchar*sourceText,constchar*comment=0);staticinlineQString trUtf8(constchar*sourceText,constchar*comment=0);
This macro is useful if you want to useQObject::tr() orQObject::trUtf8() in classes that don't inherit fromQObject.
Q_DECLARE_TR_FUNCTIONS() must appear at the very top of the class definition (before the firstpublic: orprotected:). For example:
class MyMfcView :public CView{ Q_DECLARE_TR_FUNCTIONS(MyMfcView)public: MyMfcView();...};
Thecontext parameter is normally the class name, but it can be any string.
See alsoQ_OBJECT,QObject::tr(), andQObject::trUtf8().
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.