Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# QApplication Class Reference

The QApplication class manages the GUI application's control flow and main settings. More...

    #include <qnamespace.h>
    #include <qwindowdefs.h>
    #include <qglobal.h>

Inherits QCoreApplication.

- List of all members, including inherited members
- Compatibility members

### Public Types

- enum ColorSpec { NormalColor, CustomColor, ManyColor }
- enum Type { Tty, GuiClient, GuiServer }

### Writable Properties

- 1 writable property inherited from QObject

### Public Functions

- QApplication ( int & argc, char ** argv )
- QApplication ( int & argc, char ** argv, bool GUIenabled )
- QApplication ( int & argc, char ** argv, Type type )
- QApplication ( Display * dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0 )
- QApplication ( Display * dpy, int argc, char ** argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0 )
- virtual ~QApplication ()
- QWidget * activeWindow () const
- virtual void commitData ( QSessionManager & sm )
- QWidget * focusWidget () const
- bool isSessionRestored () const
- virtual bool macEventFilter ( EventHandlerCallRef caller, EventRef event )
- QWidget * mainWidget () const
- virtual void polish ( QWidget * w )
- virtual bool qwsEventFilter ( QWSEvent * event )
- void qwsSetCustomColors ( QRgb * colorTable, int start, int numColors )
- virtual void saveState ( QSessionManager & sm )
- QString sessionId () const
- QString sessionKey () const
- void setActiveWindow ( QWidget * act )
- virtual void setMainWidget ( QWidget * mainWidget )
- Type type () const
- void winFocus ( QWidget * widget, bool gotFocus )
- virtual bool x11EventFilter ( XEvent * event )
- int x11ProcessEvent ( XEvent * event )

- 15 public functions inherited from QCoreApplication
- 24 public functions inherited from QObject

### Public Slots

- void aboutQt ()
- void closeAllWindows ()

- 1 public slot inherited from QCoreApplication
- 1 public slot inherited from QObject

### Signals

- void lastWindowClosed ()

- 1 signal inherited from QCoreApplication
- 1 signal inherited from QObject

### Static Public Members

- QWidget * activeModalWidget ()
- QWidget * activePopupWidget ()
- QWidgetList allWidgets ()
- void beep ()
- QClipboard * clipboard ()
- int colorSpec ()
- int cursorFlashTime ()
- QDesktopWidget * desktop ()
- bool desktopSettingsAware ()
- int doubleClickInterval ()
- QFont font ( const QWidget * w = 0 )
- QFontMetrics fontMetrics ()
- QSize globalStrut ()
- Qt::Alignment horizontalAlignment ( Qt::Alignment align )
- bool isEffectEnabled ( Qt::UIEffect effect )
- QCursor * overrideCursor ()
- QPalette palette ()
- QPalette palette ( const QWidget * w )
- QPalette palette ( const char * className )
- QDecoration & qwsDecoration ()
- void qwsSetDecoration ( QDecoration * dec )
- QDecoration * qwsSetDecoration ( const QString & decoration )
- void restoreOverrideCursor ()
- bool reverseLayout ()
- void setColorSpec ( int spec )
- void setCursorFlashTime ( int msecs )
- void setDesktopSettingsAware ( bool on )
- void setDoubleClickInterval ( int ms )
- void setEffectEnabled ( Qt::UIEffect effect, bool enable = true )
- void setFont ( const QFont & font, const char * className = 0 )
- void setGlobalStrut ( const QSize & strut )
- void setOverrideCursor ( const QCursor & cursor, bool replace = false )
- void setPalette ( const QPalette & palette, const char * className = 0 )
- void setReverseLayout ( bool b )
- void setStartDragDistance ( int l )
- void setStartDragTime ( int ms )
- void setStyle ( QStyle * style )
- QStyle * setStyle ( const QString & style )
- void setWheelScrollLines ( int n )
- void setWindowIcon ( const QPixmap & pixmap )
- int startDragDistance ()
- int startDragTime ()
- QStyle & style ()
- void syncX ()
- QWidget * topLevelAt ( const QPoint & p )
- QWidget * topLevelAt ( int x, int y )
- QWidgetList topLevelWidgets ()
- int wheelScrollLines ()
- QWidget * widgetAt ( int x, int y )
- QWidget * widgetAt ( const QPoint & pos )
- const QPixmap & windowIcon ()

