QGuiApplication Class

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

Header: #include <QGuiApplication>
qmake: QT += gui
Since: Qt 5.0
Inherits: QCoreApplication.
Inherited By:

QApplication.

Properties

Public Functions

QGuiApplication(int & argc, char ** argv)
virtual ~QGuiApplication()
qreal devicePixelRatio() const
bool isSavingSession() const
bool isSessionRestored() const
QString sessionId() const
QString sessionKey() const

Reimplemented Public Functions

virtual bool notify(QObject * object, QEvent * event)

Signals

void applicationStateChanged(Qt::ApplicationState state)
void commitDataRequest(QSessionManager & manager)
void focusObjectChanged(QObject * focusObject)
void focusWindowChanged(QWindow * focusWindow)
void fontDatabaseChanged()
void lastWindowClosed()
void layoutDirectionChanged(Qt::LayoutDirection direction)
void paletteChanged(const QPalette & palette)
void saveStateRequest(QSessionManager & manager)
void screenAdded(QScreen * screen)
void screenRemoved(QScreen * screen)

Static Public Members

QWindowList allWindows()
QString applicationDisplayName()
Qt::ApplicationState applicationState()
void changeOverrideCursor(const QCursor & cursor)
QClipboard * clipboard()
bool desktopSettingsAware()
int exec()
QObject * focusObject()
QWindow * focusWindow()
QFont font()
QInputMethod * inputMethod()
bool isLeftToRight()
bool isRightToLeft()
Qt::KeyboardModifiers keyboardModifiers()
Qt::LayoutDirection layoutDirection()
QWindow * modalWindow()
Qt::MouseButtons mouseButtons()
QCursor * overrideCursor()
QPalette palette()
QFunctionPointer platformFunction(const QByteArray & function)
QString platformName()
QPlatformNativeInterface * platformNativeInterface()
QScreen * primaryScreen()
Qt::KeyboardModifiers queryKeyboardModifiers()
bool quitOnLastWindowClosed()
void restoreOverrideCursor()
QList<QScreen *> screens()
void setApplicationDisplayName(const QString & name)
void setDesktopSettingsAware(bool on)
void setFont(const QFont & font)
void setLayoutDirection(Qt::LayoutDirection direction)
void setOverrideCursor(const QCursor & cursor)
void setPalette(const QPalette & pal)
void setQuitOnLastWindowClosed(bool quit)
void setWindowIcon(const QIcon & icon)
QStyleHints * styleHints()
void sync()
QWindow * topLevelAt(const QPoint & pos)
QWindowList topLevelWindows()
QIcon windowIcon()

Reimplemented Protected Functions

virtual bool event(QEvent * e)

Additional Inherited Members

Detailed Description

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

QGuiApplication 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. In addition, QGuiApplication handles most of the system-wide and application-wide settings.

For any GUI application using Qt, there is precisely one QGuiApplication object no matter whether the application has 0, 1, 2 or more windows at any given time. For non-GUI Qt applications, use QCoreApplication instead, as it does not depend on the Qt GUI module. For QWidget based Qt applications, use QApplication instead, as it provides some functionality needed for creating QWidget instances.

The QGuiApplication object is accessible through the instance() function, which returns a pointer equivalent to the global qApp pointer.

QGuiApplication's main areas of responsibility are:

  • It initializes the application with the user's desktop settings, such as palette(), font() and styleHints(). 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. You can send your own events to windows by using sendEvent() and postEvent().
  • It parses common command line arguments and sets its internal state accordingly. See the constructor documentation below for more details.
  • It provides localization of strings that are visible to the user via translate().
  • It provides some magical objects like the clipboard().
  • It knows about the application's windows. You can ask which window is at a certain position using topLevelAt(), get a list of topLevelWindows(), etc.
  • It manages the application's mouse cursor handling, see setOverrideCursor()
  • 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 commitDataRequest() and saveStateRequest() for details.

Since the QGuiApplication object does so much initialization, it must be created before any other objects related to the user interface are created. QGuiApplication also deals with common command line arguments. Hence, it is usually a good idea to create it before any interpretation or modification of argv is done in the application itself.

