![]() |
Home · All Classes · Main Classes · Annotated · Grouped Classes · Functions | ![]() |
The QApplication class manages the GUI application's control flow and main settings. More...
#include <QApplication>
Part of the QtGui module.
Inherits QCoreApplication.
|
|
The QApplication class manages the GUI application's control flow and main settings.
It contains the main event loop, where all events from the window system and other sources are processed and dispatched. It also handles the application's initialization and finalization, and provides session management. It also handles most system-wide and application-wide settings.
For any GUI application that uses Qt, there is precisely one QApplication object, no matter whether the application has 0, 1, 2 or more windows at any time.
The QApplication object is accessible through the instance() function. (In earlier Qt versions the qApp global was used instead of instance().)
QApplication's main areas of responsibility are:
Since the QApplication object does so much initialization, it must be created before any other objects related to the user interface are created.
Since it also deals with common command line arguments, it is usually a good idea to create it before any interpretation or modification of argv is done in the application itself.
Constant | Value | Description |
---|---|---|
QApplication::NormalColor | 0 | the default color allocation policy |
QApplication::CustomColor | 1 | the same as NormalColor for X11; allocates colors to a palette on demand under Windows |
QApplication::ManyColor | 2 | the right choice for applications that use thousands of colors |
See setColorSpec() for full details.
Constant | Value | Description |
---|---|---|
QApplication::Tty | 0 | a console application |
QApplication::GuiClient | 1 | a GUI client application |
QApplication::GuiServer | 2 | a GUI server application |
Access functions:
Access functions:
Access functions:
Access functions:
Access functions:
Access functions:
This property holds the default layout direction for this application.
On system start-up, the default layout direction depends on the application's language.
Access functions:
See also QWidget::layoutDirection.
Access functions:
This property holds whether the application implicitly quits when the last window is closed.
The default is true.
Only top level windows with the Qt::WA_QuitOnClose attribute set are taken into account. For convenience, this attribute is not set for transient top level widgets such as splash screens, popup menus, and dialogs.
Access functions:
See also quit() and QWidget::close().
If you support drag and drop in your application, and want to start a drag and drop operation after the user has moved the cursor a certain distance with a button held down, you should use this property's value as the minimum distance required.
For example, if the mouse position of the click is stored in startPos and the current position (e.g. in the mouse move event) is currentPos, you can find out if a drag should be started with code like this:
if ((startPos - currentPos).manhattanLength() >= QApplication::startDragDistance()) startTheDrag();
Qt uses this value internally, e.g. in QFileDialog.
The default value is 4 pixels.
Access functions:
See also setStartDragDistance(), startDragTime(), QPoint::manhattanLength(), and Drag and Drop.
This property holds the time in milliseconds that a mouse button must be held down before a drag and drop operation will begin.
If you support drag and drop in your application, and want to start a drag and drop operation after the user has held down a mouse button for a certain amount of time, you should use this property's value as the delay.
Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for starting a drag.
The default value is 500 ms.
Access functions:
See also setStartDragTime(), startDragDistance(), and Drag and Drop.
Access functions:
Access functions:
Initializes the window system and constructs an application object with argc command line arguments in argv.
The global qApp pointer refers to this application object. Only one application object should be created.
This application object must be constructed before any paint devices (including widgets, pixmaps, bitmaps etc.).
Note that argc and argv might be changed. Qt removes command line arguments that it recognizes. The original argc and argv can be accessed later with qApp->argc() and qApp->argv(). The documentation for argv() contains a detailed description of how to process command line arguments.
Qt debugging options (not available if Qt was compiled without the QT_DEBUG flag defined):
See Debugging Techniques for a more detailed explanation.
All Qt programs automatically support the following command line options:
The X11 version of Qt also supports some traditional X11 command line options:
Constructs an application object with argc command line arguments in argv. If GUIenabled is true, a GUI application is constructed, otherwise a non-GUI (console) application is created.
Set GUIenabled to false for programs without a graphical user interface that should be able to run without a window system.
On X11, the window system is initialized if GUIenabled is true. If GUIenabled is false, the application does not connect to the X-server. On Windows and Macintosh, currently the window system is always initialized, regardless of the value of GUIenabled. This may change in future versions of Qt.
The following example shows how to create an application that uses a graphical interface when available.
int main(int argc, char **argv) { #ifdef Q_WS_X11 bool useGUI = getenv("DISPLAY") != 0; #else bool useGUI = true; #endif QApplication app(argc, argv, useGUI); if (useGUI) { //start GUI version ... } else { //start non-GUI version ... } return app.exec(); }
Constructs an application object with argc command line arguments in argv.
For Qt/Embedded, passing QApplication::GuiServer for type makes this application the server (equivalent to running with the -qws option).
Create an application, given an already open display dpy. If visual and colormap are non-zero, the application will use those as the default Visual and Colormap contexts.
Warning: Qt only supports TrueColor visuals at depths higher than 8 bits-per-pixel.
This is available only on X11.
Create an application, given an already open display dpy and using argc command line arguments in argv. If visual and colormap are non-zero, the application will use those as the default Visual and Colormap contexts.
Warning: Qt only supports TrueColor visuals at depths higher than 8 bits-per-pixel.
This is available only on X11.
Cleans up any window system resources that were allocated by this application. Sets the global variable qApp to 0.
Displays a simple message box about Qt. The message includes the version number of Qt being used by the application.
This is useful for inclusion in the Help menu of an application. See the examples/menu/menu.cpp example.
This function is a convenience slot for QMessageBox::aboutQt().
Returns the active modal widget.
A modal widget is a special top level widget which is a subclass of QDialog that specifies the modal parameter of the constructor as true. A modal widget must be closed before the user can continue with other parts of the program.
Modal widgets are organized in a stack. This function returns the active modal widget at the top of the stack.
See also activePopupWidget() and topLevelWidgets().
Returns the active popup widget.
A popup widget is a special top level widget that sets the Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application opens a popup widget, all events are sent to the popup. Normal widgets and modal widgets cannot be accessed before the popup widget is closed.
Only other popup widgets may be opened when a popup widget is shown. The popup widgets are organized in a stack. This function returns the active popup widget at the top of the stack.
See also activeModalWidget() and topLevelWidgets().
Returns the application top-level window that has the keyboard input focus, or 0 if no application window has the focus. Note that there might be an activeWindow() even if there is no focusWidget(), for example if no widget in that window accepts key events.
See also QWidget::setFocus(), QWidget::hasFocus(), and focusWidget().
Returns a list of all the widgets in the application.
The list is empty (QList::isEmpty()) if there are no widgets.
Note that some of the widgets may be hidden.
Example that updates all widgets:
foreach(QWidget *w, QApplication::allWidgets()) w->update();
See also topLevelWidgets(), QWidget::isVisible(), and QList::isEmpty().
Sounds the bell, using the default volume and sound.
Changes the currently active application override cursor to cursor.
This function has no effect if setOverrideCursor() wasn't called.
See also setOverrideCursor(), overrideCursor(), restoreOverrideCursor(), changeOverrideCursor(), and QWidget::setCursor().
Returns a pointer to the application global clipboard.
Closes all top-level windows.
This function is particularly useful for applications with many top-level windows. It could, for example, be connected to a "Quit" entry in the file menu as shown in the following code example:
// the "Quit" menu entry should try to close all windows QMenu* file = new Menu(this); file->addAction("&Quit", qApp, SLOT(closeAllWindows()), Qt::CTRL+Qt::Key_Q);
The windows are closed in random order, until one window does not accept the close event. The application quits when the last window was successfully closed. This can be turned of by setting quitOnLastWindowClosed to false.
See also quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(), QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(), and QWidget::isWindow().
Returns the color specification.
See also QApplication::setColorSpec().
This function deals with session management. It is invoked when the QSessionManager wants the application to commit all its data.
Usually this means saving all open files, after getting permission from the user. Furthermore you may want to provide a means by which the user can cancel the shutdown.
Note that you should not exit the application within this function. Instead, the session manager may or may not do this afterwards, depending on the context.
Warning: Within this function, no user interaction is possible, unless you ask the session manager sm for explicit permission. See QSessionManager::allowsInteraction() and QSessionManager::allowsErrorInteraction() for details and example usage.
The default implementation requests interaction and sends a close event to all visible top level widgets. If any event was rejected, the shutdown is canceled.
See also isSessionRestored(), sessionId(), saveState(), and the Session Management overview.
Returns the desktop widget (also called the root window).
The desktop widget is useful for obtaining the size of the screen. It may also be possible to draw on the desktop. We recommend against assuming that it's possible to draw on the desktop, since this does not work on all operating systems.
QDesktopWidget *d = QApplication::desktop(); int w = d->width(); // returns desktop width int h = d->height(); // returns desktop height
Enters the main event loop and waits until exit() is called or the main widget is destroyed, and 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.
Generally speaking, no user interaction can take place before calling exec(). As a special case, modal widgets like QMessageBox can be used before calling exec(), because modal widgets call exec() to start a local event loop.
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().
See also quitOnLastWindowClosed, quit(), exit(), processEvents(), and QCoreApplication::exec().
Returns the application widget that has the keyboard input focus, or 0 if no widget in this application has the focus.
See also QWidget::setFocus(), QWidget::hasFocus(), and activeWindow().
Returns display (screen) font metrics for the application font.
See also font(), setFont(), QWidget::fontMetrics(), and QPainter::fontMetrics().
Returns true if effect is enabled; otherwise returns false.
By default, Qt will try to use the desktop settings. Call setDesktopSettingsAware(false) to prevent this.
Note: All effects are disabled on screens running at less than 16-bit color depth.
See also setEffectEnabled() and Qt::UIEffect.
Returns true if the application has been restored from an earlier session; otherwise returns false.
See also sessionId(), commitData(), and saveState().
Returns the current state of the modifier keys on the keyboard. The current state is updated sychronously as the event queue is emptied of events that will spontaneously change the keyboard state (QEvent::KeyPress and QEvent::KeyRelease events).
It should be noted this may not reflect the actual keys held on the input device at the time of calling but rather the modifiers as last reported in one of the above events. If no keys are being held Qt::NoModifier is returned.
See also QApplication::mouseButtons() and Qt::KeyboardModifiers.
This signal is emitted when the user has closed the last top level window.
By default QApplication implicitely quits when this signal is emitted. This feature be turned off by setting quitOnLastWindowClosed to false.
Only top level windows with the Qt::WA_QuitOnClose attribute set are taken into account. For convenience, this attribute is not set for transient top level widgets such as splash screens, popup menus, and dialogs.
See also QWidget::close().
Warning: This virtual function is only implemented under Mac OS X.
If you create an application that inherits QApplication and reimplement this function, you get direct access to all Carbon Events that are received from Mac OS X with this function being called with the caller and the event.
Return true if you want to stop the event from being processed. Return false for normal event dispatching. The default implementation returns false.
Returns the current state of the buttons on the mouse. The current state is updated syncronously as the event queue is emptied of events that will spontaneously change the mouse state (QEvent::MousePress and QEvent::MouseRelease events).
It should be noted this may not reflect the actual buttons held on theinput device at the time of calling but rather the mouse buttons as last reported in one of the above events. If no mouse buttons rae being held Qt::NoButton is returned.
See also QApplication::keyboardModifiers() and Qt::MouseButtons.
Returns the active application override cursor.
This function returns 0 if no application cursor has been defined (i.e. the internal cursor stack is empty).
See also setOverrideCursor() and restoreOverrideCursor().
Return the QWSDecoration used for decorating windows.
This method is non-portable. It is available only in Qt/Embedded.
See also QDecoration.
Warning: This virtual function is only implemented under Qt/Embedded.
If you create an application that inherits QApplication and reimplement this function, you get direct access to all QWS (Q Window System) events that the are received from the QWS master process. The events are passed in the event parameter.
Return true if you want to stop the event from being processed. Return false for normal event dispatching. The default implementation returns false.
Set Qt/Embedded custom color table.
Qt/Embedded on 8-bpp displays allocates a standard 216 color cube. The remaining 40 colors may be used by setting a custom color table in the QWS master process before any clients connect.
colorTable is an array of up to 40 custom colors. start is the starting index (0-39) and numColors is the number of colors to be set (1-40).
This method is non-portable. It is available only in Qt/Embedded.
Set the QWSDecoration derived class to use for decorating the Qt/Embedded windows to dec.
This method is non-portable. It is available only in Qt/Embedded.
See also QDecoration.
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Requests a QDecoration object for decoration from the QDecorationFactory.
The string must be one of the QStyleFactory::keys(), typically one of "windows", "motif", "cde", "motifplus", "platinum", "sgi" and "compact". Depending on the platform, "windowsxp", "aqua" or "macintosh" may be available.
A later call to the QApplication constructor will override the requested style when a "-style" option is passed in as a commandline parameter.
Returns 0 if an unknown decoration is passed, otherwise the QStyle object returned is set as the application's GUI style.
Undoes the last setOverrideCursor().
If setOverrideCursor() has been called twice, calling restoreOverrideCursor() will activate the first cursor set. Calling this function a second time restores the original widgets' cursors.
See also setOverrideCursor(), overrideCursor(), and ..
This function deals with session management. It is invoked when the session manager wants the application to preserve its state for a future session.
For example, a text editor would create a temporary file that includes the current contents of its edit buffers, the location of the cursor and other aspects of the current editing session.
Note that you should never exit the application within this function. Instead, the session manager may or may not do this afterwards, depending on the context. Futhermore, most session managers will very likely request a saved state immediately after the application has been started. This permits the session manager to learn about the application's restart policy.
Warning: Within this function, no user interaction is possible, unless you ask the session manager sm for explicit permission. See QSessionManager::allowsInteraction() and QSessionManager::allowsErrorInteraction() for details.
See also isSessionRestored(), sessionId(), commitData(), and the Session Management overview.
Returns the current session's identifier.
If the application has been restored from an earlier session, this identifier is the same as it was in that previous session.
The session identifier is guaranteed to be unique both for different applications and for different instances of the same application.
See also isSessionRestored(), sessionKey(), commitData(), and saveState().
Returns the session key in the current session.
If the application has been restored from an earlier session, this key is the same as it was when the previous session ended.
The session key changes with every call of commitData() or saveState().
See also isSessionRestored(), sessionId(), commitData(), and saveState().
Sets the active window to the act widget in response to a system event. The function is called from the platform specific event handlers.
Warning: This function does not set the keyboard focus to the active widget. Call QWidget::activateWindow() instead.
It sets the activeWindow() and focusWidget() attributes and sends proper WindowActivate/WindowDeactivate and FocusIn/FocusOut events to all appropriate widgets. The window will then be painted in active state (e.g. cursors in line edits will blink), and it will have tool tips enabled.
See also activeWindow() and QWidget::activateWindow().
Sets the color specification for the application to spec.
The color specification controls how the application allocates colors when run on a display with a limited amount of colors, e.g. 8 bit / 256 color displays.
The color specification must be set before you create the QApplication object.
The options are:
On Windows, Qt creates a Windows palette, and fills it with a color cube.
Be aware that the CustomColor and ManyColor choices may lead to colormap flashing: The foreground application gets (most) of the available colors, while the background windows will look less attractive.
Example:
int main(int argc, char **argv) { QApplication::setColorSpec(QApplication::ManyColor); QApplication a(argc, argv); ... }
QColor provides more functionality for controlling color allocation and freeing up certain colors. See QColor::enterAllocContext() for more information.
To check what mode you end up with, call QColor::numBitPlanes() once the QApplication object exists. A value greater than 8 (typically 16, 24 or 32) means true color.
See also colorSpec(), QColor::numBitPlanes(), and QColor::enterAllocContext().
Enables the UI effect effect if enable is true, otherwise the effect will not be used.
Note: All effects are disabled on screens running at less than 16-bit color depth.
See also isEffectEnabled(), Qt::UIEffect, and setDesktopSettingsAware().
This function replaces all QInputContext instances in the application. The function's argument is the identifier name of the newly selected input method.
Sets the application override cursor to cursor.
Application override cursors are intended for showing the user that the application is in a special state, for example during an operation that might take some time.
This cursor will be displayed in all the application's widgets until restoreOverrideCursor() or another setOverrideCursor() is called.
Application cursors are stored on an internal stack. setOverrideCursor() pushes the cursor onto the stack, and restoreOverrideCursor() pops the active cursor off the stack. changeOverrideCursor() changes the curently active application override cursor. Every setOverrideCursor() must eventually be followed by a corresponding restoreOverrideCursor(), otherwise the stack will never be emptied.
Example:
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); calculateHugeMandelbrot(); // lunch time... QApplication::restoreOverrideCursor();
See also overrideCursor(), restoreOverrideCursor(), changeOverrideCursor(), and QWidget::setCursor().
Sets the application's GUI style to style. Ownership of the style object is transferred to QApplication, so QApplication will delete the style object on application exit or when a new style is set.
Example usage:
QApplication::setStyle(new QWindowsStyle);
When switching application styles, the color palette is set back to the initial colors or the system defaults. This is necessary since certain styles have to adapt the color palette to be fully style-guide compliant.
See also style(), QStyle, setPalette(), and desktopSettingsAware().
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Requests a QStyle object for style from the QStyleFactory.
The string must be one of the QStyleFactory::keys(), typically one of "windows", "motif", "cde", "motifplus", "platinum", "sgi" and "compact". Depending on the platform, "windowsxp", "aqua" or "macintosh" may be available.
Returns 0 if an unknown style is passed, otherwise the QStyle object returned is set as the application's GUI style.
Returns the application's style object.
See also setStyle() and QStyle.
Synchronizes with the X server in the X11 implementation. This normally takes some time. Does nothing on other platforms.
Returns the top level widget at the point p.
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
Returns the top level widget at the point (x, y).
Returns a list of the top level widgets in the application.
The list is empty (QList::isEmpty()) if there are no top level widgets.
Note that some of the top level widgets may be hidden, for example the tooltip if no tooltip is currently shown.
Example:
// Show all hidden top level widgets. foreach(QWidget *w, QApplication::topLevelWidgets()) { if (w->isExplicitlyHidden()) w->show(); }
See also allWidgets(), QWidget::isWindow(), QWidget::isExplicitlyHidden(), and QList::isEmpty().
Returns the type of application, Tty, GuiClient or GuiServer.
Returns a pointer to the widget at global screen position p, or 0 if there is no Qt widget there.
This function can be slow.
See also QCursor::pos(), QWidget::grabMouse(), and QWidget::grabKeyboard().
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
If gotFocus is true, widget will become the active window. Otherwise the active window is reset to NULL.
Warning: This virtual function is only implemented under X11.
If you create an application that inherits QApplication and reimplement this function, you get direct access to all X events that the are received from the X server. The events are passed in the event parameter.
Return true if you want to stop the event from being processed. Return false for normal event dispatching. THe default implementation returns false.
See also x11ProcessEvent().
This function does the core processing of individual X events, normally by dispatching Qt events to the right destination.
It returns 1 if the event was consumed by special handling, 0 if the event was consumed by normal handling, and -1 if the event was for an unrecognized widget.
See also x11EventFilter().
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 which uses the parent-child mechanism to call a cleanup function at the right time:
class MyPrivateInitStuff: public QObject { private: MyPrivateInitStuff(QObject *parent): QObject(parent) { // initialization goes here } MyPrivateInitStuff *p; public: static MyPrivateInitStuff *initStuff(QObject *parent) { if (!p) p = new MyPrivateInitStuff(parent); return p; } ~MyPrivateInitStuff() { // cleanup (the "post routine") goes here } }
By selecting the right parent widget/object, this can often be made to clean up the module's data at the exactly the right moment.
Copyright © 2005 Trolltech | Trademarks | Qt 4.0.0-b2 |