- 16 static public members inherited from QCoreApplication
- 4 static public members inherited from QObject

### Protected Functions

- 9 protected functions inherited from QObject

### Related Non-Members

- void qAddPostRoutine ( QtCleanUpFunction ptr )

## Detailed Description

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:

- It initializes the application with the user's desktop settings such as palette(), font() and doubleClickInterval(). It keeps track of these properties in case the user changes the desktop globally, for example through some kind of control panel.
- It performs event handling, meaning that it receives events from the underlying window system and dispatches them to the relevant widgets. By using sendEvent() and postEvent() you can send your own events to widgets.
- It parses common command line arguments and sets its internal state accordingly. See the constructor documentation below for more details about this.
- It defines the application's look and feel, which is encapsulated in a QStyle object. This can be changed at runtime with setStyle().
- It specifies how the application is to allocate colors. See setColorSpec() for details.
- It provides localization of strings that are visible to the user via translate().
- It provides some magical objects like the desktop() and the clipboard().
- It knows about the application's windows. You can ask which widget is at a certain position using widgetAt(), get a list of topLevelWidgets() and closeAllWindows(), etc.
- It manages the application's mouse cursor handling, see setOverrideCursor()
- On the X window system, it provides functions to flush and sync the communication stream, see flushX() and syncX().
- It provides support for sophisticated session management. This makes it possible for applications to terminate gracefully when the user logs out, to cancel a shutdown process if termination isn't possible and even to preserve the entire application's state for a future session. See isSessionRestored(), sessionId() and commitData() and saveState() for details.

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. (Note also that for X11, setMainWidget() may change the main widget according to the `-geometry` option. To preserve this functionality, you must set your defaults before setMainWidget() and any overrides after.)

Groups of functions
System settings | desktopSettingsAware(), setDesktopSettingsAware(), cursorFlashTime(), setCursorFlashTime(), doubleClickInterval(), setDoubleClickInterval(), wheelScrollLines(), setWheelScrollLines(), palette(), setPalette(), font(), setFont(), fontMetrics().
Event handling | exec(), processEvents(), enter_loop(), exit_loop(), exit(), quit(). sendEvent(), postEvent(), sendPostedEvents(), removePostedEvents(), hasPendingEvents(), notify(), macEventFilter(), qwsEventFilter(), x11EventFilter(), x11ProcessEvent(), winEventFilter().
GUI Styles | style(), setStyle(), polish().
Color usage | colorSpec(), setColorSpec(), qwsSetCustomColors().
Text handling | installTranslator(), removeTranslator() translate().
Widgets | mainWidget(), setMainWidget(), allWidgets(), topLevelWidgets(), desktop(), activePopupWidget(), activeModalWidget(), clipboard(), focusWidget(), winFocus(), activeWindow(), widgetAt().
Advanced cursor handling | overrideCursor(), setOverrideCursor(), restoreOverrideCursor().
X Window System synchronization | flushX(), syncX().
Session management | isSessionRestored(), sessionId(), commitData(), saveState().
Threading | lock(), unlock(), locked(), tryLock(),
Miscellaneous | closeAllWindows(), startingUp(), closingDown(), type().

Non-GUI programs: While Qt is not optimized or designed for writing non-GUI programs, it's possible to use some of its classes without creating a QApplication. This can be useful if you wish to share code between a non-GUI server and a GUI client.

## Member Type Documentation

### enum QApplication::ColorSpec

`QApplication::NormalColor` | the default color allocation policy
`QApplication::CustomColor` | the same as NormalColor for X11; allocates colors to a palette on demand under Windows
`QApplication::ManyColor` | the right choice for applications that use thousands of colors

See setColorSpec() for full details.

### enum QApplication::Type

`QApplication::Tty` | a console application
`QApplication::GuiClient` | a GUI client application
`QApplication::GuiServer` | a GUI server application

## Member Function Documentation

### QApplication::QApplication ( int & argc, char ** argv )

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 with the QT_NO_DEBUG flag defined):

- -nograb, tells Qt that it must never grab the mouse or the keyboard.
- -dograb (only under X11), running under a debugger can cause an implicit -nograb, use -dograb to override.
- -sync (only under X11), switches to synchronous mode for debugging.