Groups of functions
System settingsdesktopSettingsAware(), setDesktopSettingsAware(), styleHints(), palette(), setPalette(), font(), setFont().
Event handlingexec(), processEvents(), exit(), quit(). sendEvent(), postEvent(), sendPostedEvents(), removePostedEvents(), hasPendingEvents(), notify().
WindowsallWindows(), topLevelWindows(), focusWindow(), clipboard(), topLevelAt().
Advanced cursor handlingoverrideCursor(), setOverrideCursor(), restoreOverrideCursor().
Session managementisSessionRestored(), sessionId(), commitDataRequest(), saveStateRequest().
MiscellaneousstartingUp(), closingDown(), type().

See also QCoreApplication, QAbstractEventDispatcher, and QEventLoop.

Property Documentation

applicationDisplayName : QString

This property holds the user-visible name of this application.

This name is shown to the user, for instance in window titles. It can be translated, if necessary.

If not set, the application display name defaults to the application name.

This property was introduced in Qt 5.0.

Access functions:

QString applicationDisplayName()
void setApplicationDisplayName(const QString & name)

See also applicationName.

layoutDirection : Qt::LayoutDirection

This property holds the default layout direction for this application.

On system start-up, the default layout direction depends on the application's language.

The notifier signal was introduced in Qt 5.4.

Access functions:

Qt::LayoutDirection layoutDirection()
void setLayoutDirection(Qt::LayoutDirection direction)

Notifier signal:

void layoutDirectionChanged(Qt::LayoutDirection direction)

See also QWidget::layoutDirection, isLeftToRight(), and isRightToLeft().

platformName : const QString

This property holds the name of the underlying platform plugin.

The QPA platform plugins are located in qtbase\src\plugins\platforms. At the time of writing, the following platform plugin names are supported:

  • android
  • cocoa is a platform plugin for Mac OS X.
  • directfb
  • eglfs is a platform plugin for running Qt5 applications on top of EGL and OpenGL ES 2.0 without an actual windowing system (like X11 or Wayland). For more information, see EGLFS.
  • ios
  • kms is an experimental platform plugin using kernel modesetting and DRM (Direct Rendering Manager).
  • linuxfb writes directly to the framebuffer. For more information, see LinuxFB.
  • minimal is provided as an examples for developers who want to write their own platform plugins. However, you can use the plugin to run GUI applications in environments without a GUI, such as servers.
  • minimalegl is an example plugin.
  • offscreen
  • openwfd
  • qnx
  • windows
  • xcb is the X11 plugin used on regular desktop Linux platforms.

For more information about the platform plugins for embedded Linux devices, see Qt for Embedded Linux.

Access functions:

QString platformName()

quitOnLastWindowClosed : bool

This property holds whether the application implicitly quits when the last window is closed.

The default is true.

If this property is true, the applications quits when the last visible primary window (i.e. window with no parent) is closed.

Access functions:

bool quitOnLastWindowClosed()
void setQuitOnLastWindowClosed(bool quit)

See also quit() and QWindow::close().

windowIcon : QIcon

This property holds the default window icon.

Access functions:

QIcon windowIcon()
void setWindowIcon(const QIcon & icon)

See also QWindow::setIcon() and Setting the Application Icon.

Member Function Documentation

QGuiApplication::​QGuiApplication(int & argc, char ** argv)

Initializes the window system and constructs an application object with argc command line arguments in argv.

Warning: The data referred to by argc and argv must stay valid for the entire lifetime of the QGuiApplication object. In addition, argc must be greater than zero and argv must contain at least one valid character string.

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 pixmaps, bitmaps etc.).

Note: argc and argv might be changed as Qt removes command line arguments that it recognizes.

Supported Command Line Options

All Qt programs automatically support a set of command-line options that allow modifying the way Qt will interact with the windowing system. Some of the options are also accessible via environment variables, which are the preferred form if the application can launch GUI sub-processes or other applications (environment variables will be inherited by child processes). When in doubt, use the environment variables.

The options currently supported are the following:

  • -platform platformName[:options], specifies the Qt Platform Abstraction (QPA) plugin.

    Overridden by the QT_QPA_PLATFORM environment variable.

  • -platformpluginpath path, specifies the path to platform plugins.

    Overridden by the QT_QPA_PLATFORM_PLUGIN_PATH environment variable.

  • -platformtheme platformTheme, specifies the platform theme.

    Overridden by the QT_QPA_PLATFORMTHEME environment variable.

  • -plugin plugin, specifies additional plugins to load. The argument may appear multiple times.

    Overridden by the QT_QPA_GENERIC_PLUGINS environment variable.

  • -qmljsdebugger=, activates the QML/JS debugger with a specified port. The value must be of format port:1234[,block], where block is optional and will make the application wait until a debugger connects to it.
  • -qwindowgeometry geometry, specifies window geometry for the main window using the X11-syntax. For example: -qwindowgeometry 100x100+50+50
  • -qwindowicon, sets the default window icon
  • -qwindowtitle, sets the title of the first window
  • -reverse, sets the application's layout direction to Qt::RightToLeft. This option is intended to aid debugging and should not be used in production. The default value is automatically detected from the user's locale (see also QLocale::textDirection()).
  • -session session, restores the application from an earlier session.

The following standard command line options are available for X11:

  • -display hostname:screen_number, switches displays on X11.

    Overrides the DISPLAY environment variable.

  • -geometry geometry, same as -qwindowgeometry.

Platform-Specific Arguments

You can specify platform-specific arguments for the -platform option. Place them after the platform plugin name following a colon as a comma-separated list. For example, -platform windows:dialogs=xp,fontengine=freetype.

The following parameters are available for -platform windows:

  • dialogs=[xp|none], xp uses XP-style native dialogs and none disables them.
  • fontengine=freetype, uses the FreeType font engine.

For more information about the platform-specific arguments available for embedded Linux platforms, see Qt for Embedded Linux.

See also arguments() and QGuiApplication::platformName.

[virtual] QGuiApplication::​~QGuiApplication()

Destructs the application.

[static] QWindowList QGuiApplication::​allWindows()

Returns a list of all the windows in the application.

The list is empty if there are no windows.

See also topLevelWindows().

[static] Qt::ApplicationState QGuiApplication::​applicationState()

Returns the current state of the application.

You can react to application state changes to perform actions such as stopping/resuming CPU-intensive tasks, freeing/loading resources or saving/restoring application data.

This function was introduced in Qt 5.2.

[signal] void QGuiApplication::​applicationStateChanged(Qt::ApplicationState state)

This signal is emitted when the state of the application changes.

This function was introduced in Qt 5.2.

See also applicationState().

[static] void QGuiApplication::​changeOverrideCursor(const QCursor & cursor)

Changes the currently active application override cursor to cursor.

This function has no effect if setOverrideCursor() was not called.

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

[static] QClipboard * QGuiApplication::​clipboard()

Returns the object for interacting with the clipboard.

[signal] void QGuiApplication::​commitDataRequest(QSessionManager & manager)

This signal deals with session management. It is emitted 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.

You should not exit the application within this signal. Instead, the session manager may or may not do this afterwards, depending on the context.

Warning: Within this signal, no user interaction is possible, unless you ask the manager for explicit permission. See QSessionManager::allowsInteraction() and QSessionManager::allowsErrorInteraction() for details and example usage.

Note: You should use Qt::DirectConnection when connecting to this signal.

This function was introduced in Qt 4.2.

See also isSessionRestored(), sessionId(), saveStateRequest(), and Session Management.

[static] bool QGuiApplication::​desktopSettingsAware()

Returns true if Qt is set to use the system's standard colors, fonts, etc.; otherwise returns false. The default is true.

See also setDesktopSettingsAware().

qreal QGuiApplication::​devicePixelRatio() const

Returns the highest screen device pixel ratio found on the system. This is the ratio between physical pixels and device-independent pixels.

Use this function only when you don't know which window you are targeting. If you do know the target window, use QWindow::devicePixelRatio() instead.

See also QWindow::devicePixelRatio().

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

Reimplemented from QObject::event().