See Debugging Techniques for a more detailed explanation.

All Qt programs automatically support the following command line options:

- -style= style, sets the application GUI style. Possible values are `motif`, `windows`, and `platinum`. If you compiled Qt with additional styles or have additional styles as plugins these will be available to the `-style` command line option.
- -style style, is the same as listed above.
- -session= session, restores the application from an earlier session.
- -session session, is the same as listed above.
- -widgetcount, prints debug message at the end about number of widgets left undestroyed and maximum number of widgets existed at the same time

The X11 version of Qt also supports some traditional X11 command line options:

- -display display, sets the X display (default is $DISPLAY).
- -geometry geometry, sets the client geometry of the main widget.
- -fn or `-font` font, defines the application font. The font should be specified using an X logical font description.
- -bg or `-background` color, sets the default background color and an application palette (light and dark shades are calculated).
- -fg or `-foreground` color, sets the default foreground color.
- -btn or `-button` color, sets the default button color.
- -name name, sets the application name.
- -title title, sets the application title (caption).
- -visual `TrueColor`, forces the application to use a TrueColor visual on an 8-bit display.
- -ncols count, limits the number of colors allocated in the color cube on an 8-bit display, if the application is using the `QApplication::ManyColor` color specification. If count is 216 then a 6x6x6 color cube is used (i.e. 6 levels of red, 6 of green, and 6 of blue); for other values, a cube approximately proportional to a 2x3x1 cube is used.
- -cmap, causes the application to install a private color map on an 8-bit display.

See also argc() and argv().

### QApplication::QApplication ( int & argc, char ** argv, bool GUIenabled )

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

### QApplication::QApplication ( int & argc, char ** argv, Type type )

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

### QApplication::QApplication ( Display * dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0 )

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.

### QApplication::QApplication ( Display * dpy, int argc, char ** argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0 )

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.

### QApplication::~QApplication () `[virtual]`

Cleans up any window system resources that were allocated by this application. Sets the global variable `qApp` to 0.

### void QApplication::aboutQt () `[slot]`

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

### QWidget * QApplication::activeModalWidget () `[static]`

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

### QWidget * QApplication::activePopupWidget () `[static]`

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

### QWidget * QApplication::activeWindow () const

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

### QWidgetList QApplication::allWidgets () `[static]`

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

### void QApplication::beep () `[static]`

Sounds the bell, using the default volume and sound.

### QClipboard * QApplication::clipboard () `[static]`

Returns a pointer to the application global clipboard.

### void QApplication::closeAllWindows () `[slot]`

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

        // when the last window is closed, the application should quit
        connect(qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()));

The windows are closed in random order, until one window does not accept the close event.

See also QWidget::close(), QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(), and QWidget::isTopLevel().

### int QApplication::colorSpec () `[static]`

Returns the color specification.

See also QApplication::setColorSpec().

### void QApplication::commitData ( QSessionManager & sm ) `[virtual]`

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.

### int QApplication::cursorFlashTime () `[static]`

Returns the text cursor's flash (blink) time in milliseconds. The flash time is the time required to display, invert and restore the caret display.

The default value on X11 is 1000 milliseconds. On Windows, the control panel value is used.

Widgets should not cache this value since it may be changed at any time by the user changing the global desktop settings.

See also setCursorFlashTime().

### QDesktopWidget * QApplication::desktop () `[static]`

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

### bool QApplication::desktopSettingsAware () `[static]`

Returns the value set by setDesktopSettingsAware(); by default true.

See also setDesktopSettingsAware().

### int QApplication::doubleClickInterval () `[static]`

Returns the maximum duration for a double click.

The default value on X11 is 400 milliseconds. On Windows and Mac OS X, the operating system's value is used.

See also setDoubleClickInterval().

### QWidget * QApplication::focusWidget () const

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

### QFont QApplication::font ( const QWidget * w = 0 ) `[static]`

Returns the default font for the widget w, or the default application font if w is 0.

See also setFont(), fontMetrics(), and QWidget::font().

### QFontMetrics QApplication::fontMetrics () `[static]`

Returns display (screen) font metrics for the application font.

See also font(), setFont(), QWidget::fontMetrics(), and QPainter::fontMetrics().