[static] int QGuiApplication::​exec()

Enters the main event loop and waits until exit() is called, and then 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, no user interaction can take place before calling exec().

To make your application perform idle processing, e.g., executing a special function whenever there are no pending events, use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().

We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function. This is because, on some platforms, the QApplication::exec() call may not return.

See also quitOnLastWindowClosed, quit(), exit(), processEvents(), and QCoreApplication::exec().

[static] QObject * QGuiApplication::​focusObject()

Returns the QObject in currently active window that will be final receiver of events tied to focus, such as key events.

[signal] void QGuiApplication::​focusObjectChanged(QObject * focusObject)

This signal is emitted when final receiver of events tied to focus is changed. focusObject is the new receiver.

See also focusObject().

[static] QWindow * QGuiApplication::​focusWindow()

Returns the QWindow that receives events tied to focus, such as key events.

[signal] void QGuiApplication::​focusWindowChanged(QWindow * focusWindow)

This signal is emitted when the focused window changes. focusWindow is the new focused window.

See also focusWindow().

[static] QFont QGuiApplication::​font()

Returns the default application font.

See also setFont().

[signal] void QGuiApplication::​fontDatabaseChanged()

This signal is emitted when application fonts are loaded or removed.

See also QFontDatabase::addApplicationFont(), QFontDatabase::addApplicationFontFromData(), QFontDatabase::removeAllApplicationFonts(), and QFontDatabase::removeApplicationFont().

[static] QInputMethod * QGuiApplication::​inputMethod()

returns the input method.

The input method returns properties about the state and position of the virtual keyboard. It also provides information about the position of the current focused input element.

See also QInputMethod.

[static] bool QGuiApplication::​isLeftToRight()

Returns true if the application's layout direction is Qt::LeftToRight; otherwise returns false.

See also layoutDirection() and isRightToLeft().

[static] bool QGuiApplication::​isRightToLeft()

Returns true if the application's layout direction is Qt::RightToLeft; otherwise returns false.

See also layoutDirection() and isLeftToRight().

bool QGuiApplication::​isSavingSession() const

Returns true if the application is currently saving the session; otherwise returns false.

This is true when commitDataRequest() and saveStateRequest() are emitted, but also when the windows are closed afterwards by session management.

This function was introduced in Qt 5.0.

See also sessionId(), commitDataRequest(), and saveStateRequest().

bool QGuiApplication::​isSessionRestored() const

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

See also sessionId(), commitDataRequest(), and saveStateRequest().

[static] Qt::KeyboardModifiers QGuiApplication::​keyboardModifiers()

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

[signal] void QGuiApplication::​lastWindowClosed()

This signal is emitted from exec() when the last visible primary window (i.e. window with no parent) is closed.

By default, QGuiApplication quits after this signal is emitted. This feature can be turned off by setting quitOnLastWindowClosed to false.

See also QWindow::close() and QWindow::isTopLevel().

Returns the most recently shown modal window. If no modal windows are visible, this function returns zero.

A modal window is a window which has its modality property set to Qt::WindowModal or Qt::ApplicationModal. A modal window must be closed before the user can continue with other parts of the program.

Modal window are organized in a stack. This function returns the modal window at the top of the stack.

See also Qt::WindowModality and QWindow::setModality().

[static] Qt::MouseButtons QGuiApplication::​mouseButtons()

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::MouseButtonPress and QEvent::MouseButtonRelease events).

It should be noted this may not reflect the actual buttons held on the input device at the time of calling but rather the mouse buttons as last reported in one of the above events. If no mouse buttons are being held Qt::NoButton is returned.

See also keyboardModifiers().

[virtual] bool QGuiApplication::​notify(QObject * object, QEvent * event)

Reimplemented from QCoreApplication::notify().

[static] QCursor * QGuiApplication::​overrideCursor()

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

[static] QPalette QGuiApplication::​palette()

Returns the default application palette.

See also setPalette().

[signal] void QGuiApplication::​paletteChanged(const QPalette & palette)

This signal is emitted when the palette of the application changes.

This function was introduced in Qt 5.4.

See also palette().

[static] QFunctionPointer QGuiApplication::​platformFunction(const QByteArray & function)

Returns a function pointer from the platformplugin matching function

[static] QPlatformNativeInterface * QGuiApplication::​platformNativeInterface()

Returns the platform's native interface, for platform specific functionality.

[static] QScreen * QGuiApplication::​primaryScreen()

Returns the primary (or default) screen of the application.

This will be the screen where QWindows are shown, unless otherwise specified.

[static] Qt::KeyboardModifiers QGuiApplication::​queryKeyboardModifiers()

Queries and returns the state of the modifier keys on the keyboard. Unlike keyboardModifiers, this method returns the actual keys held on the input device at the time of calling the method.

It does not rely on the keypress events having been received by this process, which makes it possible to check the modifiers while moving a window, for instance. Note that in most cases, you should use keyboardModifiers(), which is faster and more accurate since it contains the state of the modifiers as they were when the currently processed event was received.

See also keyboardModifiers().

[static] void QGuiApplication::​restoreOverrideCursor()

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

[signal] void QGuiApplication::​saveStateRequest(QSessionManager & manager)

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

You should never exit the application within this signal. 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 signal, no user interaction is possible, unless you ask the manager for explicit permission. See QSessionManager::allowsInteraction() and QSessionManager::allowsErrorInteraction() for details.

Note: You should use Qt::DirectConnection when connecting to this signal.

This function was introduced in Qt 4.2.

See also isSessionRestored(), sessionId(), commitDataRequest(), and Session Management.

[signal] void QGuiApplication::​screenAdded(QScreen * screen)

This signal is emitted whenever a new screen screen has been added to the system.

See also screens(), primaryScreen(), and screenRemoved().

[signal] void QGuiApplication::​screenRemoved(QScreen * screen)

This signal is emitted whenever a screen is removed from the system. It provides an opportunity to manage the windows on the screen before Qt falls back to moving them to the primary screen.

This function was introduced in Qt 5.4.

See also screens(), screenAdded(), QObject::destroyed(), and QWindow::setScreen().

[static] QList<QScreen *> QGuiApplication::​screens()

Returns a list of all the screens associated with the windowing system the application is connected to.

QString QGuiApplication::​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(), commitDataRequest(), and saveStateRequest().

QString QGuiApplication::​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 every time the session is saved. If the shutdown process is cancelled, another session key will be used when shutting down again.

See also isSessionRestored(), sessionId(), commitDataRequest(), and saveStateRequest().

[static] void QGuiApplication::​setDesktopSettingsAware(bool on)

Sets whether Qt should use the system's standard colors, fonts, etc., to on. By default, this is true.

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

int main(int argc, char *argv[])
{
    QApplication::setDesktopSettingsAware(false);
    QApplication app(argc, argv);
    ...
    return app.exec();
}

See also desktopSettingsAware().

[static] void QGuiApplication::​setFont(const QFont & font)

Changes the default application font to font.

See also font().

[static] void QGuiApplication::​setOverrideCursor(const QCursor & cursor)

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

[static] void QGuiApplication::​setPalette(const QPalette & pal)

Changes the default application palette to pal.

See also palette().

[static] QStyleHints * QGuiApplication::​styleHints()

Returns the application's style hints.

The style hints encapsulate a set of platform dependent properties such as double click intervals, full width selection and others.

The hints can be used to integrate tighter with the underlying platform.

See also QStyleHints.

[static] void QGuiApplication::​sync()

Function that can be used to sync Qt state with the Window Systems state.

This function will first empty Qts events by calling QCoreApplication::processEvents(), then the platform plugin will sync up with the windowsystem, and finally Qts events will be delived by another call to QCoreApplication::processEvents();

This function is timeconsuming and its use is discouraged.

This function was introduced in Qt 5.2.

[static] QWindow * QGuiApplication::​topLevelAt(const QPoint & pos)

Returns the top level window at the given position pos, if any.

[static] QWindowList QGuiApplication::​topLevelWindows()

Returns a list of the top-level windows in the application.

See also allWindows().

© 2015 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 the GNU 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.