### QSize QApplication::globalStrut () `[static]`

Returns the application's global strut.

The strut is a size object whose dimensions are the minimum that any GUI element that the user can interact with should have. For example no button should be resized to be smaller than the global strut size.

See also setGlobalStrut().

### Qt::Alignment QApplication::horizontalAlignment ( Qt::Alignment align ) `[static]`

Strips out vertical alignment flags and transforms an alignment align of Qt::AlignAuto into Qt::AlignLeft or Qt::AlignRight according to the language used. The other horizontal alignment flags are left untouched.

### bool QApplication::isEffectEnabled ( Qt::UIEffect effect ) `[static]`

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.

### bool QApplication::isSessionRestored () const

Returns true if the application has been restored from an earlier session; otherwise returns false.

See also sessionId(), commitData(), and saveState().

### void QApplication::lastWindowClosed () `[signal]`

This signal is emitted when the user has closed the last top level window.

The signal is very useful when your application has many top level widgets but no main widget. You can then connect it to the quit() slot.

For convenience, this signal is not emitted for transient top level widgets such as popup menus and dialogs.

See also mainWidget(), topLevelWidgets(), QWidget::isTopLevel(), and QWidget::close().

### bool QApplication::macEventFilter ( EventHandlerCallRef caller, EventRef event ) `[virtual]`

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.

### QWidget * QApplication::mainWidget () const

Returns the main application widget, or 0 if there is no main widget.

See also setMainWidget().

### QCursor * QApplication::overrideCursor () `[static]`

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

### QPalette QApplication::palette () `[static]`

Returns the application palette.

See also setPalette() and QWidget::palette().

### QPalette QApplication::palette ( const QWidget * w ) `[static]`

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

If a widget is passed in w, the default palette for the widget's class is returned. This may or may not be the application palette. In most cases there isn't a special palette for certain types of widgets, but one notable exception is the popup menu under Windows, if the user has defined a special background color for menus in the display settings.

See also setPalette() and QWidget::palette().

### QPalette QApplication::palette ( const char * className ) `[static]`

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns the palette for widgets of the given className.

See also setPalette() and QWidget::palette().

### void QApplication::polish ( QWidget * w ) `[virtual]`

Initialization of the appearance of the widget w before it is first shown.

Usually widgets call this automatically when they are polished. It may be used to do some style-based central customization of widgets.

Note that you are not limited to the public functions of QWidget. Instead, based on meta information like QObject::className() you are able to customize any kind of widget.

See also QStyle::polish(), setPalette(), and setFont().

### QDecoration & QApplication::qwsDecoration () `[static]`

Return the QWSDecoration used for decorating windows.

This method is non-portable. It is available only in Qt/Embedded.

See also QDecoration.

### bool QApplication::qwsEventFilter ( QWSEvent * event ) `[virtual]`

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.

### void QApplication::qwsSetCustomColors ( QRgb * colorTable, int start, int numColors )

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.

### void QApplication::qwsSetDecoration ( QDecoration * dec ) `[static]`

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.

### QDecoration * QApplication::qwsSetDecoration ( const QString & decoration ) `[static]`

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.

### void QApplication::restoreOverrideCursor () `[static]`

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

### bool QApplication::reverseLayout () `[static]`

Returns true if all dialogs and widgets will be laid out in a mirrored (right to left) fashion. Returns false if dialogs and widgets will be laid out left to right.

See also setReverseLayout().

### void QApplication::saveState ( QSessionManager & sm ) `[virtual]`

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.

### QString QApplication::sessionId () const

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

### QString QApplication::sessionKey () const

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

### void QApplication::setActiveWindow ( QWidget * act )

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

### void QApplication::setColorSpec ( int spec ) `[static]`

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:

- QApplication::NormalColor. This is the default color allocation strategy. Use this option if your application uses buttons, menus, texts and pixmaps with few colors. With this option, the application uses system global colors. This works fine for most applications under X11, but on Windows machines it may cause dithering of non-standard colors.
- QApplication::CustomColor. Use this option if your application needs a small number of custom colors. On X11, this option is the same as NormalColor. On Windows, Qt creates a Windows palette, and allocates colors to it on demand.
- QApplication::ManyColor. Use this option if your application is very color hungry (e.g. it requires thousands of colors). Under X11 the effect is:
  - For 256-color displays which have at best a 256 color true color visual, the default visual is used, and colors are allocated from a color cube. The color cube is the 6x6x6 (216 color) "Web palette" (the red, green, and blue components always have one of the following values: 0x00, 0x33, 0x66, 0x99, 0xCC, or 0xFF), but the number of colors can be changed by the -ncols option. The user can force the application to use the true color visual with the -visual option.
  - For 256-color displays which have a true color visual with more than 256 colors, use that visual. Silicon Graphics X servers have this feature, for example. They provide an 8 bit visual by default but can deliver true color when asked.

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

### void QApplication::setCursorFlashTime ( int msecs ) `[static]`

Sets the text cursor's flash (blink) time to msecs milliseconds. The flash time is the time required to display, invert and restore the caret display. Usually the text cursor is displayed for msecs/2 milliseconds, then hidden for msecs/2 milliseconds, but this may vary.

Note that on Microsoft Windows, calling this function sets the cursor flash time for all windows.

See also cursorFlashTime().

### void QApplication::setDesktopSettingsAware ( bool on ) `[static]`

By default, Qt will try to use the current standard colors, fonts etc., from the underlying window system's desktop settings, and use them for all relevant widgets. This behavior can be switched off by calling this function with on set to false.

This static function must be called before creating the QApplication object, like this:

        int main(int argc, char** argv) {
          QApplication::setDesktopSettingsAware(false); // I know better than the user
          QApplication myApp(argc, argv); // Use default fonts & colors
          ...
        }

See also desktopSettingsAware().

### void QApplication::setDoubleClickInterval ( int ms ) `[static]`

Sets the time limit that distinguishes a double click from two consecutive mouse clicks to ms milliseconds.

On Microsoft Windows, calling this function sets the double click interval for all windows.

See also doubleClickInterval().

### void QApplication::setEffectEnabled ( Qt::UIEffect effect, bool enable = true ) `[static]`

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

### void QApplication::setFont ( const QFont & font, const char * className = 0 ) `[static]`

Changes the default application font to font. If className is passed, the change applies only to classes that inherit className (as reported by QObject::inherits()).

On application start-up, the default font depends on the window system. It can vary depending on both the window system version and the locale. This function lets you override the default font; but overriding may be a bad idea because, for example, some locales need extra-large fonts to support their special characters.

See also font(), fontMetrics(), and QWidget::setFont().

### void QApplication::setGlobalStrut ( const QSize & strut ) `[static]`

Sets the application's global strut to strut.

The strut is a size object whose dimensions are the minimum that any GUI element that the user can interact with should have. For example no button should be resized to be smaller than the global strut size.

The strut size should be considered when reimplementing GUI controls that may be used on touch-screens or similar IO-devices.

Example:

        QSize& WidgetClass::sizeHint() const
        {
            return QSize(80, 25).expandedTo(QApplication::globalStrut());
        }

See also globalStrut().

### void QApplication::setMainWidget ( QWidget * mainWidget ) `[virtual]`

Sets the application's main widget to mainWidget.

In most respects the main widget is like any other widget, except that if it is closed, the application exits. Note that QApplication does not take ownership of the mainWidget, so if you create your main widget on the heap you must delete it yourself.

You need not have a main widget; connecting lastWindowClosed() to quit() is an alternative.

For X11, this function also resizes and moves the main widget according to the -geometry command-line option, so you should set the default geometry (using QWidget::setGeometry()) before calling setMainWidget().

See also mainWidget(), exec(), and quit().

### void QApplication::setOverrideCursor ( const QCursor & cursor, bool replace = false ) `[static]`

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. Every setOverrideCursor() must eventually be followed by a corresponding restoreOverrideCursor(), otherwise the stack will never be emptied.

If replace is true, the new cursor will replace the last override cursor (the stack keeps its depth). If replace is false, the new stack is pushed onto the top of the stack.

Example:

        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        calculateHugeMandelbrot();              // lunch time...
        QApplication::restoreOverrideCursor();

See also overrideCursor(), restoreOverrideCursor(), and QWidget::setCursor().

### void QApplication::setPalette ( const QPalette & palette, const char * className = 0 ) `[static]`

Changes the default application palette to palette.

If className is passed, the change applies only to widgets that inherit className (as reported by QObject::inherits()). If className is left 0, the change affects all widgets, thus overriding any previously set class specific palettes.

The palette may be changed according to the current GUI style in QStyle::polish().

See also QWidget::setPalette(), palette(), and QStyle::polish().

### void QApplication::setReverseLayout ( bool b ) `[static]`

If b is true, all dialogs and widgets will be laid out in a mirrored fashion, as required by right to left languages such as Arabic and Hebrew. If b is false, dialogs and widgets are laid out left to right.

Changing this flag in runtime does not cause a relayout of already instantiated widgets.

See also reverseLayout().

### void QApplication::setStartDragDistance ( int l ) `[static]`

Sets the distance after which a drag should start to l pixels.

See also startDragDistance().

### void QApplication::setStartDragTime ( int ms ) `[static]`

Sets the time after which a drag should start to ms ms.

See also startDragTime().

### void QApplication::setStyle ( QStyle * style ) `[static]`

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

### QStyle * QApplication::setStyle ( const QString & style ) `[static]`

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.

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 style is passed, otherwise the QStyle object returned is set as the application's GUI style.

### void QApplication::setWheelScrollLines ( int n ) `[static]`

Sets the number of lines to scroll when the mouse wheel is rotated to n.

If this number exceeds the number of visible lines in a certain widget, the widget should interpret the scroll operation as a single page up / page down operation instead.

See also wheelScrollLines().

### void QApplication::setWindowIcon ( const QPixmap & pixmap ) `[static]`

Sets the default window icon to pixmap.

See also windowIcon().

### int QApplication::startDragDistance () `[static]`

If you support drag and drop in you application and a drag should start after a mouse click and after moving the mouse a certain distance, you should use the value which this method returns as the distance.

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 `currPos`, you can find out if a drag should be started with code like this:

        if ((startPos - currPos).manhattanLength() >
             QApplication::startDragDistance())
          startTheDrag();

Qt uses this value internally, e.g. in QFileDialog.

The default value is 4 pixels.

See also setStartDragDistance(), startDragTime(), and QPoint::manhattanLength().

### int QApplication::startDragTime () `[static]`

If you support drag and drop in you application and a drag should start after a mouse click and after a certain time elapsed, you should use the value which this method returns as the delay (in ms).

Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for starting a drag.

The default value is 500 ms.

See also setStartDragTime() and startDragDistance().

### QStyle & QApplication::style () `[static]`

Returns the application's style object.

See also setStyle() and QStyle.

### void QApplication::syncX () `[static]`

Synchronizes with the X server in the X11 implementation. This normally takes some time. Does nothing on other platforms.

### QWidget * QApplication::topLevelAt ( const QPoint & p ) `[static]`

Returns the top level widget at the point p.

### QWidget * QApplication::topLevelAt ( int x, int y ) `[static]`

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

### QWidgetList QApplication::topLevelWidgets () `[static]`

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->isHidden())
                w->show();
        }

See also allWidgets(), QWidget::isTopLevel(), QWidget::isHidden(), and QList::isEmpty().

### Type QApplication::type () const

Returns the type of application, Tty, GuiClient or GuiServer.

### int QApplication::wheelScrollLines () `[static]`

Returns the number of lines to scroll when the mouse wheel is rotated.

See also setWheelScrollLines().

### QWidget * QApplication::widgetAt ( int x, int y ) `[static]`

Returns a pointer to the widget at global screen position (x, y), or 0 if there is no Qt widget there.

This function is normally rather slow.

See also QCursor::pos(), QWidget::grabMouse(), and QWidget::grabKeyboard().

### QWidget * QApplication::widgetAt ( const QPoint & pos ) `[static]`

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a pointer to the widget at global screen position pos, or 0 if there is no Qt widget there.

### void QApplication::winFocus ( QWidget * widget, bool gotFocus )

If gotFocus is true, widget will become the active window. Otherwise the active window is reset to NULL.

### const QPixmap & QApplication::windowIcon () `[static]`

Returns the default window icon.

See also setWindowIcon().

### bool QApplication::x11EventFilter ( XEvent * event ) `[virtual]`

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

### int QApplication::x11ProcessEvent ( XEvent * event )

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

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