1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qplatformdefs.h"
43 #include "qabstracteventdispatcher.h"
44 #include "qaccessible.h"
45 #include "qapplication.h"
46 #include "qclipboard.h"
48 #include "qdesktopwidget.h"
52 #include "qfileinfo.h"
53 #include "qgraphicsscene.h"
57 #include "qsessionmanager.h"
59 #include "qstylefactory.h"
60 #include "qtextcodec.h"
61 #include "qtranslator.h"
64 #include "private/qdnd_p.h"
65 #include "qcolormap.h"
67 #include "private/qstylesheetstyle_p.h"
68 #include "private/qstyle_p.h"
69 #include "qmessagebox.h"
70 #include <QtWidgets/qgraphicsproxywidget.h>
71 #include <QtGui/qstylehints.h>
72 #include <QtGui/qinputpanel.h>
74 #include "qinputcontext.h"
75 #include "private/qkeymapper_p.h"
78 #include <private/qt_x11_p.h>
81 #if defined(Q_WS_X11) || defined(Q_OS_SYMBIAN)
82 #include "qinputcontextfactory.h"
85 #include "qguiplatformplugin_p.h"
88 #include <private/qthread_p.h>
90 #include <private/qfont_p.h>
94 #if defined(Q_WS_X11) && !defined(QT_NO_EGL)
98 #include "qapplication_p.h"
99 #include "private/qevent_p.h"
100 #include "qwidget_p.h"
102 #include "qapplication.h"
104 #include "qgesture.h"
105 #include "private/qgesturemanager_p.h"
106 #include "private/qguiapplication_p.h"
107 #include "qplatformfontdatabase_qpa.h"
108 #ifndef QT_NO_LIBRARY
109 #include "qlibrary.h"
113 #include "qdatetime.h"
114 #include "qguifunctions_wince.h"
115 extern bool qt_wince_is_smartphone(); //qguifunctions_wince.cpp
116 extern bool qt_wince_is_mobile(); //qguifunctions_wince.cpp
117 extern bool qt_wince_is_pocket_pc(); //qguifunctions_wince.cpp
120 #include "qdatetime.h"
122 #ifdef QT_MAC_USE_COCOA
123 #include <private/qt_cocoa_helpers_mac_p.h>
126 //#define ALIEN_DEBUG
128 #if defined(Q_OS_SYMBIAN)
129 #include "qt_s60_p.h"
132 static void initResources()
134 #if defined(Q_WS_WINCE)
135 Q_INIT_RESOURCE_EXTERN(qstyle_wince)
136 Q_INIT_RESOURCE(qstyle_wince);
137 #elif defined(Q_OS_SYMBIAN)
138 Q_INIT_RESOURCE_EXTERN(qstyle_s60)
139 Q_INIT_RESOURCE(qstyle_s60);
141 Q_INIT_RESOURCE_EXTERN(qstyle)
142 Q_INIT_RESOURCE(qstyle);
144 Q_INIT_RESOURCE_EXTERN(qmessagebox)
145 Q_INIT_RESOURCE(qmessagebox);
151 Q_CORE_EXPORT void qt_call_post_routines();
153 QApplication::Type qt_appType=QApplication::Tty;
154 QApplicationPrivate *QApplicationPrivate::self = 0;
156 QInputContext *QApplicationPrivate::inputContext = 0;
158 bool QApplicationPrivate::quitOnLastWindowClosed = true;
161 int QApplicationPrivate::autoMaximizeThreshold = -1;
162 bool QApplicationPrivate::autoSipEnabled = false;
164 bool QApplicationPrivate::autoSipEnabled = true;
167 QApplicationPrivate::QApplicationPrivate(int &argc, char **argv, QApplication::Type type, int flags)
168 : QApplicationPrivateBase(argc, argv, flags)
170 application_type = type;
173 #ifndef QT_NO_SESSIONMANAGER
174 is_session_restored = false;
177 quitOnLastWindowClosed = true;
181 qt_compat_resolved = 0;
182 qt_tryAccelEvent = 0;
183 qt_tryComposeUnicode = 0;
184 qt_dispatchAccelEvent = 0;
186 #if defined(Q_WS_QWS) && !defined(QT_NO_DIRECTPAINTER)
190 #ifndef QT_NO_GESTURES
193 #endif // QT_NO_GESTURES
195 #if defined(Q_WS_X11) || defined(Q_WS_WIN)
200 #if defined(Q_WS_WIN)
208 QApplicationPrivate::~QApplicationPrivate()
216 \brief The QApplication class manages the GUI application's control
217 flow and main settings.
219 QApplication contains the main event loop, where all events from the window
220 system and other sources are processed and dispatched. It also handles the
221 application's initialization, finalization, and provides session
222 management. In addition, QApplication handles most of the system-wide and
223 application-wide settings.
225 For any GUI application using Qt, there is precisely \bold one QApplication
226 object, no matter whether the application has 0, 1, 2 or more windows at
227 any given time. For non-GUI Qt applications, use QCoreApplication instead,
228 as it does not depend on the \l QtGui library.
230 The QApplication object is accessible through the instance() function that
231 returns a pointer equivalent to the global qApp pointer.
233 QApplication's main areas of responsibility are:
235 \o It initializes the application with the user's desktop settings
236 such as palette(), font() and doubleClickInterval(). It keeps
237 track of these properties in case the user changes the desktop
238 globally, for example through some kind of control panel.
240 \o It performs event handling, meaning that it receives events
241 from the underlying window system and dispatches them to the
242 relevant widgets. By using sendEvent() and postEvent() you can
243 send your own events to widgets.
245 \o It parses common command line arguments and sets its internal
246 state accordingly. See the \l{QApplication::QApplication()}
247 {constructor documentation} below for more details.
249 \o It defines the application's look and feel, which is
250 encapsulated in a QStyle object. This can be changed at runtime
253 \o It specifies how the application is to allocate colors. See
254 setColorSpec() for details.
256 \o It provides localization of strings that are visible to the
257 user via translate().
259 \o It provides some magical objects like the desktop() and the
262 \o It knows about the application's windows. You can ask which
263 widget is at a certain position using widgetAt(), get a list of
264 topLevelWidgets() and closeAllWindows(), etc.
266 \o It manages the application's mouse cursor handling, see
269 \o On the X window system, it provides functions to flush and sync
270 the communication stream, see flushX() and syncX().
272 \o It provides support for sophisticated \l{Session Management}
273 {session management}. This makes it possible for applications
274 to terminate gracefully when the user logs out, to cancel a
275 shutdown process if termination isn't possible and even to
276 preserve the entire application's state for a future session.
277 See isSessionRestored(), sessionId() and commitData() and
278 saveState() for details.
281 Since the QApplication object does so much initialization, it \e{must} be
282 created before any other objects related to the user interface are created.
283 QApplication also deals with common command line arguments. Hence, it is
284 usually a good idea to create it \e before any interpretation or
285 modification of \c argv is done in the application itself.
289 \o{2,1} Groups of functions
293 \o desktopSettingsAware(),
294 setDesktopSettingsAware(),
296 setCursorFlashTime(),
297 doubleClickInterval(),
298 setDoubleClickInterval(),
299 setKeyboardInputInterval(),
301 setWheelScrollLines(),
317 removePostedEvents(),
335 qwsSetCustomColors().
339 \o installTranslator(),
356 \o Advanced cursor handling
359 restoreOverrideCursor().
362 \o X Window System synchronization
367 \o Session management
368 \o isSessionRestored(),
375 \o closeAllWindows(),
381 \sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
385 \enum QApplication::Type
387 \value Tty a console application
388 \value GuiClient a GUI client application
389 \value GuiServer a GUI server application (for Qt for Embedded Linux)
393 \enum QApplication::ColorSpec
395 \value NormalColor the default color allocation policy
396 \value CustomColor the same as NormalColor for X11; allocates colors
397 to a palette on demand under Windows
398 \value ManyColor the right choice for applications that use thousands of
401 See setColorSpec() for full details.
405 \fn QWidget *QApplication::topLevelAt(const QPoint &point)
407 Returns the top-level widget at the given \a point; returns 0 if
408 there is no such widget.
412 \fn QWidget *QApplication::topLevelAt(int x, int y)
416 Returns the top-level widget at the point (\a{x}, \a{y}); returns
417 0 if there is no such widget.
422 The qt_init() and qt_cleanup() functions are implemented in the
423 qapplication_xyz.cpp file.
426 void qt_init(QApplicationPrivate *priv, int type
428 , Display *display = 0, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0
433 Qt::MouseButtons QApplicationPrivate::mouse_buttons = Qt::NoButton;
434 Qt::KeyboardModifiers QApplicationPrivate::modifier_buttons = Qt::NoModifier;
436 QStyle *QApplicationPrivate::app_style = 0; // default application style
437 QString QApplicationPrivate::styleOverride; // style override
439 #ifndef QT_NO_STYLE_STYLESHEET
440 QString QApplicationPrivate::styleSheet; // default application stylesheet
442 QPointer<QWidget> QApplicationPrivate::leaveAfterRelease = 0;
444 int QApplicationPrivate::app_cspec = QApplication::NormalColor;
445 QPalette *QApplicationPrivate::sys_pal = 0; // default system palette
446 QPalette *QApplicationPrivate::set_pal = 0; // default palette set by programmer
449 Q_GLOBAL_STATIC(QMutex, applicationFontMutex)
450 QFont *QApplicationPrivate::app_font = 0; // default application font
452 QFont *QApplicationPrivate::sys_font = 0; // default system font
453 QFont *QApplicationPrivate::set_font = 0; // default font set by programmer
455 QIcon *QApplicationPrivate::app_icon = 0;
456 QWidget *QApplicationPrivate::main_widget = 0; // main application widget
457 QWidget *QApplicationPrivate::focus_widget = 0; // has keyboard input focus
458 QWidget *QApplicationPrivate::hidden_focus_widget = 0; // will get keyboard input focus after show()
459 QWidget *QApplicationPrivate::active_window = 0; // toplevel with keyboard focus
460 bool QApplicationPrivate::obey_desktop_settings = true; // use winsys resources
461 #ifndef QT_NO_WHEELEVENT
462 int QApplicationPrivate::wheel_scroll_lines; // number of lines to scroll
465 bool Q_WIDGETS_EXPORT qt_tab_all_widgets = true;
466 bool qt_in_tab_key_event = false;
467 int qt_antialiasing_threshold = -1;
468 QSize QApplicationPrivate::app_strut = QSize(0,0); // no default application strut
469 bool QApplicationPrivate::animate_ui = true;
470 bool QApplicationPrivate::animate_menu = false;
471 bool QApplicationPrivate::fade_menu = false;
472 bool QApplicationPrivate::animate_combo = false;
473 bool QApplicationPrivate::animate_tooltip = false;
474 bool QApplicationPrivate::fade_tooltip = false;
475 bool QApplicationPrivate::animate_toolbox = false;
476 bool QApplicationPrivate::widgetCount = false;
477 bool QApplicationPrivate::load_testability = false;
478 #ifdef QT_KEYPAD_NAVIGATION
480 Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadDirectional;
482 Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadTabOrder;
484 QWidget *QApplicationPrivate::oldEditFocus = 0;
487 bool qt_tabletChokeMouse = false;
489 inline bool QApplicationPrivate::isAlien(QWidget *widget)
491 return widget && !widget->isWindow();
494 // ######## move to QApplicationPrivate
495 // Default application palettes and fonts (per widget type)
496 Q_GLOBAL_STATIC(PaletteHash, app_palettes)
497 PaletteHash *qt_app_palettes_hash()
499 return app_palettes();
502 Q_GLOBAL_STATIC_WITH_INITIALIZER(FontHash, app_fonts, { *x = QGuiApplicationPrivate::platformIntegration()->fontDatabase()->defaultFonts(); } )
503 FontHash *qt_app_fonts_hash()
508 QWidgetList *QApplicationPrivate::popupWidgets = 0; // has keyboard input focus
510 QDesktopWidget *qt_desktopWidget = 0; // root window widgets
511 #if !defined(Q_WS_QPA) && !defined(QT_NO_CLIPBOARD)
512 QClipboard *qt_clipboard = 0; // global clipboard object
514 QWidgetList * qt_modal_stack = 0; // stack of modal widgets
515 bool app_do_modal = false;
520 void QApplicationPrivate::process_cmdline()
522 // process platform-indep command line
523 if (!qt_is_gui_used || !argc)
529 for (i=1; i<argc; i++) { // if you add anything here, modify QCoreApplication::arguments()
530 if (argv[i] && *argv[i] != '-') {
534 QByteArray arg = argv[i];
537 if (arg == "-qdevel" || arg == "-qdebug") {
539 } else if (arg.indexOf("-qmljsdebugger=", 0) != -1) {
540 qmljs_debug_arguments = QString::fromLocal8Bit(arg.right(arg.length() - 15));
541 } else if (arg.indexOf("-style=", 0) != -1) {
542 s = QString::fromLocal8Bit(arg.right(arg.length() - 7).toLower());
543 } else if (arg == "-style" && i < argc-1) {
544 s = QString::fromLocal8Bit(argv[++i]).toLower();
545 #ifndef QT_NO_SESSIONMANAGER
546 } else if (arg == "-session" && i < argc-1) {
548 if (argv[i] && *argv[i]) {
549 session_id = QString::fromLatin1(argv[i]);
550 int p = session_id.indexOf(QLatin1Char('_'));
552 session_key = session_id.mid(p +1);
553 session_id = session_id.left(p);
555 is_session_restored = true;
558 #ifndef QT_NO_STYLE_STYLESHEET
559 } else if (arg == "-stylesheet" && i < argc -1) {
560 styleSheet = QLatin1String("file:///");
561 styleSheet.append(QString::fromLocal8Bit(argv[++i]));
562 } else if (arg.indexOf("-stylesheet=") != -1) {
563 styleSheet = QLatin1String("file:///");
564 styleSheet.append(QString::fromLocal8Bit(arg.right(arg.length() - 12)));
566 } else if (qstrcmp(arg, "-widgetcount") == 0) {
568 } else if (qstrcmp(arg, "-testability") == 0) {
569 load_testability = true;
589 Initializes the window system and constructs an application object with
590 \a argc command line arguments in \a argv.
592 \warning The data referred to by \a argc and \a argv must stay valid for
593 the entire lifetime of the QApplication object. In addition, \a argc must
594 be greater than zero and \a argv must contain at least one valid character
597 The global \c qApp pointer refers to this application object. Only one
598 application object should be created.
600 This application object must be constructed before any \l{QPaintDevice}
601 {paint devices} (including widgets, pixmaps, bitmaps etc.).
603 \note \a argc and \a argv might be changed as Qt removes command line
604 arguments that it recognizes.
606 Qt debugging options (not available if Qt was compiled without the QT_DEBUG
609 \o -nograb, tells Qt that it must never grab the mouse or the
611 \o -dograb (only under X11), running under a debugger can cause an
612 implicit -nograb, use -dograb to override.
613 \o -sync (only under X11), switches to synchronous mode for
617 See \l{Debugging Techniques} for a more detailed explanation.
619 All Qt programs automatically support the following command line options:
621 \o -style= \e style, sets the application GUI style. Possible values
622 are \c motif, \c windows, and \c platinum. If you compiled Qt with
623 additional styles or have additional styles as plugins these will
624 be available to the \c -style command line option.
625 \o -style \e style, is the same as listed above.
626 \o -stylesheet= \e stylesheet, sets the application \l styleSheet. The
627 value must be a path to a file that contains the Style Sheet.
628 \note Relative URLs in the Style Sheet file are relative to the
629 Style Sheet file's path.
630 \o -stylesheet \e stylesheet, is the same as listed above.
631 \o -session= \e session, restores the application from an earlier
632 \l{Session Management}{session}.
633 \o -session \e session, is the same as listed above.
634 \o -widgetcount, prints debug message at the end about number of
635 widgets left undestroyed and maximum number of widgets existed at
637 \o -reverse, sets the application's layout direction to
639 \o -qmljsdebugger=, activates the QML/JS debugger with a specified port.
640 The value must be of format port:1234[,block], where block is optional
641 and will make the application wait until a debugger connects to it.
644 The X11 version of Qt supports some traditional X11 command line options:
646 \o -display \e display, sets the X display (default is $DISPLAY).
647 \o -geometry \e geometry, sets the client geometry of the first window
649 \o -fn or \c -font \e font, defines the application font. The font
650 should be specified using an X logical font description. Note that
651 this option is ignored when Qt is built with fontconfig support enabled.
652 \o -bg or \c -background \e color, sets the default background color
653 and an application palette (light and dark shades are calculated).
654 \o -fg or \c -foreground \e color, sets the default foreground color.
655 \o -btn or \c -button \e color, sets the default button color.
656 \o -name \e name, sets the application name.
657 \o -title \e title, sets the application title.
658 \o -visual \c TrueColor, forces the application to use a TrueColor
659 visual on an 8-bit display.
660 \o -ncols \e count, limits the number of colors allocated in the color
661 cube on an 8-bit display, if the application is using the
662 QApplication::ManyColor color specification. If \e count is 216
663 then a 6x6x6 color cube is used (i.e. 6 levels of red, 6 of green,
664 and 6 of blue); for other values, a cube approximately proportional
665 to a 2x3x1 cube is used.
666 \o -cmap, causes the application to install a private color map on an
668 \o -im, sets the input method server (equivalent to setting the
669 XMODIFIERS environment variable)
670 \o -inputstyle, defines how the input is inserted into the given
671 widget, e.g., \c onTheSpot makes the input appear directly in the
672 widget, while \c overTheSpot makes the input appear in a box
673 floating over the widget and is not inserted until the editing is
679 If QApplication fails to open the X11 display, it will terminate
680 the process. This behavior is consistent with most X11
686 QApplication::QApplication(int &argc, char **argv)
687 : QApplicationBase(*new QApplicationPrivate(argc, argv, GuiClient, 0x040000))
688 { Q_D(QApplication); d->construct(); }
690 QApplication::QApplication(int &argc, char **argv, int _internal)
691 : QApplicationBase(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
692 { Q_D(QApplication); d->construct(); }
696 Constructs an application object with \a argc command line arguments in
697 \a argv. If \a GUIenabled is true, a GUI application is constructed,
698 otherwise a non-GUI (console) application is created.
700 \warning The data referred to by \a argc and \a argv must stay valid for
701 the entire lifetime of the QApplication object. In addition, \a argc must
702 be greater than zero and \a argv must contain at least one valid character
705 Set \a GUIenabled to false for programs without a graphical user interface
706 that should be able to run without a window system.
708 On X11, the window system is initialized if \a GUIenabled is true. If
709 \a GUIenabled is false, the application does not connect to the X server.
710 On Windows and Mac OS, currently the window system is always initialized,
711 regardless of the value of GUIenabled. This may change in future versions
714 The following example shows how to create an application that uses a
715 graphical interface when available.
717 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 0
720 QApplication::QApplication(int &argc, char **argv, bool GUIenabled )
721 : QApplicationBase(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, 0x040000))
722 { Q_D(QApplication); d->construct(); }
724 QApplication::QApplication(int &argc, char **argv, bool GUIenabled , int _internal)
725 : QApplicationBase(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, _internal))
726 { Q_D(QApplication); d->construct();}
731 Constructs an application object with \a argc command line arguments in
734 \warning The data referred to by \a argc and \a argv must stay valid for
735 the entire lifetime of the QApplication object. In addition, \a argc must
736 be greater than zero and \a argv must contain at least one valid character
739 With Qt for Embedded Linux, passing QApplication::GuiServer for \a type
740 makes this application the server (equivalent to running with the
743 QApplication::QApplication(int &argc, char **argv, Type type)
744 : QApplicationBase(*new QApplicationPrivate(argc, argv, type, 0x040000))
745 { Q_D(QApplication); d->construct(); }
747 QApplication::QApplication(int &argc, char **argv, Type type , int _internal)
748 : QApplicationBase(*new QApplicationPrivate(argc, argv, type, _internal))
749 { Q_D(QApplication); d->construct(); }
751 #if defined(Q_WS_X11) && !defined(QT_NO_EGL)
752 static int qt_matchLibraryName(dl_phdr_info *info, size_t, void *data)
754 const char *name = static_cast<const char *>(data);
755 return strstr(info->dlpi_name, name) != 0;
762 void QApplicationPrivate::construct(
764 Display *dpy, Qt::HANDLE visual, Qt::HANDLE cmap
770 qt_is_gui_used = (qt_appType != QApplication::Tty);
773 // Must be called before initialize()
774 qt_init(this, qt_appType
780 eventDispatcher->startingUp();
783 extern void qt_gui_eval_init(uint);
784 qt_gui_eval_init(application_type);
787 #if defined(Q_OS_SYMBIAN) && !defined(QT_NO_SYSTEMLOCALE)
791 #ifndef QT_NO_LIBRARY
792 if(load_testability) {
793 QLibrary testLib(QLatin1String("qttestability"));
794 if (testLib.load()) {
795 typedef void (*TasInitialize)(void);
796 TasInitialize initFunction = (TasInitialize)testLib.resolve("qt_testability_init");
798 // resolving method by name does not work on Symbian OS so need to use ordinal
800 initFunction = (TasInitialize)testLib.resolve("1");
806 qCritical("Library qttestability resolve failed!");
809 qCritical("Library qttestability load failed!");
813 //make sure the plugin is loaded
815 qt_guiPlatformPlugin();
819 #if defined(Q_WS_X11)
820 // ### a string literal is a cont char*
821 // ### using it as a char* is wrong and could lead to segfaults
822 // ### if aargv is modified someday
823 // ########## make it work with argc == argv == 0
824 static int aargc = 1;
825 static char *aargv[] = { (char*)"unknown", 0 };
828 \fn QApplication::QApplication(Display* display, Qt::HANDLE visual, Qt::HANDLE colormap)
830 Creates an application, given an already open display \a display. If
831 \a visual and \a colormap are non-zero, the application will use those
832 values as the default Visual and Colormap contexts.
834 \warning Qt only supports TrueColor visuals at depths higher than 8
837 This function is only available on X11.
839 QApplication::QApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE colormap)
840 : QApplicationBase(*new QApplicationPrivate(aargc, aargv, GuiClient, 0x040000))
843 qWarning("QApplication: Invalid Display* argument");
845 d->construct(dpy, visual, colormap);
848 QApplication::QApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE colormap, int _internal)
849 : QApplicationBase(*new QApplicationPrivate(aargc, aargv, GuiClient, _internal))
852 qWarning("QApplication: Invalid Display* argument");
854 d->construct(dpy, visual, colormap);
855 QApplicationPrivate::app_compile_version = _internal;
859 \fn QApplication::QApplication(Display *display, int &argc, char **argv,
860 Qt::HANDLE visual, Qt::HANDLE colormap)
862 Creates an application, given an already open \a display and using \a argc
863 command line arguments in \a argv. If \a visual and \a colormap are
864 non-zero, the application will use those values as the default Visual
865 and Colormap contexts.
867 \warning Qt only supports TrueColor visuals at depths higher than 8
870 This function is only available on X11.
872 QApplication::QApplication(Display *dpy, int &argc, char **argv,
873 Qt::HANDLE visual, Qt::HANDLE colormap)
874 : QApplicationBase(*new QApplicationPrivate(argc, argv, GuiClient, 0x040000))
877 qWarning("QApplication: Invalid Display* argument");
879 d->construct(dpy, visual, colormap);
882 QApplication::QApplication(Display *dpy, int &argc, char **argv,
883 Qt::HANDLE visual, Qt::HANDLE colormap, int _internal)
884 : QApplicationBase(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
887 qWarning("QApplication: Invalid Display* argument");
889 d->construct(dpy, visual, colormap);
890 QApplicationPrivate::app_compile_version = _internal;
895 #ifndef QT_NO_STATEMACHINE
896 extern int qRegisterGuiStateMachine();
897 extern int qUnregisterGuiStateMachine();
901 \fn void QApplicationPrivate::initialize()
903 Initializes the QApplication object, called from the constructors.
905 void QApplicationPrivate::initialize()
907 QWidgetPrivate::mapper = new QWidgetMapper;
908 QWidgetPrivate::allWidgets = new QWidgetSet;
910 if (qt_appType != QApplication::Tty)
911 (void) QApplication::style(); // trigger creation of application style
912 #ifndef QT_NO_STATEMACHINE
913 // trigger registering of QStateMachine's GUI types
914 qRegisterGuiStateMachine();
917 is_app_running = true; // no longer starting up
920 #ifndef QT_NO_SESSIONMANAGER
921 // connect to the session manager
922 session_manager = new QSessionManager(q, session_id, session_key);
925 if (qgetenv("QT_USE_NATIVE_WINDOWS").toInt() > 0)
926 q->setAttribute(Qt::AA_NativeWindows);
929 #ifdef QT_AUTO_MAXIMIZE_THRESHOLD
930 autoMaximizeThreshold = QT_AUTO_MAXIMIZE_THRESHOLD;
932 if (qt_wince_is_mobile())
933 autoMaximizeThreshold = 50;
935 autoMaximizeThreshold = -1;
936 #endif //QT_AUTO_MAXIMIZE_THRESHOLD
939 #ifndef QT_NO_WHEELEVENT
940 QApplicationPrivate::wheel_scroll_lines = 3;
944 initializeMultitouch();
948 Returns the type of application (\l Tty, GuiClient, or
949 GuiServer). The type is set when constructing the QApplication
952 QApplication::Type QApplication::type()
957 /*****************************************************************************
958 Functions returning the active popup and modal widgets.
959 *****************************************************************************/
962 Returns the active popup widget.
964 A popup widget is a special top-level widget that sets the \c
965 Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application
966 opens a popup widget, all events are sent to the popup. Normal widgets and
967 modal widgets cannot be accessed before the popup widget is closed.
969 Only other popup widgets may be opened when a popup widget is shown. The
970 popup widgets are organized in a stack. This function returns the active
971 popup widget at the top of the stack.
973 \sa activeModalWidget(), topLevelWidgets()
976 QWidget *QApplication::activePopupWidget()
978 return QApplicationPrivate::popupWidgets && !QApplicationPrivate::popupWidgets->isEmpty() ?
979 QApplicationPrivate::popupWidgets->last() : 0;
984 Returns the active modal widget.
986 A modal widget is a special top-level widget which is a subclass of QDialog
987 that specifies the modal parameter of the constructor as true. A modal
988 widget must be closed before the user can continue with other parts of the
991 Modal widgets are organized in a stack. This function returns the active
992 modal widget at the top of the stack.
994 \sa activePopupWidget(), topLevelWidgets()
997 QWidget *QApplication::activeModalWidget()
999 return qt_modal_stack && !qt_modal_stack->isEmpty() ? qt_modal_stack->first() : 0;
1003 Cleans up any window system resources that were allocated by this
1004 application. Sets the global variable \c qApp to 0.
1007 QApplication::~QApplication()
1011 #if !defined(Q_WS_QPA) && !defined(QT_NO_CLIPBOARD)
1012 // flush clipboard contents
1014 QEvent event(QEvent::Clipboard);
1015 QApplication::sendEvent(qt_clipboard, &event);
1019 //### this should probable be done even later
1020 qt_call_post_routines();
1022 // kill timers before closing down the dispatcher
1023 d->toolTipWakeUp.stop();
1024 d->toolTipFallAsleep.stop();
1026 #if !defined(Q_WS_QPA)
1027 d->eventDispatcher->closingDown();
1028 d->eventDispatcher = 0;
1030 QApplicationPrivate::is_app_closing = true;
1031 QApplicationPrivate::is_app_running = false;
1033 delete QWidgetPrivate::mapper;
1034 QWidgetPrivate::mapper = 0;
1036 // delete all widgets
1037 if (QWidgetPrivate::allWidgets) {
1038 QWidgetSet *mySet = QWidgetPrivate::allWidgets;
1039 QWidgetPrivate::allWidgets = 0;
1040 for (QWidgetSet::ConstIterator it = mySet->constBegin(); it != mySet->constEnd(); ++it) {
1041 register QWidget *w = *it;
1042 if (!w->parent()) // window
1043 w->destroy(true, true);
1048 delete qt_desktopWidget;
1049 qt_desktopWidget = 0;
1051 #if !defined(Q_WS_QPA) && !defined(QT_NO_CLIPBOARD)
1052 delete qt_clipboard;
1056 #if defined(Q_WS_X11) || defined(Q_WS_WIN)
1057 delete d->move_cursor; d->move_cursor = 0;
1058 delete d->copy_cursor; d->copy_cursor = 0;
1059 delete d->link_cursor; d->link_cursor = 0;
1061 #if defined(Q_WS_WIN)
1062 delete d->ignore_cursor; d->ignore_cursor = 0;
1065 delete QApplicationPrivate::app_pal;
1066 QApplicationPrivate::app_pal = 0;
1067 delete QApplicationPrivate::sys_pal;
1068 QApplicationPrivate::sys_pal = 0;
1069 delete QApplicationPrivate::set_pal;
1070 QApplicationPrivate::set_pal = 0;
1071 app_palettes()->clear();
1075 QMutexLocker locker(applicationFontMutex());
1076 delete QApplicationPrivate::app_font;
1077 QApplicationPrivate::app_font = 0;
1081 delete QApplicationPrivate::sys_font;
1082 QApplicationPrivate::sys_font = 0;
1083 delete QApplicationPrivate::set_font;
1084 QApplicationPrivate::set_font = 0;
1085 app_fonts()->clear();
1087 delete QApplicationPrivate::app_style;
1088 QApplicationPrivate::app_style = 0;
1089 delete QApplicationPrivate::app_icon;
1090 QApplicationPrivate::app_icon = 0;
1092 #ifndef QT_NO_DRAGANDDROP
1094 delete QDragManager::self();
1097 d->cleanupMultitouch();
1101 if (QApplicationPrivate::widgetCount)
1102 qDebug("Widgets left: %i Max widgets: %i \n", QWidgetPrivate::instanceCounter, QWidgetPrivate::maxInstances);
1103 #ifndef QT_NO_SESSIONMANAGER
1104 delete d->session_manager;
1105 d->session_manager = 0;
1106 #endif //QT_NO_SESSIONMANAGER
1108 QApplicationPrivate::obey_desktop_settings = true;
1110 QApplicationPrivate::app_strut = QSize(0, 0);
1111 QApplicationPrivate::animate_ui = true;
1112 QApplicationPrivate::animate_menu = false;
1113 QApplicationPrivate::fade_menu = false;
1114 QApplicationPrivate::animate_combo = false;
1115 QApplicationPrivate::animate_tooltip = false;
1116 QApplicationPrivate::fade_tooltip = false;
1117 QApplicationPrivate::widgetCount = false;
1119 #ifndef QT_NO_STATEMACHINE
1120 // trigger unregistering of QStateMachine's GUI types
1121 qUnregisterGuiStateMachine();
1127 \fn QWidget *QApplication::widgetAt(const QPoint &point)
1129 Returns the widget at global screen position \a point, or 0 if there is no
1132 This function can be slow.
1134 \sa QCursor::pos(), QWidget::grabMouse(), QWidget::grabKeyboard()
1136 QWidget *QApplication::widgetAt(const QPoint &p)
1138 QWidget *window = QApplication::topLevelAt(p);
1144 if (!window->testAttribute(Qt::WA_TransparentForMouseEvents))
1145 child = window->childAt(window->mapFromGlobal(p));
1150 if (window->testAttribute(Qt::WA_TransparentForMouseEvents)) {
1151 //shoot a hole in the widget and try once again,
1152 //suboptimal on Qt for Embedded Linux where we do
1153 //know the stacking order of the toplevels.
1156 QRegion oldmask = window->mask();
1157 QPoint wpoint = window->mapFromGlobal(QPoint(x, y));
1158 QRegion newmask = (oldmask.isEmpty() ? QRegion(window->rect()) : oldmask)
1159 - QRegion(wpoint.x(), wpoint.y(), 1, 1);
1160 window->setMask(newmask);
1161 QWidget *recurse = 0;
1162 if (QApplication::topLevelAt(p) != window) // verify recursion will terminate
1163 recurse = widgetAt(x, y);
1164 if (oldmask.isEmpty())
1165 window->clearMask();
1167 window->setMask(oldmask);
1174 \fn QWidget *QApplication::widgetAt(int x, int y)
1178 Returns the widget at global screen position (\a x, \a y), or 0 if there is
1183 \fn void QApplication::setArgs(int argc, char **argv)
1192 bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
1194 if ((event->type() == QEvent::UpdateRequest
1196 || event->type() == QEvent::LayoutHint
1198 || event->type() == QEvent::LayoutRequest
1199 || event->type() == QEvent::Resize
1200 || event->type() == QEvent::Move
1201 || event->type() == QEvent::LanguageChange
1202 || event->type() == QEvent::UpdateSoftKeys
1203 || event->type() == QEvent::InputMethod)) {
1204 for (QPostEventList::const_iterator it = postedEvents->constBegin(); it != postedEvents->constEnd(); ++it) {
1205 const QPostEvent &cur = *it;
1206 if (cur.receiver != receiver || cur.event == 0 || cur.event->type() != event->type())
1208 if (cur.event->type() == QEvent::LayoutRequest
1210 || cur.event->type() == QEvent::LayoutHint
1212 || cur.event->type() == QEvent::UpdateRequest) {
1214 } else if (cur.event->type() == QEvent::Resize) {
1215 ((QResizeEvent *)(cur.event))->s = ((QResizeEvent *)event)->s;
1216 } else if (cur.event->type() == QEvent::Move) {
1217 ((QMoveEvent *)(cur.event))->p = ((QMoveEvent *)event)->p;
1218 } else if (cur.event->type() == QEvent::LanguageChange) {
1220 } else if (cur.event->type() == QEvent::UpdateSoftKeys) {
1222 } else if ( cur.event->type() == QEvent::InputMethod ) {
1223 *(QInputMethodEvent *)(cur.event) = *(QInputMethodEvent *)event;
1232 return QApplicationBase::compressEvent(event, receiver, postedEvents);
1236 \property QApplication::styleSheet
1237 \brief the application style sheet
1240 By default, this property returns an empty string unless the user specifies
1241 the \c{-stylesheet} option on the command line when running the application.
1243 \sa QWidget::setStyle(), {Qt Style Sheets}
1247 \property QApplication::autoMaximizeThreshold
1249 \brief defines a threshold for auto maximizing widgets
1251 \bold{The auto maximize threshold is only available as part of Qt for
1254 This property defines a threshold for the size of a window as a percentage
1255 of the screen size. If the minimum size hint of a window exceeds the
1256 threshold, calling show() will cause the window to be maximized
1259 Setting the threshold to 100 or greater means that the widget will always
1260 be maximized. Alternatively, setting the threshold to 50 means that the
1261 widget will be maximized only if the vertical minimum size hint is at least
1262 50% of the vertical screen size.
1264 Setting the threshold to -1 disables the feature.
1266 On Windows CE the default is -1 (i.e., it is disabled).
1267 On Windows Mobile the default is 40.
1271 \property QApplication::autoSipEnabled
1273 \brief toggles automatic SIP (software input panel) visibility
1275 Set this property to \c true to automatically display the SIP when entering
1276 widgets that accept keyboard input. This property only affects widgets with
1277 the WA_InputMethodEnabled attribute set, and is typically used to launch
1278 a virtual keyboard on devices which have very few or no keys.
1280 \bold{ The property only has an effect on platforms which use software input
1281 panels, such as Windows CE and Symbian.}
1283 The default is platform dependent.
1287 void QApplication::setAutoMaximizeThreshold(const int threshold)
1289 QApplicationPrivate::autoMaximizeThreshold = threshold;
1292 int QApplication::autoMaximizeThreshold() const
1294 return QApplicationPrivate::autoMaximizeThreshold;
1298 void QApplication::setAutoSipEnabled(const bool enabled)
1300 QApplicationPrivate::autoSipEnabled = enabled;
1303 bool QApplication::autoSipEnabled() const
1305 return QApplicationPrivate::autoSipEnabled;
1308 #ifndef QT_NO_STYLE_STYLESHEET
1310 QString QApplication::styleSheet() const
1312 return QApplicationPrivate::styleSheet;
1315 void QApplication::setStyleSheet(const QString& styleSheet)
1317 QApplicationPrivate::styleSheet = styleSheet;
1318 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle*>(QApplicationPrivate::app_style);
1319 if (styleSheet.isEmpty()) { // application style sheet removed
1321 return; // there was no stylesheet before
1322 setStyle(proxy->base);
1323 } else if (proxy) { // style sheet update, just repolish
1324 proxy->repolish(qApp);
1325 } else { // stylesheet set the first time
1326 QStyleSheetStyle *newProxy = new QStyleSheetStyle(QApplicationPrivate::app_style);
1327 QApplicationPrivate::app_style->setParent(newProxy);
1332 #endif // QT_NO_STYLE_STYLESHEET
1335 Returns the application's style object.
1337 \sa setStyle(), QStyle
1339 QStyle *QApplication::style()
1341 if (QApplicationPrivate::app_style)
1342 return QApplicationPrivate::app_style;
1343 if (!qt_is_gui_used) {
1344 Q_ASSERT(!"No style available in non-gui applications!");
1348 if (!QApplicationPrivate::app_style) {
1349 // Compile-time search for default style
1352 #ifdef QT_BUILD_INTERNAL
1353 QString envStyle = QString::fromLocal8Bit(qgetenv("QT_STYLE_OVERRIDE"));
1357 if (!QApplicationPrivate::styleOverride.isEmpty()) {
1358 style = QApplicationPrivate::styleOverride;
1359 } else if (!envStyle.isEmpty()) {
1362 style = QApplicationPrivate::desktopStyleKey();
1365 QStyle *&app_style = QApplicationPrivate::app_style;
1366 app_style = QStyleFactory::create(style);
1368 QStringList styles = QStyleFactory::keys();
1369 for (int i = 0; i < styles.size(); ++i) {
1370 if ((app_style = QStyleFactory::create(styles.at(i))))
1375 Q_ASSERT(!"No styles available!");
1379 // take ownership of the style
1380 QApplicationPrivate::app_style->setParent(qApp);
1382 if (!QApplicationPrivate::sys_pal)
1383 QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
1384 if (QApplicationPrivate::set_pal) // repolish set palette with the new style
1385 QApplication::setPalette(*QApplicationPrivate::set_pal);
1387 #ifndef QT_NO_STYLE_STYLESHEET
1388 if (!QApplicationPrivate::styleSheet.isEmpty()) {
1389 qApp->setStyleSheet(QApplicationPrivate::styleSheet);
1392 QApplicationPrivate::app_style->polish(qApp);
1394 return QApplicationPrivate::app_style;
1398 Sets the application's GUI style to \a style. Ownership of the style object
1399 is transferred to QApplication, so QApplication will delete the style
1400 object on application exit or when a new style is set and the old style is
1401 still the parent of the application object.
1404 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 1
1406 When switching application styles, the color palette is set back to the
1407 initial colors or the system defaults. This is necessary since certain
1408 styles have to adapt the color palette to be fully style-guide compliant.
1410 Setting the style before a palette has been se, i.e., before creating
1411 QApplication, will cause the application to use QStyle::standardPalette()
1414 \warning Qt style sheets are currently not supported for custom QStyle
1415 subclasses. We plan to address this in some future release.
1417 \sa style(), QStyle, setPalette(), desktopSettingsAware()
1419 void QApplication::setStyle(QStyle *style)
1421 if (!style || style == QApplicationPrivate::app_style)
1424 QWidgetList all = allWidgets();
1426 // clean up the old style
1427 if (QApplicationPrivate::app_style) {
1428 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1429 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1430 register QWidget *w = *it;
1431 if (!(w->windowType() == Qt::Desktop) && // except desktop
1432 w->testAttribute(Qt::WA_WState_Polished)) { // has been polished
1433 QApplicationPrivate::app_style->unpolish(w);
1437 QApplicationPrivate::app_style->unpolish(qApp);
1440 QStyle *old = QApplicationPrivate::app_style; // save
1442 #ifndef QT_NO_STYLE_STYLESHEET
1443 if (!QApplicationPrivate::styleSheet.isEmpty() && !qobject_cast<QStyleSheetStyle *>(style)) {
1444 // we have a stylesheet already and a new style is being set
1445 QStyleSheetStyle *newProxy = new QStyleSheetStyle(style);
1446 style->setParent(newProxy);
1447 QApplicationPrivate::app_style = newProxy;
1449 #endif // QT_NO_STYLE_STYLESHEET
1450 QApplicationPrivate::app_style = style;
1451 QApplicationPrivate::app_style->setParent(qApp); // take ownership
1453 // take care of possible palette requirements of certain gui
1454 // styles. Do it before polishing the application since the style
1455 // might call QApplication::setPalette() itself
1456 if (QApplicationPrivate::set_pal) {
1457 QApplication::setPalette(*QApplicationPrivate::set_pal);
1458 } else if (QApplicationPrivate::sys_pal) {
1459 QApplicationPrivate::initializeWidgetPaletteHash();
1460 QApplicationPrivate::setPalette_helper(*QApplicationPrivate::sys_pal, /*className=*/0, /*clearWidgetPaletteHash=*/false);
1461 } else if (!QApplicationPrivate::sys_pal) {
1462 // Initialize the sys_pal if it hasn't happened yet...
1463 QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
1466 // initialize the application with the new style
1467 QApplicationPrivate::app_style->polish(qApp);
1469 // re-polish existing widgets if necessary
1470 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1471 for (QWidgetList::ConstIterator it1 = all.constBegin(); it1 != all.constEnd(); ++it1) {
1472 register QWidget *w = *it1;
1473 if (w->windowType() != Qt::Desktop && w->testAttribute(Qt::WA_WState_Polished)) {
1474 if (w->style() == QApplicationPrivate::app_style)
1475 QApplicationPrivate::app_style->polish(w); // repolish
1476 #ifndef QT_NO_STYLE_STYLESHEET
1478 w->setStyleSheet(w->styleSheet()); // touch
1483 for (QWidgetList::ConstIterator it2 = all.constBegin(); it2 != all.constEnd(); ++it2) {
1484 register QWidget *w = *it2;
1485 if (w->windowType() != Qt::Desktop && !w->testAttribute(Qt::WA_SetStyle)) {
1486 QEvent e(QEvent::StyleChange);
1487 QApplication::sendEvent(w, &e);
1490 w->styleChange(*old);
1497 #ifndef QT_NO_STYLE_STYLESHEET
1498 if (QStyleSheetStyle *oldProxy = qobject_cast<QStyleSheetStyle *>(old)) {
1502 if (old && old->parent() == qApp) {
1506 if (QApplicationPrivate::focus_widget) {
1507 QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
1508 QApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
1509 QApplicationPrivate::focus_widget->update();
1516 Requests a QStyle object for \a style from the QStyleFactory.
1518 The string must be one of the QStyleFactory::keys(), typically one of
1519 "windows", "motif", "cde", "plastique", "windowsxp", or "macintosh". Style
1520 names are case insensitive.
1522 Returns 0 if an unknown \a style is passed, otherwise the QStyle object
1523 returned is set as the application's GUI style.
1525 \warning To ensure that the application's style is set correctly, it is
1526 best to call this function before the QApplication constructor, if
1529 QStyle* QApplication::setStyle(const QString& style)
1531 QStyle *s = QStyleFactory::create(style);
1540 Returns the color specification.
1542 \sa QApplication::setColorSpec()
1545 int QApplication::colorSpec()
1547 return QApplicationPrivate::app_cspec;
1551 Sets the color specification for the application to \a spec.
1553 The color specification controls how the application allocates colors when
1554 run on a display with a limited amount of colors, e.g. 8 bit / 256 color
1557 The color specification must be set before you create the QApplication
1562 \o QApplication::NormalColor. This is the default color allocation
1563 strategy. Use this option if your application uses buttons, menus,
1564 texts and pixmaps with few colors. With this option, the
1565 application uses system global colors. This works fine for most
1566 applications under X11, but on the Windows platform, it may cause
1567 dithering of non-standard colors.
1568 \o QApplication::CustomColor. Use this option if your application
1569 needs a small number of custom colors. On X11, this option is the
1570 same as NormalColor. On Windows, Qt creates a Windows palette, and
1571 allocates colors to it on demand.
1572 \o QApplication::ManyColor. Use this option if your application is
1573 very color hungry, e.g., it requires thousands of colors. \br
1574 Under X11 the effect is:
1576 \o For 256-color displays which have at best a 256 color true
1577 color visual, the default visual is used, and colors are
1578 allocated from a color cube. The color cube is the 6x6x6
1579 (216 color) "Web palette" (the red, green, and blue
1580 components always have one of the following values: 0x00,
1581 0x33, 0x66, 0x99, 0xCC, or 0xFF), but the number of colors
1582 can be changed by the \e -ncols option. The user can force
1583 the application to use the true color visual with the
1584 \l{QApplication::QApplication()}{-visual} option.
1585 \o For 256-color displays which have a true color visual with
1586 more than 256 colors, use that visual. Silicon Graphics X
1587 servers this feature, for example. They provide an 8 bit
1588 visual by default but can deliver true color when asked.
1590 On Windows, Qt creates a Windows palette, and fills it with a color
1594 Be aware that the CustomColor and ManyColor choices may lead to colormap
1595 flashing: The foreground application gets (most) of the available colors,
1596 while the background windows will look less attractive.
1600 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 2
1605 void QApplication::setColorSpec(int spec)
1608 qWarning("QApplication::setColorSpec: This function must be "
1609 "called before the QApplication object is created");
1610 QApplicationPrivate::app_cspec = spec;
1614 \property QApplication::globalStrut
1615 \brief the minimum size that any GUI element that the user can interact
1618 For example, no button should be resized to be smaller than the global
1619 strut size. The strut size should be considered when reimplementing GUI
1620 controls that may be used on touch-screens or similar I/O devices.
1624 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 3
1626 By default, this property contains a QSize object with zero width and height.
1628 QSize QApplication::globalStrut()
1630 return QApplicationPrivate::app_strut;
1633 void QApplication::setGlobalStrut(const QSize& strut)
1635 QApplicationPrivate::app_strut = strut;
1640 \fn QPalette QApplication::palette(const QWidget* widget)
1643 If a \a widget is passed, the default palette for the widget's class is
1644 returned. This may or may not be the application palette. In most cases
1645 there is no special palette for certain types of widgets, but one notable
1646 exception is the popup menu under Windows, if the user has defined a
1647 special background color for menus in the display settings.
1649 \sa setPalette(), QWidget::palette()
1651 QPalette QApplication::palette(const QWidget* w)
1653 PaletteHash *hash = app_palettes();
1654 if (w && hash && hash->size()) {
1655 QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(w->metaObject()->className());
1656 if (it != hash->constEnd())
1658 for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1659 if (w->inherits(it.key()))
1669 Returns the palette for widgets of the given \a className.
1671 \sa setPalette(), QWidget::palette()
1673 QPalette QApplication::palette(const char *className)
1675 if (!QApplicationPrivate::app_pal)
1677 PaletteHash *hash = app_palettes();
1678 if (className && hash && hash->size()) {
1679 QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(className);
1680 if (it != hash->constEnd())
1683 return *QApplicationPrivate::app_pal;
1686 void QApplicationPrivate::setPalette_helper(const QPalette &palette, const char* className, bool clearWidgetPaletteHash)
1688 QPalette pal = palette;
1690 if (QApplicationPrivate::app_style)
1691 QApplicationPrivate::app_style->polish(pal); // NB: non-const reference
1694 PaletteHash *hash = app_palettes();
1696 if (QApplicationPrivate::app_pal && pal.isCopyOf(*QApplicationPrivate::app_pal))
1698 if (!QApplicationPrivate::app_pal)
1699 QApplicationPrivate::app_pal = new QPalette(pal);
1701 *QApplicationPrivate::app_pal = pal;
1702 if (hash && hash->size()) {
1704 if (clearWidgetPaletteHash)
1708 hash->insert(className, pal);
1711 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1712 // Send ApplicationPaletteChange to qApp itself, and to the widgets.
1713 QEvent e(QEvent::ApplicationPaletteChange);
1714 QApplication::sendEvent(QApplication::instance(), &e);
1716 QWidgetList wids = QApplication::allWidgets();
1717 for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1718 register QWidget *w = *it;
1719 if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1720 QApplication::sendEvent(w, &e);
1723 // Send to all scenes as well.
1724 #ifndef QT_NO_GRAPHICSVIEW
1725 QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1726 for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1727 it != scenes.constEnd(); ++it) {
1728 QApplication::sendEvent(*it, &e);
1730 #endif //QT_NO_GRAPHICSVIEW
1732 if (!className && (!QApplicationPrivate::sys_pal || !palette.isCopyOf(*QApplicationPrivate::sys_pal))) {
1733 if (!QApplicationPrivate::set_pal)
1734 QApplicationPrivate::set_pal = new QPalette(palette);
1736 *QApplicationPrivate::set_pal = palette;
1741 Changes the default application palette to \a palette.
1743 If \a className is passed, the change applies only to widgets that inherit
1744 \a className (as reported by QObject::inherits()). If \a className is left
1745 0, the change affects all widgets, thus overriding any previously set class
1748 The palette may be changed according to the current GUI style in
1751 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1752 When using style sheets, the palette of a widget can be customized using
1753 the "color", "background-color", "selection-color",
1754 "selection-background-color" and "alternate-background-color".
1756 \note Some styles do not use the palette for all drawing, for instance, if
1757 they make use of native theme engines. This is the case for the Windows XP,
1758 Windows Vista, and Mac OS X styles.
1760 \sa QWidget::setPalette(), palette(), QStyle::polish()
1763 void QApplication::setPalette(const QPalette &palette, const char* className)
1765 QApplicationPrivate::setPalette_helper(palette, className, /*clearWidgetPaletteHash=*/ true);
1770 void QApplicationPrivate::setSystemPalette(const QPalette &pal)
1775 // adjust the system palette to avoid dithering
1776 QColormap cmap = QColormap::instance();
1777 if (cmap.depths() > 4 && cmap.depths() < 24) {
1778 for (int g = 0; g < QPalette::NColorGroups; g++)
1779 for (int i = 0; i < QPalette::NColorRoles; i++) {
1780 QColor color = pal.color((QPalette::ColorGroup)g, (QPalette::ColorRole)i);
1781 color = cmap.colorAt(cmap.pixel(color));
1782 adjusted.setColor((QPalette::ColorGroup)g, (QPalette::ColorRole) i, color);
1790 sys_pal = new QPalette(adjusted);
1792 *sys_pal = adjusted;
1795 if (!QApplicationPrivate::set_pal)
1796 QApplication::setPalette(*sys_pal);
1800 Returns the default application font.
1802 \sa fontMetrics(), QWidget::font()
1804 QFont QApplication::font()
1807 QMutexLocker locker(applicationFontMutex());
1808 if (!QApplicationPrivate::app_font)
1809 QApplicationPrivate::app_font = new QFont(QLatin1String("Helvetica"));
1810 return *QApplicationPrivate::app_font;
1812 return QGuiApplication::font();
1819 Returns the default font for the \a widget.
1821 \sa fontMetrics(), QWidget::setFont()
1824 QFont QApplication::font(const QWidget *widget)
1826 FontHash *hash = app_fonts();
1829 // short circuit for small and mini controls
1830 if (widget->testAttribute(Qt::WA_MacSmallSize)) {
1831 return hash->value("QSmallFont");
1832 } else if (widget->testAttribute(Qt::WA_MacMiniSize)) {
1833 return hash->value("QMiniFont");
1836 if (widget && hash && hash->size()) {
1837 QHash<QByteArray, QFont>::ConstIterator it =
1838 hash->constFind(widget->metaObject()->className());
1839 if (it != hash->constEnd())
1841 for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1842 if (widget->inherits(it.key()))
1852 Returns the font for widgets of the given \a className.
1854 \sa setFont(), QWidget::font()
1856 QFont QApplication::font(const char *className)
1858 FontHash *hash = app_fonts();
1859 if (className && hash && hash->size()) {
1860 QHash<QByteArray, QFont>::ConstIterator it = hash->constFind(className);
1861 if (it != hash->constEnd())
1869 Changes the default application font to \a font. If \a className is passed,
1870 the change applies only to classes that inherit \a className (as reported
1871 by QObject::inherits()).
1873 On application start-up, the default font depends on the window system. It
1874 can vary depending on both the window system version and the locale. This
1875 function lets you override the default font; but overriding may be a bad
1876 idea because, for example, some locales need extra large fonts to support
1877 their special characters.
1879 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1880 The font of an application can be customized using the "font" style sheet
1881 property. To set a bold font for all QPushButtons, set the application
1882 styleSheet() as "QPushButton { font: bold }"
1884 \sa font(), fontMetrics(), QWidget::setFont()
1887 void QApplication::setFont(const QFont &font, const char *className)
1890 FontHash *hash = app_fonts();
1893 QMutexLocker locker(applicationFontMutex());
1894 if (!QApplicationPrivate::app_font)
1895 QApplicationPrivate::app_font = new QFont(font);
1897 *QApplicationPrivate::app_font = font;
1899 QGuiApplication::setFont(font);
1901 if (hash && hash->size()) {
1906 hash->insert(className, font);
1908 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1909 // Send ApplicationFontChange to qApp itself, and to the widgets.
1910 QEvent e(QEvent::ApplicationFontChange);
1911 QApplication::sendEvent(QApplication::instance(), &e);
1913 QWidgetList wids = QApplication::allWidgets();
1914 for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1915 register QWidget *w = *it;
1916 if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1920 #ifndef QT_NO_GRAPHICSVIEW
1921 // Send to all scenes as well.
1922 QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1923 for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1924 it != scenes.constEnd(); ++it) {
1925 QApplication::sendEvent(*it, &e);
1927 #endif //QT_NO_GRAPHICSVIEW
1929 if (!className && (!QApplicationPrivate::sys_font || !font.isCopyOf(*QApplicationPrivate::sys_font))) {
1930 if (!QApplicationPrivate::set_font)
1931 QApplicationPrivate::set_font = new QFont(font);
1933 *QApplicationPrivate::set_font = font;
1939 void QApplicationPrivate::setSystemFont(const QFont &font)
1942 sys_font = new QFont(font);
1946 if (!QApplicationPrivate::set_font)
1947 QApplication::setFont(*sys_font);
1952 QString QApplicationPrivate::desktopStyleKey()
1954 return qt_guiPlatformPlugin()->styleName();
1958 \property QApplication::windowIcon
1959 \brief the default window icon
1961 \sa QWidget::setWindowIcon(), {Setting the Application Icon}
1963 QIcon QApplication::windowIcon()
1965 return QApplicationPrivate::app_icon ? *QApplicationPrivate::app_icon : QIcon();
1968 void QApplication::setWindowIcon(const QIcon &icon)
1970 if (!QApplicationPrivate::app_icon)
1971 QApplicationPrivate::app_icon = new QIcon();
1972 *QApplicationPrivate::app_icon = icon;
1973 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1975 void qt_mac_set_app_icon(const QPixmap &); //qapplication_mac.cpp
1976 QSize size = QApplicationPrivate::app_icon->actualSize(QSize(128, 128));
1977 qt_mac_set_app_icon(QApplicationPrivate::app_icon->pixmap(size));
1979 QEvent e(QEvent::ApplicationWindowIconChange);
1980 QWidgetList all = QApplication::allWidgets();
1981 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1982 register QWidget *w = *it;
1990 Returns a list of the top-level widgets (windows) in the application.
1992 \note Some of the top-level widgets may be hidden, for example a tooltip if
1993 no tooltip is currently shown.
1997 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 4
1999 \sa allWidgets(), QWidget::isWindow(), QWidget::isHidden()
2001 QWidgetList QApplication::topLevelWidgets()
2004 QWidgetList all = allWidgets();
2006 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
2008 if (w->isWindow() && w->windowType() != Qt::Desktop)
2015 Returns a list of all the widgets in the application.
2017 The list is empty (QList::isEmpty()) if there are no widgets.
2019 \note Some of the widgets may be hidden.
2022 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 5
2024 \sa topLevelWidgets(), QWidget::isVisible()
2027 QWidgetList QApplication::allWidgets()
2029 if (QWidgetPrivate::allWidgets)
2030 return QWidgetPrivate::allWidgets->toList();
2031 return QWidgetList();
2035 Returns the application widget that has the keyboard input focus, or 0 if
2036 no widget in this application has the focus.
2038 \sa QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), focusChanged()
2041 QWidget *QApplication::focusWidget()
2043 return QApplicationPrivate::focus_widget;
2046 void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
2048 #ifndef QT_NO_GRAPHICSVIEW
2049 if (focus && focus->window()->graphicsProxyWidget())
2053 hidden_focus_widget = 0;
2055 if (focus != focus_widget) {
2056 if (focus && focus->isHidden()) {
2057 hidden_focus_widget = focus;
2061 if (focus && (reason == Qt::BacktabFocusReason || reason == Qt::TabFocusReason)
2062 && qt_in_tab_key_event)
2063 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
2064 else if (focus && reason == Qt::ShortcutFocusReason) {
2065 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
2067 QWidget *prev = focus_widget;
2068 focus_widget = focus;
2070 if (prev && ((reason != Qt::PopupFocusReason && reason != Qt::MenuBarFocusReason
2071 && prev->testAttribute(Qt::WA_InputMethodEnabled))
2072 // Do reset the input context, in case the new focus widget won't accept keyboard input
2073 // or it is not created fully yet.
2074 || (focus_widget && (!focus_widget->testAttribute(Qt::WA_InputMethodEnabled)
2075 || !focus_widget->testAttribute(Qt::WA_WState_Created))))) {
2076 QInputContext *qic = prev->inputContext();
2079 qic->setFocusWidget(0);
2085 focus_widget->d_func()->setFocus_sys();
2087 if (reason != Qt::NoFocusReason) {
2091 #ifdef QT_KEYPAD_NAVIGATION
2092 if (QApplication::keypadNavigationEnabled()) {
2093 if (prev->hasEditFocus() && reason != Qt::PopupFocusReason
2095 && reason != Qt::ActiveWindowFocusReason
2098 prev->setEditFocus(false);
2101 QFocusEvent out(QEvent::FocusOut, reason);
2102 QPointer<QWidget> that = prev;
2103 QApplication::sendEvent(prev, &out);
2105 QApplication::sendEvent(that->style(), &out);
2107 if(focus && QApplicationPrivate::focus_widget == focus) {
2109 if (focus->testAttribute(Qt::WA_InputMethodEnabled)) {
2110 QInputContext *qic = focus->inputContext();
2111 if (qic && focus->testAttribute(Qt::WA_WState_Created)
2112 && focus->isEnabled())
2113 qic->setFocusWidget(focus);
2116 QFocusEvent in(QEvent::FocusIn, reason);
2117 QPointer<QWidget> that = focus;
2118 QApplication::sendEvent(focus, &in);
2120 QApplication::sendEvent(that->style(), &in);
2122 emit qApp->focusChanged(prev, focus_widget);
2129 Returns the application top-level window that has the keyboard input focus,
2130 or 0 if no application window has the focus. There might be an
2131 activeWindow() even if there is no focusWidget(), for example if no widget
2132 in that window accepts key events.
2134 \sa QWidget::setFocus(), QWidget::hasFocus(), focusWidget()
2137 QWidget *QApplication::activeWindow()
2139 return QApplicationPrivate::active_window;
2143 Returns display (screen) font metrics for the application font.
2145 \sa font(), setFont(), QWidget::fontMetrics(), QPainter::fontMetrics()
2148 QFontMetrics QApplication::fontMetrics()
2150 return desktop()->fontMetrics();
2155 Closes all top-level windows.
2157 This function is particularly useful for applications with many top-level
2158 windows. It could, for example, be connected to a \gui{Exit} entry in the
2161 \snippet examples/mainwindows/mdi/mainwindow.cpp 0
2163 The windows are closed in random order, until one window does not accept
2164 the close event. The application quits when the last window was
2165 successfully closed; this can be turned off by setting
2166 \l quitOnLastWindowClosed to false.
2168 \sa quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(),
2169 QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(),
2172 void QApplication::closeAllWindows()
2174 bool did_close = true;
2176 while ((w = activeModalWidget()) && did_close) {
2177 if (!w->isVisible() || w->data->is_closing)
2179 did_close = w->close();
2181 QWidgetList list = QApplication::topLevelWidgets();
2182 for (int i = 0; did_close && i < list.size(); ++i) {
2185 && w->windowType() != Qt::Desktop
2186 && !w->data->is_closing) {
2187 did_close = w->close();
2188 list = QApplication::topLevelWidgets();
2195 Displays a simple message box about Qt. The message includes the version
2196 number of Qt being used by the application.
2198 This is useful for inclusion in the \gui Help menu of an application, as
2199 shown in the \l{mainwindows/menus}{Menus} example.
2201 This function is a convenience slot for QMessageBox::aboutQt().
2203 void QApplication::aboutQt()
2205 #ifndef QT_NO_MESSAGEBOX
2206 QMessageBox::aboutQt(
2213 #endif // QT_NO_MESSAGEBOX
2218 \fn void QApplication::lastWindowClosed()
2220 This signal is emitted from QApplication::exec() when the last visible
2221 primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose
2222 attribute set is closed.
2227 \o this attribute is set for all widgets except transient windows such
2228 as splash screens, tool windows, and popup menus
2230 \o QApplication implicitly quits when this signal is emitted.
2233 This feature can be turned off by setting \l quitOnLastWindowClosed to
2236 \sa QWidget::close()
2241 \fn void QApplication::focusChanged(QWidget *old, QWidget *now)
2243 This signal is emitted when the widget that has keyboard focus changed from
2244 \a old to \a now, i.e., because the user pressed the tab-key, clicked into
2245 a widget or changed the active window. Both \a old and \a now can be the
2248 The signal is emitted after both widget have been notified about the change
2249 through QFocusEvent.
2251 \sa QWidget::setFocus(), QWidget::clearFocus(), Qt::FocusReason
2257 bool QApplication::event(QEvent *e)
2260 if(e->type() == QEvent::Close) {
2261 #if defined(Q_OS_SYMBIAN)
2262 // In order to have proper application-exit effects on Symbian, certain
2263 // native APIs have to be called _before_ closing/destroying the widgets.
2264 bool effectStarted = qt_beginFullScreenEffect();
2266 QCloseEvent *ce = static_cast<QCloseEvent*>(e);
2270 QWidgetList list = topLevelWidgets();
2271 for (int i = 0; i < list.size(); ++i) {
2272 QWidget *w = list.at(i);
2273 if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
2274 (!(w->windowType() == Qt::Dialog) || !w->parentWidget())) {
2279 if (ce->isAccepted()) {
2282 #if defined(Q_OS_SYMBIAN)
2284 qt_abortFullScreenEffect();
2288 } else if (e->type() == QEvent::LocaleChange) {
2289 // on Windows the event propagation is taken care by the
2290 // WM_SETTINGCHANGE event handler.
2291 QWidgetList list = topLevelWidgets();
2292 for (int i = 0; i < list.size(); ++i) {
2293 QWidget *w = list.at(i);
2294 if (!(w->windowType() == Qt::Desktop)) {
2295 if (!w->testAttribute(Qt::WA_SetLocale))
2296 w->d_func()->setLocale_helper(QLocale(), true);
2300 } else if (e->type() == QEvent::Timer) {
2301 QTimerEvent *te = static_cast<QTimerEvent*>(e);
2303 if (te->timerId() == d->toolTipWakeUp.timerId()) {
2304 d->toolTipWakeUp.stop();
2305 if (d->toolTipWidget) {
2306 QWidget *w = d->toolTipWidget->window();
2307 // show tooltip if WA_AlwaysShowToolTips is set, or if
2308 // any ancestor of d->toolTipWidget is the active
2310 bool showToolTip = w->testAttribute(Qt::WA_AlwaysShowToolTips);
2311 while (w && !showToolTip) {
2312 showToolTip = w->isActiveWindow();
2313 w = w->parentWidget();
2314 w = w ? w->window() : 0;
2317 QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
2318 QApplication::sendEvent(d->toolTipWidget, &e);
2320 d->toolTipFallAsleep.start(2000, this);
2323 } else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
2324 d->toolTipFallAsleep.stop();
2327 return QApplicationBase::event(e);
2329 if(e->type() == QEvent::LanguageChange) {
2330 #if defined(QT_MAC_USE_COCOA)
2331 qt_mac_post_retranslateAppMenu();
2333 QWidgetList list = topLevelWidgets();
2334 for (int i = 0; i < list.size(); ++i) {
2335 QWidget *w = list.at(i);
2336 if (!(w->windowType() == Qt::Desktop))
2337 postEvent(w, new QEvent(QEvent::LanguageChange));
2342 #if !defined(Q_WS_X11)
2344 // The doc and X implementation of this function is in qapplication_x11.cpp
2346 void QApplication::syncX() {} // do nothing
2350 void QApplicationPrivate::notifyLayoutDirectionChange()
2353 QWidgetList list = q->topLevelWidgets();
2354 for (int i = 0; i < list.size(); ++i) {
2355 QWidget *w = list.at(i);
2356 QEvent ev(QEvent::ApplicationLayoutDirectionChange);
2357 q->sendEvent(w, &ev);
2362 \fn Qt::WindowsVersion QApplication::winVersion()
2364 Use \l QSysInfo::WindowsVersion instead.
2368 \fn void QApplication::setActiveWindow(QWidget* active)
2370 Sets the active window to the \a active widget in response to a system
2371 event. The function is called from the platform specific event handlers.
2373 \warning This function does \e not set the keyboard focus to the active
2374 widget. Call QWidget::activateWindow() instead.
2376 It sets the activeWindow() and focusWidget() attributes and sends proper
2377 \l{QEvent::WindowActivate}{WindowActivate}/\l{QEvent::WindowDeactivate}
2378 {WindowDeactivate} and \l{QEvent::FocusIn}{FocusIn}/\l{QEvent::FocusOut}
2379 {FocusOut} events to all appropriate widgets. The window will then be
2380 painted in active state (e.g. cursors in line edits will blink), and it
2381 will have tool tips enabled.
2383 \sa activeWindow(), QWidget::activateWindow()
2385 void QApplication::setActiveWindow(QWidget* act)
2387 QWidget* window = act?act->window():0;
2389 if (QApplicationPrivate::active_window == window)
2392 #ifndef QT_NO_GRAPHICSVIEW
2393 if (window && window->graphicsProxyWidget()) {
2394 // Activate the proxy's view->viewport() ?
2399 QWidgetList toBeActivated;
2400 QWidgetList toBeDeactivated;
2402 if (QApplicationPrivate::active_window) {
2403 if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2404 QWidgetList list = topLevelWidgets();
2405 for (int i = 0; i < list.size(); ++i) {
2406 QWidget *w = list.at(i);
2407 if (w->isVisible() && w->isActiveWindow())
2408 toBeDeactivated.append(w);
2411 toBeDeactivated.append(QApplicationPrivate::active_window);
2415 #if !defined(Q_WS_MAC)
2416 QWidget *previousActiveWindow = QApplicationPrivate::active_window;
2418 QApplicationPrivate::active_window = window;
2420 if (QApplicationPrivate::active_window) {
2421 if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2422 QWidgetList list = topLevelWidgets();
2423 for (int i = 0; i < list.size(); ++i) {
2424 QWidget *w = list.at(i);
2425 if (w->isVisible() && w->isActiveWindow())
2426 toBeActivated.append(w);
2429 toBeActivated.append(QApplicationPrivate::active_window);
2434 // first the activation/deactivation events
2435 QEvent activationChange(QEvent::ActivationChange);
2436 QEvent windowActivate(QEvent::WindowActivate);
2437 QEvent windowDeactivate(QEvent::WindowDeactivate);
2439 #if !defined(Q_WS_MAC)
2440 if (!previousActiveWindow) {
2441 QEvent appActivate(QEvent::ApplicationActivate);
2442 sendSpontaneousEvent(qApp, &appActivate);
2446 for (int i = 0; i < toBeActivated.size(); ++i) {
2447 QWidget *w = toBeActivated.at(i);
2448 sendSpontaneousEvent(w, &windowActivate);
2449 sendSpontaneousEvent(w, &activationChange);
2452 #ifdef QT_MAC_USE_COCOA
2453 // In case the user clicked on a child window, we need to
2454 // reestablish the stacking order of the window so
2455 // it pops in front of other child windows in cocoa:
2456 qt_cocoaStackChildWindowOnTopOfOtherChildren(window);
2459 for(int i = 0; i < toBeDeactivated.size(); ++i) {
2460 QWidget *w = toBeDeactivated.at(i);
2461 sendSpontaneousEvent(w, &windowDeactivate);
2462 sendSpontaneousEvent(w, &activationChange);
2465 #if !defined(Q_WS_MAC)
2466 if (!QApplicationPrivate::active_window) {
2467 QEvent appDeactivate(QEvent::ApplicationDeactivate);
2468 sendSpontaneousEvent(qApp, &appDeactivate);
2472 if (QApplicationPrivate::popupWidgets == 0) { // !inPopupMode()
2473 // then focus events
2474 if (!QApplicationPrivate::active_window && QApplicationPrivate::focus_widget) {
2475 QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2476 } else if (QApplicationPrivate::active_window) {
2477 QWidget *w = QApplicationPrivate::active_window->focusWidget();
2478 if (w && w->isVisible() /*&& w->focusPolicy() != QWidget::NoFocus*/)
2479 w->setFocus(Qt::ActiveWindowFocusReason);
2481 w = QApplicationPrivate::focusNextPrevChild_helper(QApplicationPrivate::active_window, true);
2483 w->setFocus(Qt::ActiveWindowFocusReason);
2485 // If the focus widget is not in the activate_window, clear the focus
2486 w = QApplicationPrivate::focus_widget;
2487 if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus)
2488 QApplicationPrivate::setFocusWidget(QApplicationPrivate::active_window, Qt::ActiveWindowFocusReason);
2489 else if (!QApplicationPrivate::active_window->isAncestorOf(w))
2490 QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2498 * Helper function that returns the new focus widget, but does not set the focus reason.
2499 * Returns 0 if a new focus widget could not be found.
2500 * Shared with QGraphicsProxyWidgetPrivate::findFocusChild()
2502 QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool next)
2504 uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
2506 QWidget *f = toplevel->focusWidget();
2511 QWidget *test = f->d_func()->focus_next;
2512 while (test && test != f) {
2513 if ((test->focusPolicy() & focus_flag) == focus_flag
2514 && !(test->d_func()->extra && test->d_func()->extra->focus_proxy)
2515 && test->isVisibleTo(toplevel) && test->isEnabled()
2516 && !(w->windowType() == Qt::SubWindow && !w->isAncestorOf(test))
2517 && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))) {
2522 test = test->d_func()->focus_next;
2525 if (qt_in_tab_key_event) {
2526 w->window()->setAttribute(Qt::WA_KeyboardFocusChange);
2535 \fn void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave)
2538 Creates the proper Enter/Leave event when widget \a enter is entered and
2539 widget \a leave is left.
2541 void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave) {
2544 QEvent e(QEvent::Leave);
2545 QApplication::sendEvent(leave, & e);
2548 QEvent e(QEvent::Enter);
2549 QApplication::sendEvent(enter, & e);
2555 if ((!enter && !leave) || (enter == leave))
2558 qDebug() << "QApplicationPrivate::dispatchEnterLeave, ENTER:" << enter << "LEAVE:" << leave;
2560 QWidgetList leaveList;
2561 QWidgetList enterList;
2563 bool sameWindow = leave && enter && leave->window() == enter->window();
2564 if (leave && !sameWindow) {
2567 leaveList.append(w);
2568 } while (!w->isWindow() && (w = w->parentWidget()));
2570 if (enter && !sameWindow) {
2573 enterList.prepend(w);
2574 } while (!w->isWindow() && (w = w->parentWidget()));
2580 while (!w->isWindow() && (w = w->parentWidget()))
2583 while (!w->isWindow() && (w = w->parentWidget()))
2585 QWidget* wenter = enter;
2586 QWidget* wleave = leave;
2587 while (enterDepth > leaveDepth) {
2588 wenter = wenter->parentWidget();
2591 while (leaveDepth > enterDepth) {
2592 wleave = wleave->parentWidget();
2595 while (!wenter->isWindow() && wenter != wleave) {
2596 wenter = wenter->parentWidget();
2597 wleave = wleave->parentWidget();
2601 while (w != wleave) {
2602 leaveList.append(w);
2603 w = w->parentWidget();
2606 while (w != wenter) {
2607 enterList.prepend(w);
2608 w = w->parentWidget();
2612 QEvent leaveEvent(QEvent::Leave);
2613 for (int i = 0; i < leaveList.size(); ++i) {
2614 w = leaveList.at(i);
2615 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2616 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
2617 if (leaveAfterRelease == w)
2618 leaveAfterRelease = 0;
2620 QApplication::sendEvent(w, &leaveEvent);
2621 if (w->testAttribute(Qt::WA_Hover) &&
2622 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2623 Q_ASSERT(instance());
2624 QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos),
2625 QApplication::keyboardModifiers());
2626 qApp->d_func()->notify_helper(w, &he);
2630 QPoint posEnter = QCursor::pos();
2631 QEvent enterEvent(QEvent::Enter);
2632 for (int i = 0; i < enterList.size(); ++i) {
2633 w = enterList.at(i);
2634 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2635 QApplication::sendEvent(w, &enterEvent);
2636 if (w->testAttribute(Qt::WA_Hover) &&
2637 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2638 QHoverEvent he(QEvent::HoverEnter, w->mapFromGlobal(posEnter), QPoint(-1, -1),
2639 QApplication::keyboardModifiers());
2640 qApp->d_func()->notify_helper(w, &he);
2645 #ifndef QT_NO_CURSOR
2646 // Update cursor for alien/graphics widgets.
2648 const bool enterOnAlien = (enter && (isAlien(enter) || enter->testAttribute(Qt::WA_DontShowOnScreen)));
2649 #if defined(Q_WS_X11) || defined(Q_WS_QPA)
2650 //Whenever we leave an alien widget on X11, we need to reset its nativeParentWidget()'s cursor.
2651 // This is not required on Windows as the cursor is reset on every single mouse move.
2652 QWidget *parentOfLeavingCursor = 0;
2653 for (int i = 0; i < leaveList.size(); ++i) {
2654 w = leaveList.at(i);
2657 if (w->testAttribute(Qt::WA_SetCursor)) {
2658 QWidget *parent = w->parentWidget();
2659 while (parent && parent->d_func()->data.in_destructor)
2660 parent = parent->parentWidget();
2661 parentOfLeavingCursor = parent;
2662 //continue looping, we need to find the downest alien widget with a cursor.
2663 // (downest on the screen)
2666 //check that we will not call qt_x11_enforce_cursor twice with the same native widget
2667 if (parentOfLeavingCursor && (!enterOnAlien
2668 || parentOfLeavingCursor->effectiveWinId() != enter->effectiveWinId())) {
2669 #ifndef QT_NO_GRAPHICSVIEW
2670 if (!parentOfLeavingCursor->window()->graphicsProxyWidget())
2673 #if defined(Q_WS_X11)
2674 qt_x11_enforce_cursor(parentOfLeavingCursor,true);
2675 #elif defined(Q_WS_QPA)
2676 if (enter == QApplication::desktop()) {
2677 qt_qpa_set_cursor(enter, true);
2679 qt_qpa_set_cursor(parentOfLeavingCursor, true);
2686 QWidget *cursorWidget = enter;
2687 while (!cursorWidget->isWindow() && !cursorWidget->isEnabled())
2688 cursorWidget = cursorWidget->parentWidget();
2693 #ifndef QT_NO_GRAPHICSVIEW
2694 if (cursorWidget->window()->graphicsProxyWidget()) {
2695 QWidgetPrivate::nearestGraphicsProxyWidget(cursorWidget)->setCursor(cursorWidget->cursor());
2699 #if defined(Q_WS_WIN)
2700 qt_win_set_cursor(cursorWidget, true);
2701 #elif defined(Q_WS_X11)
2702 qt_x11_enforce_cursor(cursorWidget, true);
2703 #elif defined(Q_OS_SYMBIAN)
2704 qt_symbian_set_cursor(cursorWidget, true);
2705 #elif defined(Q_WS_QPA)
2706 qt_qpa_set_cursor(cursorWidget, true);
2713 /* exported for the benefit of testing tools */
2714 Q_WIDGETS_EXPORT bool qt_tryModalHelper(QWidget *widget, QWidget **rettop)
2716 return QApplicationPrivate::tryModalHelper(widget, rettop);
2720 Returns true if \a widget is blocked by a modal window.
2722 bool QApplicationPrivate::isBlockedByModal(QWidget *widget)
2724 widget = widget->window();
2727 if (QApplication::activePopupWidget() == widget)
2730 for (int i = 0; i < qt_modal_stack->size(); ++i) {
2731 QWidget *modalWidget = qt_modal_stack->at(i);
2734 // check if the active modal widget is our widget or a parent of our widget
2735 QWidget *w = widget;
2737 if (w == modalWidget)
2739 w = w->parentWidget();
2742 if ((widget->testAttribute(Qt::WA_WState_Created) || widget->data->winid)
2743 && (modalWidget->testAttribute(Qt::WA_WState_Created) || modalWidget->data->winid)
2744 && IsChild(modalWidget->data->winid, widget->data->winid))
2749 Qt::WindowModality windowModality = modalWidget->windowModality();
2750 if (windowModality == Qt::NonModal) {
2751 // determine the modality type if it hasn't been set on the
2752 // modalWidget, this normally happens when waiting for a
2753 // native dialog. use WindowModal if we are the child of a
2754 // group leader; otherwise use ApplicationModal.
2755 QWidget *m = modalWidget;
2756 while (m && !m->testAttribute(Qt::WA_GroupLeader)) {
2757 m = m->parentWidget();
2761 windowModality = (m && m->testAttribute(Qt::WA_GroupLeader))
2763 : Qt::ApplicationModal;
2766 switch (windowModality) {
2767 case Qt::ApplicationModal:
2769 QWidget *groupLeaderForWidget = widget;
2770 while (groupLeaderForWidget && !groupLeaderForWidget->testAttribute(Qt::WA_GroupLeader))
2771 groupLeaderForWidget = groupLeaderForWidget->parentWidget();
2773 if (groupLeaderForWidget) {
2774 // if \a widget has WA_GroupLeader, it can only be blocked by ApplicationModal children
2775 QWidget *m = modalWidget;
2776 while (m && m != groupLeaderForWidget && !m->testAttribute(Qt::WA_GroupLeader))
2777 m = m->parentWidget();
2778 if (m == groupLeaderForWidget)
2780 } else if (modalWidget != widget) {
2785 case Qt::WindowModal:
2787 QWidget *w = widget;
2789 QWidget *m = modalWidget;
2793 m = m->parentWidget();
2797 w = w->parentWidget();
2804 Q_ASSERT_X(false, "QApplication", "internal error, a modal widget cannot be modeless");
2813 void QApplicationPrivate::enterModal(QWidget *widget)
2815 QSet<QWidget*> blocked;
2816 QList<QWidget*> windows = QApplication::topLevelWidgets();
2817 for (int i = 0; i < windows.count(); ++i) {
2818 QWidget *window = windows.at(i);
2819 if (window->windowType() != Qt::Tool && isBlockedByModal(window))
2820 blocked.insert(window);
2823 enterModal_sys(widget);
2825 windows = QApplication::topLevelWidgets();
2826 QEvent e(QEvent::WindowBlocked);
2827 for (int i = 0; i < windows.count(); ++i) {
2828 QWidget *window = windows.at(i);
2829 if (!blocked.contains(window) && window->windowType() != Qt::Tool && isBlockedByModal(window))
2830 QApplication::sendEvent(window, &e);
2836 void QApplicationPrivate::leaveModal(QWidget *widget)
2838 QSet<QWidget*> blocked;
2839 QList<QWidget*> windows = QApplication::topLevelWidgets();
2840 for (int i = 0; i < windows.count(); ++i) {
2841 QWidget *window = windows.at(i);
2842 if (window->windowType() != Qt::Tool && isBlockedByModal(window))
2843 blocked.insert(window);
2846 leaveModal_sys(widget);
2848 windows = QApplication::topLevelWidgets();
2849 QEvent e(QEvent::WindowUnblocked);
2850 for (int i = 0; i < windows.count(); ++i) {
2851 QWidget *window = windows.at(i);
2852 if(blocked.contains(window) && window->windowType() != Qt::Tool && !isBlockedByModal(window))
2853 QApplication::sendEvent(window, &e);
2861 Called from qapplication_\e{platform}.cpp, returns true
2862 if the widget should accept the event.
2864 bool QApplicationPrivate::tryModalHelper(QWidget *widget, QWidget **rettop)
2866 QWidget *top = QApplication::activeModalWidget();
2870 // the active popup widget always gets the input event
2871 if (QApplication::activePopupWidget())
2874 #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
2875 top = QApplicationPrivate::tryModalHelper_sys(top);
2880 return !isBlockedByModal(widget->window());
2886 QWidget *QApplicationPrivate::pickMouseReceiver(QWidget *candidate, const QPoint &globalPos,
2887 QPoint &pos, QEvent::Type type,
2888 Qt::MouseButtons buttons, QWidget *buttonDown,
2889 QWidget *alienWidget)
2891 Q_ASSERT(candidate);
2893 QWidget *mouseGrabber = QWidget::mouseGrabber();
2894 if (((type == QEvent::MouseMove && buttons) || (type == QEvent::MouseButtonRelease))
2895 && !buttonDown && !mouseGrabber) {
2899 if (alienWidget && alienWidget->internalWinId())
2902 QWidget *receiver = candidate;
2905 mouseGrabber = (buttonDown && !isBlockedByModal(buttonDown)) ? buttonDown : alienWidget;
2907 if (mouseGrabber && mouseGrabber != candidate) {
2908 receiver = mouseGrabber;
2909 pos = receiver->mapFromGlobal(globalPos);
2911 qDebug() << " ** receiver adjusted to:" << receiver << "pos:" << pos;
2922 bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
2923 QWidget *alienWidget, QWidget *nativeWidget,
2924 QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
2929 Q_ASSERT(nativeWidget);
2930 Q_ASSERT(buttonDown);
2932 if (alienWidget && !isAlien(alienWidget))
2935 QPointer<QWidget> receiverGuard = receiver;
2936 QPointer<QWidget> nativeGuard = nativeWidget;
2937 QPointer<QWidget> alienGuard = alienWidget;
2938 QPointer<QWidget> activePopupWidget = QApplication::activePopupWidget();
2940 const bool graphicsWidget = nativeWidget->testAttribute(Qt::WA_DontShowOnScreen);
2943 if (!graphicsWidget) {
2944 // Register the widget that shall receive a leave event
2945 // after the last button is released.
2946 if ((alienWidget || !receiver->internalWinId()) && !leaveAfterRelease && !QWidget::mouseGrabber())
2947 leaveAfterRelease = *buttonDown;
2948 if (event->type() == QEvent::MouseButtonRelease && !event->buttons())
2951 } else if (lastMouseReceiver) {
2952 // Dispatch enter/leave if we move:
2953 // 1) from an alien widget to another alien widget or
2954 // from a native widget to an alien widget (first OR case)
2955 // 2) from an alien widget to a native widget (second OR case)
2956 if ((alienWidget && alienWidget != lastMouseReceiver)
2957 || (isAlien(lastMouseReceiver) && !alienWidget)) {
2958 if (activePopupWidget) {
2959 if (!QWidget::mouseGrabber())
2960 dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver);
2962 dispatchEnterLeave(receiver, lastMouseReceiver);
2969 qDebug() << "QApplicationPrivate::sendMouseEvent: receiver:" << receiver
2970 << "pos:" << event->pos() << "alien" << alienWidget << "button down"
2971 << *buttonDown << "last" << lastMouseReceiver << "leave after release"
2972 << leaveAfterRelease;
2975 // We need this quard in case someone opens a modal dialog / popup. If that's the case
2976 // leaveAfterRelease is set to null, but we shall not update lastMouseReceiver.
2977 const bool wasLeaveAfterRelease = leaveAfterRelease != 0;
2980 result = QApplication::sendSpontaneousEvent(receiver, event);
2982 result = QApplication::sendEvent(receiver, event);
2984 if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease
2985 && !event->buttons() && QWidget::mouseGrabber() != leaveAfterRelease) {
2986 // Dispatch enter/leave if:
2987 // 1) the mouse grabber is an alien widget
2988 // 2) the button is released on an alien widget
2991 enter = alienGuard ? alienWidget : nativeWidget;
2992 else // The receiver is typically deleted on mouse release with drag'n'drop.
2993 enter = QApplication::widgetAt(event->globalPos());
2994 dispatchEnterLeave(enter, leaveAfterRelease);
2995 leaveAfterRelease = 0;
2996 lastMouseReceiver = enter;
2997 } else if (!wasLeaveAfterRelease) {
2998 if (activePopupWidget) {
2999 if (!QWidget::mouseGrabber())
3000 lastMouseReceiver = alienGuard ? alienWidget : (nativeGuard ? nativeWidget : 0);
3002 lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPos());
3009 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_QWS) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
3011 This function should only be called when the widget changes visibility, i.e.
3012 when the \a widget is shown, hidden or deleted. This function does nothing
3013 if the widget is a top-level or native, i.e. not an alien widget. In that
3014 case enter/leave events are genereated by the underlying windowing system.
3016 extern QPointer<QWidget> qt_last_mouse_receiver;
3017 extern QWidget *qt_button_down;
3018 void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
3020 #ifndef QT_NO_CURSOR
3021 #if defined(Q_WS_QWS) || defined(Q_WS_QPA)
3022 if (!widget || widget->isWindow())
3025 if (!widget || widget->internalWinId() || widget->isWindow())
3028 const bool widgetInShow = widget->isVisible() && !widget->data->in_destructor;
3029 if (!widgetInShow && widget != qt_last_mouse_receiver)
3030 return; // Widget was not under the cursor when it was hidden/deleted.
3032 if (widgetInShow && widget->parentWidget()->data->in_show)
3033 return; // Ingore recursive show.
3035 QWidget *mouseGrabber = QWidget::mouseGrabber();
3036 if (mouseGrabber && mouseGrabber != widget)
3037 return; // Someone else has the grab; enter/leave should not occur.
3039 QWidget *tlw = widget->window();
3040 if (tlw->data->in_destructor || tlw->data->is_closing)
3041 return; // Closing down the business.
3043 if (widgetInShow && (!qt_last_mouse_receiver || qt_last_mouse_receiver->window() != tlw))
3044 return; // Mouse cursor not inside the widget's top-level.
3046 const QPoint globalPos(QCursor::pos());
3047 QPoint windowPos = tlw->mapFromGlobal(globalPos);
3049 // Find the current widget under the mouse. If this function was called from
3050 // the widget's destructor, we have to make sure childAt() doesn't take into
3051 // account widgets that are about to be destructed.
3052 QWidget *widgetUnderCursor = tlw->d_func()->childAt_helper(windowPos, widget->data->in_destructor);
3053 if (!widgetUnderCursor)
3054 widgetUnderCursor = tlw;
3055 QPoint pos = widgetUnderCursor->mapFrom(tlw, windowPos);
3057 if (widgetInShow && widgetUnderCursor != widget && !widget->isAncestorOf(widgetUnderCursor))
3058 return; // Mouse cursor not inside the widget or any of its children.
3060 if (widget->data->in_destructor && qt_button_down == widget)
3063 // Send enter/leave events followed by a mouse move on the entered widget.
3064 QMouseEvent e(QEvent::MouseMove, pos, windowPos, globalPos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
3065 sendMouseEvent(widgetUnderCursor, &e, widgetUnderCursor, tlw, &qt_button_down, qt_last_mouse_receiver);
3066 #endif // QT_NO_CURSOR
3068 #endif // Q_WS_WIN || Q_WS_X11 || Q_WS_MAC
3071 Returns the desktop widget (also called the root window).
3073 The desktop may be composed of multiple screens, so it would be incorrect,
3074 for example, to attempt to \e center some widget in the desktop's geometry.
3075 QDesktopWidget has various functions for obtaining useful geometries upon
3076 the desktop, such as QDesktopWidget::screenGeometry() and
3077 QDesktopWidget::availableGeometry().
3079 On X11, it is also possible to draw on the desktop.
3081 QDesktopWidget *QApplication::desktop()
3083 if (!qt_desktopWidget || // not created yet
3084 !(qt_desktopWidget->windowType() == Qt::Desktop)) { // reparented away
3085 qt_desktopWidget = new QDesktopWidget();
3087 return qt_desktopWidget;
3090 #if !defined(Q_WS_QPA) && !defined(QT_NO_CLIPBOARD)
3092 Returns a pointer to the application global clipboard.
3094 \note The QApplication object should already be constructed before
3095 accessing the clipboard.
3097 QClipboard *QApplication::clipboard()
3099 if (qt_clipboard == 0) {
3101 qWarning("QApplication: Must construct a QApplication before accessing a QClipboard");
3104 qt_clipboard = new QClipboard(0);
3106 return qt_clipboard;
3108 #endif // Q_WS_QPA && QT_NO_CLIPBOARD
3110 Sets whether Qt should use the system's standard colors, fonts, etc., to
3111 \a on. By default, this is true.
3113 This function must be called before creating the QApplication object, like
3116 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 6
3118 \sa desktopSettingsAware()
3120 void QApplication::setDesktopSettingsAware(bool on)
3122 QApplicationPrivate::obey_desktop_settings = on;
3126 Returns true if Qt is set to use the system's standard colors, fonts, etc.;
3127 otherwise returns false. The default is true.
3129 \sa setDesktopSettingsAware()
3131 bool QApplication::desktopSettingsAware()
3133 return QApplicationPrivate::obey_desktop_settings;
3137 Returns the current state of the modifier keys on the keyboard. The current
3138 state is updated sychronously as the event queue is emptied of events that
3139 will spontaneously change the keyboard state (QEvent::KeyPress and
3140 QEvent::KeyRelease events).
3142 It should be noted this may not reflect the actual keys held on the input
3143 device at the time of calling but rather the modifiers as last reported in
3144 one of the above events. If no keys are being held Qt::NoModifier is
3147 \sa mouseButtons(), queryKeyboardModifiers()
3150 Qt::KeyboardModifiers QApplication::keyboardModifiers()
3152 return QApplicationPrivate::modifier_buttons;
3156 \fn Qt::KeyboardModifiers QApplication::queryKeyboardModifiers()
3158 Queries and returns the state of the modifier keys on the keyboard.
3159 Unlike keyboardModifiers, this method returns the actual keys held
3160 on the input device at the time of calling the method.
3162 It does not rely on the keypress events having been received by this
3163 process, which makes it possible to check the modifiers while moving
3164 a window, for instance. Note that in most cases, you should use
3165 keyboardModifiers(), which is faster and more accurate since it contains
3166 the state of the modifiers as they were when the currently processed
3169 \sa keyboardModifiers()
3174 Qt::KeyboardModifiers QApplication::queryKeyboardModifiers()
3176 qWarning("queryKeyboardModifiers() doesn't have a QPA implementation");
3177 return QApplicationPrivate::modifier_buttons;
3181 Returns the current state of the buttons on the mouse. The current state is
3182 updated syncronously as the event queue is emptied of events that will
3183 spontaneously change the mouse state (QEvent::MouseButtonPress and
3184 QEvent::MouseButtonRelease events).
3186 It should be noted this may not reflect the actual buttons held on the
3187 input device at the time of calling but rather the mouse buttons as last
3188 reported in one of the above events. If no mouse buttons are being held
3189 Qt::NoButton is returned.
3191 \sa keyboardModifiers()
3194 Qt::MouseButtons QApplication::mouseButtons()
3196 return QApplicationPrivate::mouse_buttons;
3200 \fn bool QApplication::isSessionRestored() const
3202 Returns true if the application has been restored from an earlier
3203 \l{Session Management}{session}; otherwise returns false.
3205 \sa sessionId(), commitData(), saveState()
3210 \fn QString QApplication::sessionId() const
3212 Returns the current \l{Session Management}{session's} identifier.
3214 If the application has been restored from an earlier session, this
3215 identifier is the same as it was in that previous session. The session
3216 identifier is guaranteed to be unique both for different applications
3217 and for different instances of the same application.
3219 \sa isSessionRestored(), sessionKey(), commitData(), saveState()
3223 \fn QString QApplication::sessionKey() const
3225 Returns the session key in the current \l{Session Management}{session}.
3227 If the application has been restored from an earlier session, this key is
3228 the same as it was when the previous session ended.
3230 The session key changes with every call of commitData() or saveState().
3232 \sa isSessionRestored(), sessionId(), commitData(), saveState()
3234 #ifndef QT_NO_SESSIONMANAGER
3235 bool QApplication::isSessionRestored() const
3237 Q_D(const QApplication);
3238 return d->is_session_restored;
3241 QString QApplication::sessionId() const
3243 Q_D(const QApplication);
3244 return d->session_id;
3247 QString QApplication::sessionKey() const
3249 Q_D(const QApplication);
3250 return d->session_key;
3258 \fn void QApplication::commitDataRequest(QSessionManager &manager)
3260 This signal deals with \l{Session Management}{session management}. It is
3261 emitted when the QSessionManager wants the application to commit all its
3264 Usually this means saving all open files, after getting permission from
3265 the user. Furthermore you may want to provide a means by which the user
3266 can cancel the shutdown.
3268 You should not exit the application within this signal. Instead,
3269 the session manager may or may not do this afterwards, depending on the
3272 \warning Within this signal, no user interaction is possible, \e
3273 unless you ask the \a manager for explicit permission. See
3274 QSessionManager::allowsInteraction() and
3275 QSessionManager::allowsErrorInteraction() for details and example
3278 \note You should use Qt::DirectConnection when connecting to this signal.
3280 \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
3284 This function deals with \l{Session Management}{session management}. It is
3285 invoked when the QSessionManager wants the application to commit all its
3288 Usually this means saving all open files, after getting permission from the
3289 user. Furthermore you may want to provide a means by which the user can
3290 cancel the shutdown.
3292 You should not exit the application within this function. Instead, the
3293 session manager may or may not do this afterwards, depending on the
3296 \warning Within this function, no user interaction is possible, \e
3297 unless you ask the \a manager for explicit permission. See
3298 QSessionManager::allowsInteraction() and
3299 QSessionManager::allowsErrorInteraction() for details and example
3302 The default implementation requests interaction and sends a close event to
3303 all visible top-level widgets. If any event was rejected, the shutdown is
3306 \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
3308 #ifndef QT_NO_SESSIONMANAGER
3309 void QApplication::commitData(QSessionManager& manager )
3311 emit commitDataRequest(manager);
3312 if (manager.allowsInteraction()) {
3314 QWidgetList list = QApplication::topLevelWidgets();
3315 bool cancelled = false;
3316 for (int i = 0; !cancelled && i < list.size(); ++i) {
3317 QWidget* w = list.at(i);
3318 if (w->isVisible() && !done.contains(w)) {
3319 cancelled = !w->close();
3322 list = QApplication::topLevelWidgets();
3333 \fn void QApplication::saveStateRequest(QSessionManager &manager)
3335 This signal deals with \l{Session Management}{session management}. It is
3336 invoked when the \l{QSessionManager}{session manager} wants the application
3337 to preserve its state for a future session.
3339 For example, a text editor would create a temporary file that includes the
3340 current contents of its edit buffers, the location of the cursor and other
3341 aspects of the current editing session.
3343 You should never exit the application within this signal. Instead, the
3344 session manager may or may not do this afterwards, depending on the
3345 context. Futhermore, most session managers will very likely request a saved
3346 state immediately after the application has been started. This permits the
3347 session manager to learn about the application's restart policy.
3349 \warning Within this function, no user interaction is possible, \e
3350 unless you ask the \a manager for explicit permission. See
3351 QSessionManager::allowsInteraction() and
3352 QSessionManager::allowsErrorInteraction() for details.
3354 \note You should use Qt::DirectConnection when connecting to this signal.
3356 \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
3360 This function deals with \l{Session Management}{session management}. It is
3361 invoked when the \l{QSessionManager}{session manager} wants the application
3362 to preserve its state for a future session.
3364 For example, a text editor would create a temporary file that includes the
3365 current contents of its edit buffers, the location of the cursor and other
3366 aspects of the current editing session.
3368 You should never exit the application within this function. Instead, the
3369 session manager may or may not do this afterwards, depending on the
3370 context. Futhermore, most session managers will very likely request a saved
3371 state immediately after the application has been started. This permits the
3372 session manager to learn about the application's restart policy.
3374 \warning Within this function, no user interaction is possible, \e
3375 unless you ask the \a manager for explicit permission. See
3376 QSessionManager::allowsInteraction() and
3377 QSessionManager::allowsErrorInteraction() for details.
3379 \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
3382 void QApplication::saveState(QSessionManager &manager)
3384 emit saveStateRequest(manager);
3386 #endif //QT_NO_SESSIONMANAGER
3388 Sets the time after which a drag should start to \a ms ms.
3393 void QApplication::setStartDragTime(int ms)
3399 \property QApplication::startDragTime
3400 \brief the time in milliseconds that a mouse button must be held down
3401 before a drag and drop operation will begin
3403 If you support drag and drop in your application, and want to start a drag
3404 and drop operation after the user has held down a mouse button for a
3405 certain amount of time, you should use this property's value as the delay.
3407 Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for
3410 The default value is 500 ms.
3412 \sa startDragDistance(), {Drag and Drop}
3415 int QApplication::startDragTime()
3417 return qApp->styleHints()->startDragTime();
3421 Sets the distance after which a drag should start to \a l pixels.
3423 \sa startDragDistance()
3426 void QApplication::setStartDragDistance(int l)
3432 \property QApplication::startDragDistance
3434 If you support drag and drop in your application, and want to start a drag
3435 and drop operation after the user has moved the cursor a certain distance
3436 with a button held down, you should use this property's value as the
3437 minimum distance required.
3439 For example, if the mouse position of the click is stored in \c startPos
3440 and the current position (e.g. in the mouse move event) is \c currentPos,
3441 you can find out if a drag should be started with code like this:
3443 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 7
3445 Qt uses this value internally, e.g. in QFileDialog.
3447 The default value is 4 pixels.
3449 \sa startDragTime() QPoint::manhattanLength() {Drag and Drop}
3452 int QApplication::startDragDistance()
3454 return qApp->styleHints()->startDragTime();
3458 \fn void QApplication::setReverseLayout(bool reverse)
3460 Use setLayoutDirection() instead.
3464 \fn void QApplication::reverseLayout()
3466 Use layoutDirection() instead.
3473 Strips out vertical alignment flags and transforms an alignment \a align
3474 of Qt::AlignLeft into Qt::AlignLeft or Qt::AlignRight according to the
3479 Qt::Alignment QApplication::horizontalAlignment(Qt::Alignment align)
3481 return QGuiApplicationPrivate::visualAlignment(layoutDirection(), align);
3486 Enters the main event loop and waits until exit() is called, then returns
3487 the value that was set to exit() (which is 0 if exit() is called via
3490 It is necessary to call this function to start event handling. The main
3491 event loop receives events from the window system and dispatches these to
3492 the application widgets.
3494 Generally, no user interaction can take place before calling exec(). As a
3495 special case, modal widgets like QMessageBox can be used before calling
3496 exec(), because modal widgets call exec() to start a local event loop.
3498 To make your application perform idle processing, i.e., executing a special
3499 function whenever there are no pending events, use a QTimer with 0 timeout.
3500 More advanced idle processing schemes can be achieved using processEvents().
3502 We recommend that you connect clean-up code to the
3503 \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
3504 application's \c{main()} function. This is because, on some platforms the
3505 QApplication::exec() call may not return. For example, on the Windows
3506 platform, when the user logs off, the system terminates the process after Qt
3507 closes all top-level windows. Hence, there is \e{no guarantee} that the
3508 application will have time to exit its event loop and execute code at the
3509 end of the \c{main()} function, after the QApplication::exec() call.
3511 \sa quitOnLastWindowClosed, quit(), exit(), processEvents(),
3512 QCoreApplication::exec()
3514 int QApplication::exec()
3516 #ifndef QT_NO_ACCESSIBILITY
3517 QAccessible::setRootObject(qApp);
3519 return QApplicationBase::exec();
3524 bool QApplication::notify(QObject *receiver, QEvent *e)
3527 // no events are delivered after ~QCoreApplication() has started
3528 if (QApplicationPrivate::is_app_closing)
3531 if (receiver == 0) { // serious error
3532 qWarning("QApplication::notify: Unexpected null receiver");
3537 d->checkReceiverThread(receiver);
3540 // capture the current mouse/keyboard state
3541 if(e->spontaneous()) {
3542 if (e->type() == QEvent::KeyPress
3543 || e->type() == QEvent::KeyRelease) {
3544 QKeyEvent *ke = static_cast<QKeyEvent*>(e);
3545 QApplicationPrivate::modifier_buttons = ke->modifiers();
3546 } else if(e->type() == QEvent::MouseButtonPress
3547 || e->type() == QEvent::MouseButtonRelease) {
3548 QMouseEvent *me = static_cast<QMouseEvent*>(e);
3549 QApplicationPrivate::modifier_buttons = me->modifiers();
3550 if(me->type() == QEvent::MouseButtonPress)
3551 QApplicationPrivate::mouse_buttons |= me->button();
3553 QApplicationPrivate::mouse_buttons &= ~me->button();
3555 #if !defined(QT_NO_WHEELEVENT) || !defined(QT_NO_TABLETEVENT)
3557 # ifndef QT_NO_WHEELEVENT
3558 || e->type() == QEvent::Wheel
3560 # ifndef QT_NO_TABLETEVENT
3561 || e->type() == QEvent::TabletMove
3562 || e->type() == QEvent::TabletPress
3563 || e->type() == QEvent::TabletRelease
3566 QInputEvent *ie = static_cast<QInputEvent*>(e);
3567 QApplicationPrivate::modifier_buttons = ie->modifiers();
3569 #endif // !QT_NO_WHEELEVENT || !QT_NO_TABLETEVENT
3572 #ifndef QT_NO_GESTURES
3573 // walk through parents and check for gestures
3574 if (d->gestureManager) {
3575 switch (e->type()) {
3577 case QEvent::MetaCall:
3578 case QEvent::DeferredDelete:
3579 case QEvent::DragEnter: case QEvent::DragMove: case QEvent::DragLeave:
3580 case QEvent::Drop: case QEvent::DragResponse:
3581 case QEvent::ChildAdded: case QEvent::ChildPolished:
3583 case QEvent::ChildInsertedRequest:
3584 case QEvent::ChildInserted:
3585 case QEvent::LayoutHint:
3587 case QEvent::ChildRemoved:
3588 case QEvent::UpdateRequest:
3589 case QEvent::UpdateLater:
3590 case QEvent::AccessibilityPrepare:
3591 case QEvent::LocaleChange:
3593 case QEvent::IconDrag:
3594 case QEvent::StyleChange:
3595 case QEvent::AccessibilityHelp:
3596 case QEvent::AccessibilityDescription:
3597 case QEvent::GraphicsSceneDragEnter:
3598 case QEvent::GraphicsSceneDragMove:
3599 case QEvent::GraphicsSceneDragLeave:
3600 case QEvent::GraphicsSceneDrop:
3601 case QEvent::DynamicPropertyChange:
3602 case QEvent::NetworkReplyUpdated:
3605 if (receiver->isWidgetType()) {
3606 if (d->gestureManager->filterEvent(static_cast<QWidget *>(receiver), e))
3609 // a special case for events that go to QGesture objects.
3610 // We pass the object to the gesture manager and it'll figure
3611 // out if it's QGesture or not.
3612 if (d->gestureManager->filterEvent(receiver, e))
3617 #endif // QT_NO_GESTURES
3619 // User input and window activation makes tooltips sleep
3620 switch (e->type()) {
3622 case QEvent::ActivationChange:
3623 case QEvent::KeyPress:
3624 case QEvent::KeyRelease:
3625 case QEvent::FocusOut:
3626 case QEvent::FocusIn:
3627 case QEvent::MouseButtonPress:
3628 case QEvent::MouseButtonRelease:
3629 case QEvent::MouseButtonDblClick:
3630 d->toolTipFallAsleep.stop();
3633 d->toolTipWakeUp.stop();
3639 if (!receiver->isWidgetType()) {
3640 res = d->notify_helper(receiver, e);
3641 } else switch (e->type()) {
3642 #if defined QT3_SUPPORT && !defined(QT_NO_SHORTCUT)
3645 if (d->use_compat()) {
3646 QKeyEvent* key = static_cast<QKeyEvent*>(e);
3647 res = d->notify_helper(receiver, e);
3649 if (!res && !key->isAccepted())
3650 res = d->qt_dispatchAccelEvent(static_cast<QWidget *>(receiver), key);
3652 // next lines are for compatibility with Qt <= 3.0.x: old
3653 // QAccel was listening on toplevel widgets
3654 if (!res && !key->isAccepted() && !static_cast<QWidget *>(receiver)->isWindow())
3655 res = d->notify_helper(static_cast<QWidget *>(receiver)->window(), e);
3659 #endif //QT3_SUPPORT && !QT_NO_SHORTCUT
3660 case QEvent::ShortcutOverride:
3661 case QEvent::KeyPress:
3662 case QEvent::KeyRelease:
3664 bool isWidget = receiver->isWidgetType();
3665 bool isGraphicsWidget = false;
3666 #ifndef QT_NO_GRAPHICSVIEW
3667 isGraphicsWidget = !isWidget && qobject_cast<QGraphicsWidget *>(receiver);
3669 if (!isWidget && !isGraphicsWidget) {
3670 res = d->notify_helper(receiver, e);
3674 QKeyEvent* key = static_cast<QKeyEvent*>(e);
3675 #if defined QT3_SUPPORT && !defined(QT_NO_SHORTCUT)
3676 if (d->use_compat() && d->qt_tryComposeUnicode(static_cast<QWidget*>(receiver), key))
3679 if (key->type()==QEvent::KeyPress) {
3680 #ifndef QT_NO_SHORTCUT
3681 // Try looking for a Shortcut before sending key events
3682 if ((res = qApp->d_func()->shortcutMap.tryShortcutEvent(receiver, key)))
3685 qt_in_tab_key_event = (key->key() == Qt::Key_Backtab
3686 || key->key() == Qt::Key_Tab
3687 || key->key() == Qt::Key_Left
3688 || key->key() == Qt::Key_Up
3689 || key->key() == Qt::Key_Right
3690 || key->key() == Qt::Key_Down);
3692 bool def = key->isAccepted();
3693 QPointer<QObject> pr = receiver;
3699 res = d->notify_helper(receiver, e);
3700 QWidget *w = isWidget ? static_cast<QWidget *>(receiver) : 0;
3701 #ifndef QT_NO_GRAPHICSVIEW
3702 QGraphicsWidget *gw = isGraphicsWidget ? static_cast<QGraphicsWidget *>(receiver) : 0;
3705 if ((res && key->isAccepted())
3707 QLineEdit will emit a signal on Key_Return, but
3708 ignore the event, and sometimes the connected
3709 slot deletes the QLineEdit (common in itemview
3710 delegates), so we have to check if the widget
3711 was destroyed even if the event was ignored (to
3714 note that we don't have to reset pw while
3715 propagating (because the original receiver will
3716 be destroyed if one of its ancestors is)
3719 || (isWidget && (w->isWindow() || !w->parentWidget()))
3720 #ifndef QT_NO_GRAPHICSVIEW
3721 || (isGraphicsWidget && (gw->isWindow() || !gw->parentWidget()))
3727 #ifndef QT_NO_GRAPHICSVIEW
3728 receiver = w ? (QObject *)w->parentWidget() : (QObject *)gw->parentWidget();
3730 receiver = w->parentWidget();
3733 qt_in_tab_key_event = false;
3736 case QEvent::MouseButtonPress:
3737 case QEvent::MouseButtonRelease:
3738 case QEvent::MouseButtonDblClick:
3739 case QEvent::MouseMove:
3741 QWidget* w = static_cast<QWidget *>(receiver);
3743 QMouseEvent* mouse = static_cast<QMouseEvent*>(e);
3744 QPoint relpos = mouse->pos();
3746 if (e->spontaneous()) {
3748 if (e->type() == QEvent::MouseButtonPress) {
3749 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3751 Qt::MouseFocusReason);
3754 // ### Qt 5 These dynamic tool tips should be an OPT-IN feature. Some platforms
3755 // like Mac OS X (probably others too), can optimize their views by not
3756 // dispatching mouse move events. We have attributes to control hover,
3757 // and mouse tracking, but as long as we are deciding to implement this
3758 // feature without choice of opting-in or out, you ALWAYS have to have
3759 // tracking enabled. Therefore, the other properties give a false sense of
3760 // performance enhancement.
3761 if (e->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3762 d->toolTipWidget = w;
3763 d->toolTipPos = relpos;
3764 d->toolTipGlobalPos = mouse->globalPos();
3765 d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive()?20:700, this);
3769 bool eventAccepted = mouse->isAccepted();
3771 QPointer<QWidget> pw = w;
3773 QMouseEvent me(mouse->type(), relpos, mouse->windowPos(), mouse->globalPos(), mouse->button(), mouse->buttons(),
3774 mouse->modifiers());
3775 me.spont = mouse->spontaneous();
3776 me.setTimestamp(mouse->timestamp());
3777 // throw away any mouse-tracking-only mouse events
3778 if (!w->hasMouseTracking()
3779 && mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3780 // but still send them through all application event filters (normally done by notify_helper)
3781 for (int i = 0; i < d->eventFilters.size(); ++i) {
3782 register QObject *obj = d->eventFilters.at(i);
3785 if (obj->d_func()->threadData != w->d_func()->threadData) {
3786 qWarning("QApplication: Object event filter cannot be in a different thread.");
3789 if (obj->eventFilter(w, w == receiver ? mouse : &me))
3794 w->setAttribute(Qt::WA_NoMouseReplay, false);
3795 res = d->notify_helper(w, w == receiver ? mouse : &me);
3798 eventAccepted = (w == receiver ? mouse : &me)->isAccepted();
3799 if (res && eventAccepted)
3801 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3804 w = w->parentWidget();
3807 mouse->setAccepted(eventAccepted);
3809 if (e->type() == QEvent::MouseMove) {
3813 w = static_cast<QWidget *>(receiver);
3814 relpos = mouse->pos();
3815 QPoint diff = relpos - w->mapFromGlobal(d->hoverGlobalPos);
3817 if (w->testAttribute(Qt::WA_Hover) &&
3818 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
3819 QHoverEvent he(QEvent::HoverMove, relpos, relpos - diff, mouse->modifiers());
3820 d->notify_helper(w, &he);
3822 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3825 w = w->parentWidget();
3829 d->hoverGlobalPos = mouse->globalPos();
3832 #ifndef QT_NO_WHEELEVENT
3835 QWidget* w = static_cast<QWidget *>(receiver);
3836 QWheelEvent* wheel = static_cast<QWheelEvent*>(e);
3837 QPoint relpos = wheel->pos();
3838 bool eventAccepted = wheel->isAccepted();
3840 if (e->spontaneous()) {
3841 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3843 Qt::MouseFocusReason);
3847 QWheelEvent we(relpos, wheel->globalPos(), wheel->delta(), wheel->buttons(),
3848 wheel->modifiers(), wheel->orientation());
3849 we.spont = wheel->spontaneous();
3850 res = d->notify_helper(w, w == receiver ? wheel : &we);
3851 eventAccepted = ((w == receiver) ? wheel : &we)->isAccepted();
3853 if ((res && eventAccepted)
3854 || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3858 w = w->parentWidget();
3860 wheel->setAccepted(eventAccepted);
3864 #ifndef QT_NO_CONTEXTMENU
3865 case QEvent::ContextMenu:
3867 QWidget* w = static_cast<QWidget *>(receiver);
3868 QContextMenuEvent *context = static_cast<QContextMenuEvent*>(e);
3869 QPoint relpos = context->pos();
3870 bool eventAccepted = context->isAccepted();
3872 QContextMenuEvent ce(context->reason(), relpos, context->globalPos(), context->modifiers());
3873 ce.spont = e->spontaneous();
3874 res = d->notify_helper(w, w == receiver ? context : &ce);
3875 eventAccepted = ((w == receiver) ? context : &ce)->isAccepted();
3878 if ((res && eventAccepted)
3879 || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3883 w = w->parentWidget();
3885 context->setAccepted(eventAccepted);
3888 #endif // QT_NO_CONTEXTMENU
3889 #ifndef QT_NO_TABLETEVENT
3890 case QEvent::TabletMove:
3891 case QEvent::TabletPress:
3892 case QEvent::TabletRelease:
3894 QWidget *w = static_cast<QWidget *>(receiver);
3895 QTabletEvent *tablet = static_cast<QTabletEvent*>(e);
3896 QPoint relpos = tablet->pos();
3897 bool eventAccepted = tablet->isAccepted();
3899 QTabletEvent te(tablet->type(), relpos, tablet->globalPos(),
3900 tablet->hiResGlobalPos(), tablet->device(), tablet->pointerType(),
3901 tablet->pressure(), tablet->xTilt(), tablet->yTilt(),
3902 tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
3903 tablet->modifiers(), tablet->uniqueId());
3904 te.spont = e->spontaneous();
3905 res = d->notify_helper(w, w == receiver ? tablet : &te);
3906 eventAccepted = ((w == receiver) ? tablet : &te)->isAccepted();
3908 if ((res && eventAccepted)
3910 || w->testAttribute(Qt::WA_NoMousePropagation))
3914 w = w->parentWidget();
3916 tablet->setAccepted(eventAccepted);
3917 qt_tabletChokeMouse = tablet->isAccepted();
3920 #endif // QT_NO_TABLETEVENT
3922 #if !defined(QT_NO_TOOLTIP) || !defined(QT_NO_WHATSTHIS)
3923 case QEvent::ToolTip:
3924 case QEvent::WhatsThis:
3925 case QEvent::QueryWhatsThis:
3927 QWidget* w = static_cast<QWidget *>(receiver);
3928 QHelpEvent *help = static_cast<QHelpEvent*>(e);
3929 QPoint relpos = help->pos();
3930 bool eventAccepted = help->isAccepted();
3932 QHelpEvent he(help->type(), relpos, help->globalPos());
3933 he.spont = e->spontaneous();
3934 res = d->notify_helper(w, w == receiver ? help : &he);
3936 eventAccepted = (w == receiver ? help : &he)->isAccepted();
3937 if ((res && eventAccepted) || w->isWindow())
3941 w = w->parentWidget();
3943 help->setAccepted(eventAccepted);
3947 #if !defined(QT_NO_STATUSTIP) || !defined(QT_NO_WHATSTHIS)
3948 case QEvent::StatusTip:
3949 case QEvent::WhatsThisClicked:
3951 QWidget *w = static_cast<QWidget *>(receiver);
3953 res = d->notify_helper(w, e);
3954 if ((res && e->isAccepted()) || w->isWindow())
3956 w = w->parentWidget();
3962 #ifndef QT_NO_DRAGANDDROP
3963 case QEvent::DragEnter: {
3964 QWidget* w = static_cast<QWidget *>(receiver);
3965 QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent *>(e);
3967 // HIView has a slight difference in how it delivers events to children and parents
3968 // It will not give a leave to a child's parent when it enters a child.
3969 QWidget *currentTarget = QDragManager::self()->currentTarget();
3970 if (currentTarget) {
3971 // Assume currentTarget did not get a leave
3972 QDragLeaveEvent event;
3973 QApplication::sendEvent(currentTarget, &event);
3976 #ifndef QT_NO_GRAPHICSVIEW
3977 // QGraphicsProxyWidget handles its own propagation,
3978 // and we must not change QDragManagers currentTarget.
3979 QWExtra *extra = w->window()->d_func()->extra;
3980 if (extra && extra->proxyWidget) {
3981 res = d->notify_helper(w, dragEvent);
3986 if (w->isEnabled() && w->acceptDrops()) {
3987 res = d->notify_helper(w, dragEvent);
3988 if (res && dragEvent->isAccepted()) {
3989 QDragManager::self()->setCurrentTarget(w);
3995 dragEvent->p = w->mapToParent(dragEvent->p);
3996 w = w->parentWidget();
4000 case QEvent::DragMove:
4002 case QEvent::DragLeave: {
4003 QWidget* w = static_cast<QWidget *>(receiver);
4004 #ifndef QT_NO_GRAPHICSVIEW
4005 // QGraphicsProxyWidget handles its own propagation,
4006 // and we must not change QDragManagers currentTarget.
4007 QWExtra *extra = w->window()->d_func()->extra;
4008 bool isProxyWidget = extra && extra->proxyWidget;
4011 w = qobject_cast<QWidget *>(QDragManager::self()->currentTarget());
4015 // HIView has a slight difference in how it delivers events to children and parents
4016 // It will not give an enter to a child's parent when it leaves the child.
4017 if (e->type() == QEvent::DragLeave)
4019 // Assume that w did not get an enter.
4020 QDropEvent *dropEvent = static_cast<QDropEvent *>(e);
4021 QDragEnterEvent dragEnterEvent(dropEvent->pos(), dropEvent->possibleActions(),
4022 dropEvent->mimeData(), dropEvent->mouseButtons(),
4023 dropEvent->keyboardModifiers());
4024 QApplication::sendEvent(receiver, &dragEnterEvent);
4025 w = QDragManager::self()->currentTarget();
4030 if (e->type() == QEvent::DragMove || e->type() == QEvent::Drop) {
4031 QDropEvent *dragEvent = static_cast<QDropEvent *>(e);
4032 QWidget *origReciver = static_cast<QWidget *>(receiver);
4033 while (origReciver && w != origReciver) {
4034 dragEvent->p = origReciver->mapToParent(dragEvent->p);
4035 origReciver = origReciver->parentWidget();
4038 res = d->notify_helper(w, e);
4039 if (e->type() != QEvent::DragMove
4040 #ifndef QT_NO_GRAPHICSVIEW
4044 QDragManager::self()->setCurrentTarget(0, e->type() == QEvent::Drop);
4048 case QEvent::TouchBegin:
4049 // Note: TouchUpdate and TouchEnd events are never propagated
4051 QWidget *widget = static_cast<QWidget *>(receiver);
4052 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
4053 bool eventAccepted = touchEvent->isAccepted();
4054 if (widget->testAttribute(Qt::WA_AcceptTouchEvents) && e->spontaneous()) {
4055 // give the widget focus if the focus policy allows it
4056 QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget,
4058 Qt::MouseFocusReason);
4062 // first, try to deliver the touch event
4063 bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
4064 touchEvent->setWidget(widget);
4065 touchEvent->setAccepted(acceptTouchEvents);
4066 QWeakPointer<QWidget> p = widget;
4067 res = acceptTouchEvents && d->notify_helper(widget, touchEvent);
4068 eventAccepted = touchEvent->isAccepted();
4070 // widget was deleted
4073 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
4075 touchEvent->spont = false;
4076 if (res && eventAccepted) {
4077 // the first widget to accept the TouchBegin gets an implicit grab.
4078 for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
4079 const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i);
4080 d->widgetForTouchPointId[touchPoint.id()] = widget;
4083 } else if (p.isNull() || widget->isWindow() || widget->testAttribute(Qt::WA_NoMousePropagation)) {
4086 QPoint offset = widget->pos();
4087 widget = widget->parentWidget();
4088 touchEvent->setWidget(widget);
4089 for (int i = 0; i < touchEvent->_touchPoints.size(); ++i) {
4090 QTouchEvent::TouchPoint &pt = touchEvent->_touchPoints[i];
4091 QRectF rect = pt.rect();
4092 rect.moveCenter(offset);
4094 pt.d->startPos = pt.startPos() + offset;
4095 pt.d->lastPos = pt.lastPos() + offset;
4099 touchEvent->setAccepted(eventAccepted);
4102 case QEvent::RequestSoftwareInputPanel:
4103 inputPanel()->show();
4105 case QEvent::CloseSoftwareInputPanel:
4106 inputPanel()->hide();
4109 #ifndef QT_NO_GESTURES
4110 case QEvent::NativeGesture:
4112 // only propagate the first gesture event (after the GID_BEGIN)
4113 QWidget *w = static_cast<QWidget *>(receiver);
4116 res = d->notify_helper(w, e);
4117 if ((res && e->isAccepted()) || w->isWindow())
4119 w = w->parentWidget();
4123 case QEvent::Gesture:
4124 case QEvent::GestureOverride:
4126 if (receiver->isWidgetType()) {
4127 QWidget *w = static_cast<QWidget *>(receiver);
4128 QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(e);
4129 QList<QGesture *> allGestures = gestureEvent->gestures();
4131 bool eventAccepted = gestureEvent->isAccepted();
4132 bool wasAccepted = eventAccepted;
4134 // send only gestures the widget expects
4135 QList<QGesture *> gestures;
4136 QWidgetPrivate *wd = w->d_func();
4137 for (int i = 0; i < allGestures.size();) {
4138 QGesture *g = allGestures.at(i);
4139 Qt::GestureType type = g->gestureType();
4140 QMap<Qt::GestureType, Qt::GestureFlags>::iterator contextit =
4141 wd->gestureContext.find(type);
4142 bool deliver = contextit != wd->gestureContext.end() &&
4143 (g->state() == Qt::GestureStarted || w == receiver ||
4144 (contextit.value() & Qt::ReceivePartialGestures));
4146 allGestures.removeAt(i);
4152 if (!gestures.isEmpty()) { // we have gestures for this w
4153 QGestureEvent ge(gestures);
4154 ge.t = gestureEvent->t;
4155 ge.spont = gestureEvent->spont;
4156 ge.m_accept = wasAccepted;
4157 ge.d_func()->accepted = gestureEvent->d_func()->accepted;
4158 res = d->notify_helper(w, &ge);
4159 gestureEvent->spont = false;
4160 eventAccepted = ge.isAccepted();
4161 for (int i = 0; i < gestures.size(); ++i) {
4162 QGesture *g = gestures.at(i);
4163 // Ignore res [event return value] because handling of multiple gestures
4164 // packed into a single QEvent depends on not consuming the event
4165 if (eventAccepted || ge.isAccepted(g)) {
4166 // if the gesture was accepted, mark the target widget for it
4167 gestureEvent->d_func()->targetWidgets[g->gestureType()] = w;
4168 gestureEvent->setAccepted(g, true);
4170 // if the gesture was explicitly ignored by the application,
4171 // put it back so a parent can get it
4172 allGestures.append(g);
4176 if (allGestures.isEmpty()) // everything delivered
4180 w = w->parentWidget();
4182 foreach (QGesture *g, allGestures)
4183 gestureEvent->setAccepted(g, false);
4184 gestureEvent->m_accept = false; // to make sure we check individual gestures
4186 res = d->notify_helper(receiver, e);
4190 #endif // QT_NO_GESTURES
4191 #ifdef QT_MAC_USE_COCOA
4193 if (receiver->isWidgetType()) {
4194 QWidget *w = static_cast<QWidget *>(receiver);
4195 if (w->testAttribute(Qt::WA_AcceptTouchEvents))
4196 qt_widget_private(w)->registerTouchWindow(true);
4198 res = d->notify_helper(receiver, e);
4201 if (receiver->isWidgetType()) {
4202 QWidget *w = static_cast<QWidget *>(receiver);
4203 if (w->testAttribute(Qt::WA_AcceptTouchEvents))
4204 qt_widget_private(w)->registerTouchWindow(false);
4206 res = d->notify_helper(receiver, e);
4210 res = d->notify_helper(receiver, e);
4217 bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
4219 // send to all application event filters
4220 if (sendThroughApplicationEventFilters(receiver, e))
4223 if (receiver->isWidgetType()) {
4224 QWidget *widget = static_cast<QWidget *>(receiver);
4226 #if !defined(Q_WS_WINCE) || (defined(GWES_ICONCURS) && !defined(QT_NO_CURSOR))
4227 // toggle HasMouse widget state on enter and leave
4228 if ((e->type() == QEvent::Enter || e->type() == QEvent::DragEnter) &&
4229 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == widget->window()))
4230 widget->setAttribute(Qt::WA_UnderMouse, true);
4231 else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave)
4232 widget->setAttribute(Qt::WA_UnderMouse, false);
4235 if (QLayout *layout=widget->d_func()->layout) {
4236 layout->widgetEvent(e);
4240 // send to all receiver event filters
4241 if (sendThroughObjectEventFilters(receiver, e))
4244 // deliver the event
4245 bool consumed = receiver->event(e);
4252 \class QSessionManager
4253 \brief The QSessionManager class provides access to the session manager.
4255 A session manager in a desktop environment (in which Qt GUI applications
4256 live) keeps track of a session, which is a group of running applications,
4257 each of which has a particular state. The state of an application contains
4258 (most notably) the documents the application has open and the position and
4259 size of its windows.
4261 The session manager is used to save the session, e.g., when the machine is
4262 shut down, and to restore a session, e.g., when the machine is started up.
4263 We recommend that you use QSettings to save an application's settings,
4264 for example, window positions, recently used files, etc. When the
4265 application is restarted by the session manager, you can restore the
4268 QSessionManager provides an interface between the application and the
4269 session manager so that the program can work well with the session manager.
4270 In Qt, session management requests for action are handled by the two
4271 virtual functions QApplication::commitData() and QApplication::saveState().
4272 Both provide a reference to a session manager object as argument, to allow
4273 the application to communicate with the session manager. The session
4274 manager can only be accessed through these functions.
4276 No user interaction is possible \e unless the application gets explicit
4277 permission from the session manager. You ask for permission by calling
4278 allowsInteraction() or, if it is really urgent, allowsErrorInteraction().
4279 Qt does not enforce this, but the session manager may.
4281 You can try to abort the shutdown process by calling cancel(). The default
4282 commitData() function does this if some top-level window rejected its
4285 For sophisticated session managers provided on Unix/X11, QSessionManager
4286 offers further possibilities to fine-tune an application's session
4287 management behavior: setRestartCommand(), setDiscardCommand(),
4288 setRestartHint(), setProperty(), requestPhase2(). See the respective
4289 function descriptions for further details.
4291 \sa QApplication, {Session Management}
4294 /*! \enum QSessionManager::RestartHint
4296 This enum type defines the circumstances under which this application wants
4297 to be restarted by the session manager. The current values are:
4299 \value RestartIfRunning If the application is still running when the
4300 session is shut down, it wants to be restarted
4301 at the start of the next session.
4303 \value RestartAnyway The application wants to be started at the
4304 start of the next session, no matter what.
4305 (This is useful for utilities that run just
4306 after startup and then quit.)
4308 \value RestartImmediately The application wants to be started immediately
4309 whenever it is not running.
4311 \value RestartNever The application does not want to be restarted
4314 The default hint is \c RestartIfRunning.
4319 \fn QString QSessionManager::sessionId() const
4321 Returns the identifier of the current session.
4323 If the application has been restored from an earlier session, this
4324 identifier is the same as it was in the earlier session.
4326 \sa sessionKey(), QApplication::sessionId()
4330 \fn QString QSessionManager::sessionKey() const
4332 Returns the session key in the current session.
4334 If the application has been restored from an earlier session, this key is
4335 the same as it was when the previous session ended.
4337 The session key changes with every call of commitData() or saveState().
4339 \sa sessionId(), QApplication::sessionKey()
4343 \fn void* QSessionManager::handle() const
4349 \fn bool QSessionManager::allowsInteraction()
4351 Asks the session manager for permission to interact with the user. Returns
4352 true if interaction is permitted; otherwise returns false.
4354 The rationale behind this mechanism is to make it possible to synchronize
4355 user interaction during a shutdown. Advanced session managers may ask all
4356 applications simultaneously to commit their data, resulting in a much
4359 When the interaction is completed we strongly recommend releasing the user
4360 interaction semaphore with a call to release(). This way, other
4361 applications may get the chance to interact with the user while your
4362 application is still busy saving data. (The semaphore is implicitly
4363 released when the application exits.)
4365 If the user decides to cancel the shutdown process during the interaction
4366 phase, you must tell the session manager that this has happened by calling
4369 Here's an example of how an application's QApplication::commitData() might
4372 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 8
4374 If an error occurred within the application while saving its data, you may
4375 want to try allowsErrorInteraction() instead.
4377 \sa QApplication::commitData(), release(), cancel()
4382 \fn bool QSessionManager::allowsErrorInteraction()
4384 Returns true if error interaction is permitted; otherwise returns false.
4386 This is similar to allowsInteraction(), but also enables the application to
4387 tell the user about any errors that occur. Session managers may give error
4388 interaction requests higher priority, which means that it is more likely
4389 that an error interaction is permitted. However, you are still not
4390 guaranteed that the session manager will allow interaction.
4392 \sa allowsInteraction(), release(), cancel()
4396 \fn void QSessionManager::release()
4398 Releases the session manager's interaction semaphore after an interaction
4401 \sa allowsInteraction(), allowsErrorInteraction()
4405 \fn void QSessionManager::cancel()
4407 Tells the session manager to cancel the shutdown process. Applications
4408 should not call this function without asking the user first.
4410 \sa allowsInteraction(), allowsErrorInteraction()
4414 \fn void QSessionManager::setRestartHint(RestartHint hint)
4416 Sets the application's restart hint to \a hint. On application startup, the
4417 hint is set to \c RestartIfRunning.
4419 \note These flags are only hints, a session manager may or may not respect
4422 We recommend setting the restart hint in QApplication::saveState() because
4423 most session managers perform a checkpoint shortly after an application's
4430 \fn QSessionManager::RestartHint QSessionManager::restartHint() const
4432 Returns the application's current restart hint. The default is
4433 \c RestartIfRunning.
4435 \sa setRestartHint()
4439 \fn void QSessionManager::setRestartCommand(const QStringList& command)
4441 If the session manager is capable of restoring sessions it will execute
4442 \a command in order to restore the application. The command defaults to
4444 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 9
4446 The \c -session option is mandatory; otherwise QApplication cannot tell
4447 whether it has been restored or what the current session identifier is.
4448 See QApplication::isSessionRestored() and QApplication::sessionId() for
4451 If your application is very simple, it may be possible to store the entire
4452 application state in additional command line options. This is usually a
4453 very bad idea because command lines are often limited to a few hundred
4454 bytes. Instead, use QSettings, temporary files, or a database for this
4455 purpose. By marking the data with the unique sessionId(), you will be able
4456 to restore the application in a future session.
4458 \sa restartCommand(), setDiscardCommand(), setRestartHint()
4462 \fn QStringList QSessionManager::restartCommand() const
4464 Returns the currently set restart command.
4466 To iterate over the list, you can use the \l foreach pseudo-keyword:
4468 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 10
4470 \sa setRestartCommand(), restartHint()
4474 \fn void QSessionManager::setDiscardCommand(const QStringList& list)
4476 Sets the discard command to the given \a list.
4478 \sa discardCommand(), setRestartCommand()
4483 \fn QStringList QSessionManager::discardCommand() const
4485 Returns the currently set discard command.
4487 To iterate over the list, you can use the \l foreach pseudo-keyword:
4489 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 11
4491 \sa setDiscardCommand(), restartCommand(), setRestartCommand()
4495 \fn void QSessionManager::setManagerProperty(const QString &name, const QString &value)
4498 Low-level write access to the application's identification and state
4499 records are kept in the session manager.
4501 The property called \a name has its value set to the string \a value.
4505 \fn void QSessionManager::setManagerProperty(const QString& name,
4506 const QStringList& value)
4508 Low-level write access to the application's identification and state record
4509 are kept in the session manager.
4511 The property called \a name has its value set to the string list \a value.
4515 \fn bool QSessionManager::isPhase2() const
4517 Returns true if the session manager is currently performing a second
4518 session management phase; otherwise returns false.
4524 \fn void QSessionManager::requestPhase2()
4526 Requests a second session management phase for the application. The
4527 application may then return immediately from the QApplication::commitData()
4528 or QApplication::saveState() function, and they will be called again once
4529 most or all other applications have finished their session management.
4531 The two phases are useful for applications such as the X11 window manager
4532 that need to store information about another application's windows and
4533 therefore have to wait until these applications have completed their
4534 respective session management tasks.
4536 \note If another application has requested a second phase it may get called
4537 before, simultaneously with, or after your application's second phase.
4542 /*****************************************************************************
4543 Stubbed session management support
4544 *****************************************************************************/
4545 #ifndef QT_NO_SESSIONMANAGER
4546 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_WS_QWS)
4548 #if defined(Q_OS_WINCE)
4549 HRESULT qt_CoCreateGuid(GUID* guid)
4551 // We will use the following information to create the GUID
4552 // 1. absolute path to application
4553 wchar_t tempFilename[MAX_PATH];
4554 if (!GetModuleFileName(0, tempFilename, MAX_PATH))
4556 unsigned int hash = qHash(QString::fromWCharArray(tempFilename));
4558 // 2. creation time of file
4559 QFileInfo info(QString::fromWCharArray(tempFilename));
4560 guid->Data2 = qHash(info.created().toTime_t());
4561 // 3. current system time
4562 guid->Data3 = qHash(QDateTime::currentDateTime().toTime_t());
4565 #if !defined(OLE32_MCOMGUID) || defined(QT_WINCE_FORCE_CREATE_GUID)
4566 #define CoCreateGuid qt_CoCreateGuid
4571 class QSessionManagerPrivate : public QObjectPrivate
4574 QStringList restartCommand;
4575 QStringList discardCommand;
4578 QSessionManager::RestartHint restartHint;
4581 QSessionManager* qt_session_manager_self = 0;
4582 QSessionManager::QSessionManager(QApplication * app, QString &id, QString &key)
4583 : QObject(*new QSessionManagerPrivate, app)
4585 Q_D(QSessionManager);
4586 setObjectName(QLatin1String("qt_sessionmanager"));
4587 qt_session_manager_self = this;
4588 #if defined(Q_WS_WIN)
4589 wchar_t guidstr[40];
4591 CoCreateGuid(&guid);
4592 StringFromGUID2(guid, guidstr, 40);
4593 id = QString::fromWCharArray(guidstr);
4594 CoCreateGuid(&guid);
4595 StringFromGUID2(guid, guidstr, 40);
4596 key = QString::fromWCharArray(guidstr);
4599 d->sessionKey = key;
4600 d->restartHint = RestartIfRunning;
4603 QSessionManager::~QSessionManager()
4605 qt_session_manager_self = 0;
4608 QString QSessionManager::sessionId() const
4610 Q_D(const QSessionManager);
4611 return d->sessionId;
4614 QString QSessionManager::sessionKey() const
4616 Q_D(const QSessionManager);
4617 return d->sessionKey;
4621 #if defined(Q_WS_X11) || defined(Q_WS_MAC)
4622 void* QSessionManager::handle() const
4628 #if !defined(Q_WS_WIN)
4629 bool QSessionManager::allowsInteraction()
4634 bool QSessionManager::allowsErrorInteraction()
4638 void QSessionManager::release()
4642 void QSessionManager::cancel()
4648 void QSessionManager::setRestartHint(QSessionManager::RestartHint hint)
4650 Q_D(QSessionManager);
4651 d->restartHint = hint;
4654 QSessionManager::RestartHint QSessionManager::restartHint() const
4656 Q_D(const QSessionManager);
4657 return d->restartHint;
4660 void QSessionManager::setRestartCommand(const QStringList& command)
4662 Q_D(QSessionManager);
4663 d->restartCommand = command;
4666 QStringList QSessionManager::restartCommand() const
4668 Q_D(const QSessionManager);
4669 return d->restartCommand;
4672 void QSessionManager::setDiscardCommand(const QStringList& command)
4674 Q_D(QSessionManager);
4675 d->discardCommand = command;
4678 QStringList QSessionManager::discardCommand() const
4680 Q_D(const QSessionManager);
4681 return d->discardCommand;
4684 void QSessionManager::setManagerProperty(const QString&, const QString&)
4688 void QSessionManager::setManagerProperty(const QString&, const QStringList&)
4692 bool QSessionManager::isPhase2() const
4697 void QSessionManager::requestPhase2()
4702 #endif // QT_NO_SESSIONMANAGER
4705 \typedef QApplication::ColorMode
4708 Use ColorSpec instead.
4712 \fn Qt::MacintoshVersion QApplication::macVersion()
4714 Use QSysInfo::MacintoshVersion instead.
4718 \fn QApplication::ColorMode QApplication::colorMode()
4720 Use colorSpec() instead, and use ColorSpec as the enum type.
4724 \fn void QApplication::setColorMode(ColorMode mode)
4726 Use setColorSpec() instead, and pass a ColorSpec value instead.
4730 \fn bool QApplication::hasGlobalMouseTracking()
4732 This feature does not exist anymore. This function always returns true
4737 \fn void QApplication::setGlobalMouseTracking(bool dummy)
4739 This function does nothing in Qt 4. The \a dummy parameter is ignored.
4743 \fn void QApplication::flushX()
4745 Use flush() instead.
4749 \fn void QApplication::setWinStyleHighlightColor(const QColor &c)
4751 Use the palette instead.
4754 app.setWinStyleHighlightColor(color);
4756 QPalette palette(QApplication::palette());
4757 palette.setColor(QPalette::Highlight, color);
4758 QApplication::setPalette(palette);
4763 \fn void QApplication::setPalette(const QPalette &pal, bool b, const char* className = 0)
4765 Use the two-argument overload instead.
4769 \fn void QApplication::setFont(const QFont &font, bool b, const char* className = 0)
4771 Use the two-argument overload instead.
4775 \fn const QColor &QApplication::winStyleHighlightColor()
4777 Use QApplication::palette().color(QPalette::Active, QPalette::Highlight) instead.
4781 \fn QWidget *QApplication::widgetAt(int x, int y, bool child)
4783 Use the two-argument widgetAt() overload to get the child widget. To get
4784 the top-level widget do this:
4786 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 12
4790 \fn QWidget *QApplication::widgetAt(const QPoint &point, bool child)
4792 Use the single-argument widgetAt() overload to get the child widget. To get
4793 the top-level widget do this:
4795 \snippet doc/src/snippets/code/src_gui_kernel_qapplication.cpp 13
4799 QWidget *QApplication::mainWidget()
4801 return QApplicationPrivate::main_widget;
4804 bool QApplicationPrivate::inPopupMode() const
4806 return QApplicationPrivate::popupWidgets != 0;
4810 \property QApplication::quitOnLastWindowClosed
4812 \brief whether the application implicitly quits when the last window is
4815 The default is true.
4817 If this property is true, the applications quits when the last visible
4818 primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose
4819 attribute set is closed. By default this attribute is set for all widgets
4820 except for sub-windows. Refer to \l{Qt::WindowType} for a detailed list of
4823 \sa quit(), QWidget::close()
4826 void QApplication::setQuitOnLastWindowClosed(bool quit)
4828 QApplicationPrivate::quitOnLastWindowClosed = quit;
4831 bool QApplication::quitOnLastWindowClosed()
4833 return QApplicationPrivate::quitOnLastWindowClosed;
4836 void QApplicationPrivate::emitLastWindowClosed()
4838 if (qApp && qApp->d_func()->in_exec) {
4839 if (QApplicationPrivate::quitOnLastWindowClosed) {
4840 // get ready to quit, this event might be removed if the
4841 // event loop is re-entered, however
4842 QApplication::postEvent(qApp, new QEvent(QEvent::Quit));
4844 emit qApp->lastWindowClosed();
4848 /*! \variable QApplication::NormalColors
4851 Use \l NormalColor instead.
4854 /*! \variable QApplication::CustomColors
4857 Use \l CustomColor instead.
4860 #ifdef QT_KEYPAD_NAVIGATION
4862 Sets the kind of focus navigation Qt should use to \a mode.
4864 This feature is available in Qt for Embedded Linux, Symbian and Windows CE
4867 \note On Windows CE this feature is disabled by default for touch device
4868 mkspecs. To enable keypad navigation, build Qt with
4869 QT_KEYPAD_NAVIGATION defined.
4871 \note On Symbian, setting the mode to Qt::NavigationModeCursorAuto will enable a
4872 virtual mouse cursor on non touchscreen devices, which is controlled
4873 by the cursor keys if there is no analog pointer device.
4874 On other platforms and on touchscreen devices, it has the same
4875 meaning as Qt::NavigationModeNone.
4879 \sa keypadNavigationEnabled()
4881 void QApplication::setNavigationMode(Qt::NavigationMode mode)
4884 QApplicationPrivate::setNavigationMode(mode);
4886 QApplicationPrivate::navigationMode = mode;
4891 Returns what kind of focus navigation Qt is using.
4893 This feature is available in Qt for Embedded Linux, Symbian and Windows CE
4896 \note On Windows CE this feature is disabled by default for touch device
4897 mkspecs. To enable keypad navigation, build Qt with
4898 QT_KEYPAD_NAVIGATION defined.
4900 \note On Symbian, the default mode is Qt::NavigationModeNone for touch
4901 devices, and Qt::NavigationModeKeypadDirectional.
4905 \sa keypadNavigationEnabled()
4907 Qt::NavigationMode QApplication::navigationMode()
4909 return QApplicationPrivate::navigationMode;
4913 Sets whether Qt should use focus navigation suitable for use with a
4916 This feature is available in Qt for Embedded Linux, Symbian and Windows CE
4919 \note On Windows CE this feature is disabled by default for touch device
4920 mkspecs. To enable keypad navigation, build Qt with
4921 QT_KEYPAD_NAVIGATION defined.
4925 \sa setNavigationMode()
4927 void QApplication::setKeypadNavigationEnabled(bool enable)
4931 QApplication::setNavigationMode(Qt::NavigationModeKeypadDirectional);
4933 QApplication::setNavigationMode(Qt::NavigationModeKeypadTabOrder);
4937 QApplication::setNavigationMode(Qt::NavigationModeNone);
4942 Returns true if Qt is set to use keypad navigation; otherwise returns
4943 false. The default value is true on Symbian, but false on other platforms.
4945 This feature is available in Qt for Embedded Linux, Symbian and Windows CE
4948 \note On Windows CE this feature is disabled by default for touch device
4949 mkspecs. To enable keypad navigation, build Qt with
4950 QT_KEYPAD_NAVIGATION defined.
4954 \sa navigationMode()
4956 bool QApplication::keypadNavigationEnabled()
4958 return QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadTabOrder ||
4959 QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadDirectional;
4964 \fn void QApplication::alert(QWidget *widget, int msec)
4967 Causes an alert to be shown for \a widget if the window is not the active
4968 window. The alert is shown for \a msec miliseconds. If \a msec is zero (the
4969 default), then the alert is shown indefinitely until the window becomes
4972 Currently this function does nothing on Qt for Embedded Linux.
4974 On Mac OS X, this works more at the application level and will cause the
4975 application icon to bounce in the dock.
4977 On Windows, this causes the window's taskbar entry to flash for a time. If
4978 \a msec is zero, the flashing will stop and the taskbar entry will turn a
4979 different color (currently orange).
4981 On X11, this will cause the window to be marked as "demands attention", the
4982 window must not be hidden (i.e. not have hide() called on it, but be
4983 visible in some sort of way) in order for this to work.
4987 \property QApplication::cursorFlashTime
4988 \brief the text cursor's flash (blink) time in milliseconds
4990 The flash time is the time required to display, invert and restore the
4991 caret display. Usually the text cursor is displayed for half the cursor
4992 flash time, then hidden for the same amount of time, but this may vary.
4994 The default value on X11 is 1000 milliseconds. On Windows, the
4995 \gui{Control Panel} value is used and setting this property sets the cursor
4996 flash time for all applications.
4998 We recommend that widgets do not cache this value as it may change at any
4999 time if the user changes the global desktop settings.
5001 void QApplication::setCursorFlashTime(int msecs)
5006 int QApplication::cursorFlashTime()
5008 return qApp->styleHints()->cursorFlashTime();
5013 \property QApplication::doubleClickInterval
5014 \brief the time limit in milliseconds that distinguishes a double click
5015 from two consecutive mouse clicks
5017 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
5018 operating system's value is used.
5020 Setting the interval is not supported anymore in Qt 5.
5022 void QApplication::setDoubleClickInterval(int ms)
5027 int QApplication::doubleClickInterval()
5029 return qApp->styleHints()->mouseDoubleClickInterval();
5033 \property QApplication::keyboardInputInterval
5034 \brief the time limit in milliseconds that distinguishes a key press
5035 from two consecutive key presses
5038 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
5039 operating system's value is used.
5041 void QApplication::setKeyboardInputInterval(int ms)
5046 int QApplication::keyboardInputInterval()
5048 return qApp->styleHints()->keyboardInputInterval();
5052 \property QApplication::wheelScrollLines
5053 \brief the number of lines to scroll a widget, when the
5054 mouse wheel is rotated.
5056 If the value exceeds the widget's number of visible lines, the widget
5057 should interpret the scroll operation as a single \e{page up} or
5058 \e{page down}. If the widget is an \l{QAbstractItemView}{item view class},
5059 then the result of scrolling one \e line depends on the setting of the
5060 widget's \l{QAbstractItemView::verticalScrollMode()}{scroll mode}. Scroll
5061 one \e line can mean \l{QAbstractItemView::ScrollPerItem}{scroll one item}
5062 or \l{QAbstractItemView::ScrollPerPixel}{scroll one pixel}.
5064 By default, this property has a value of 3.
5068 \fn void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
5070 Enables the UI effect \a effect if \a enable is true, otherwise the effect
5073 \note All effects are disabled on screens running at less than 16-bit color
5076 \sa isEffectEnabled(), Qt::UIEffect, setDesktopSettingsAware()
5080 \fn bool QApplication::isEffectEnabled(Qt::UIEffect effect)
5082 Returns true if \a effect is enabled; otherwise returns false.
5084 By default, Qt will try to use the desktop settings. To prevent this, call
5085 setDesktopSettingsAware(false).
5087 \note All effects are disabled on screens running at less than 16-bit color
5090 \sa setEffectEnabled(), Qt::UIEffect
5094 \fn QWidget *QApplication::mainWidget()
5096 Returns the main application widget, or 0 if there is no main widget.
5100 \fn void QApplication::setMainWidget(QWidget *mainWidget)
5102 Sets the application's main widget to \a mainWidget.
5104 In most respects the main widget is like any other widget, except that if
5105 it is closed, the application exits. QApplication does \e not take
5106 ownership of the \a mainWidget, so if you create your main widget on the
5107 heap you must delete it yourself.
5109 You need not have a main widget; connecting lastWindowClosed() to quit()
5112 On X11, this function also resizes and moves the main widget according
5113 to the \e -geometry command-line option, so you should set the default
5114 geometry (using \l QWidget::setGeometry()) before calling setMainWidget().
5116 \sa mainWidget(), exec(), quit()
5120 \fn void QApplication::beep()
5122 Sounds the bell, using the default volume and sound. The function is \e not
5123 available in Qt for Embedded Linux.
5127 \fn void QApplication::setOverrideCursor(const QCursor &cursor)
5129 Sets the application override cursor to \a cursor.
5131 Application override cursors are intended for showing the user that the
5132 application is in a special state, for example during an operation that
5133 might take some time.
5135 This cursor will be displayed in all the application's widgets until
5136 restoreOverrideCursor() or another setOverrideCursor() is called.
5138 Application cursors are stored on an internal stack. setOverrideCursor()
5139 pushes the cursor onto the stack, and restoreOverrideCursor() pops the
5140 active cursor off the stack. changeOverrideCursor() changes the curently
5141 active application override cursor.
5143 Every setOverrideCursor() must eventually be followed by a corresponding
5144 restoreOverrideCursor(), otherwise the stack will never be emptied.
5147 \snippet doc/src/snippets/code/src_gui_kernel_qapplication_x11.cpp 0
5149 \sa overrideCursor(), restoreOverrideCursor(), changeOverrideCursor(),
5150 QWidget::setCursor()
5154 \fn void QApplication::restoreOverrideCursor()
5156 Undoes the last setOverrideCursor().
5158 If setOverrideCursor() has been called twice, calling
5159 restoreOverrideCursor() will activate the first cursor set. Calling this
5160 function a second time restores the original widgets' cursors.
5162 \sa setOverrideCursor(), overrideCursor()
5167 \relates QApplication
5169 A global pointer referring to the unique application object. It is
5170 equivalent to the pointer returned by the QCoreApplication::instance()
5171 function except that, in GUI applications, it is a pointer to a
5172 QApplication instance.
5174 Only one application object can be created.
5176 \sa QCoreApplication::instance()
5180 // ************************************************************************
5181 // Input Method support
5182 // ************************************************************************
5185 This function replaces the QInputContext instance used by the application
5186 with \a inputContext.
5188 Qt takes ownership of the given \a inputContext.
5192 void QApplication::setInputContext(QInputContext *inputContext)
5194 if (inputContext == QApplicationPrivate::inputContext)
5196 if (!inputContext) {
5197 qWarning("QApplication::setInputContext: called with 0 input context");
5200 delete QApplicationPrivate::inputContext;
5201 QApplicationPrivate::inputContext = inputContext;
5202 QApplicationPrivate::inputContext->setParent(this);
5206 Returns the QInputContext instance used by the application.
5208 \sa setInputContext()
5210 QInputContext *QApplication::inputContext() const
5212 return QApplicationPrivate::inputContext;
5216 bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
5218 return QApplicationBase::sendSpontaneousEvent(receiver, event);
5222 void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget,
5223 Qt::FocusPolicy focusPolicy,
5224 Qt::FocusReason focusReason)
5226 QWidget *focusWidget = widget;
5227 while (focusWidget) {
5228 if (focusWidget->isEnabled()
5229 && QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) {
5230 focusWidget->setFocus(focusReason);
5233 if (focusWidget->isWindow())
5235 focusWidget = focusWidget->parentWidget();
5239 bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy)
5242 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5243 f = f->d_func()->extra->focus_proxy;
5245 if ((w->focusPolicy() & policy) != policy)
5247 if (w != f && (f->focusPolicy() & policy) != policy)
5252 /*! \fn QDecoration &QApplication::qwsDecoration()
5253 Return the QWSDecoration used for decorating windows.
5255 \warning This method is non-portable. It is only available in
5256 Qt for Embedded Linux.
5262 \fn void QApplication::qwsSetDecoration(QDecoration *decoration)
5264 Sets the QDecoration derived class to use for decorating the
5265 windows used by Qt for Embedded Linux to the \a decoration
5268 This method is non-portable. It is only available in Qt for Embedded Linux.
5273 /*! \fn QDecoration* QApplication::qwsSetDecoration(const QString &decoration)
5276 Requests a QDecoration object for \a decoration from the
5279 The string must be one of the QDecorationFactory::keys(). Keys are case
5282 A later call to the QApplication constructor will override the requested
5283 style when a "-style" option is passed in as a commandline parameter.
5285 Returns 0 if an unknown \a decoration is passed, otherwise the QStyle object
5286 returned is set as the application's GUI style.
5290 \fn bool QApplication::qwsEventFilter(QWSEvent *event)
5292 This virtual function is only implemented under Qt for Embedded Linux.
5294 If you create an application that inherits QApplication and
5295 reimplement this function, you get direct access to all QWS (Q
5296 Window System) events that the are received from the QWS master
5297 process. The events are passed in the \a event parameter.
5299 Return true if you want to stop the event from being processed.
5300 Return false for normal event dispatching. The default
5301 implementation returns false.
5304 /*! \fn void QApplication::qwsSetCustomColors(QRgb *colorTable, int start, int numColors)
5305 Set Qt for Embedded Linux custom color table.
5307 Qt for Embedded Linux on 8-bpp displays allocates a standard 216 color cube.
5308 The remaining 40 colors may be used by setting a custom color
5309 table in the QWS master process before any clients connect.
5311 \a colorTable is an array of up to 40 custom colors. \a start is
5312 the starting index (0-39) and \a numColors is the number of colors
5315 This method is non-portable. It is available \e only in
5316 Qt for Embedded Linux.
5318 \note The custom colors will not be used by the default screen
5319 driver. To make use of the new colors, implement a custom screen
5320 driver, or use QDirectPainter.
5323 /*! \fn int QApplication::qwsProcessEvent(QWSEvent* event)
5327 /*! \fn int QApplication::x11ClientMessage(QWidget* w, XEvent* event, bool passive_only)
5331 /*! \fn int QApplication::x11ProcessEvent(XEvent* event)
5332 This function does the core processing of individual X
5333 \a{event}s, normally by dispatching Qt events to the right
5336 It returns 1 if the event was consumed by special handling, 0 if
5337 the \a event was consumed by normal handling, and -1 if the \a
5338 event was for an unrecognized widget.
5340 \sa x11EventFilter()
5344 \fn bool QApplication::x11EventFilter(XEvent *event)
5346 \warning This virtual function is only implemented under X11.
5348 If you create an application that inherits QApplication and
5349 reimplement this function, you get direct access to all X events
5350 that the are received from the X server. The events are passed in
5351 the \a event parameter.
5353 Return true if you want to stop the event from being processed.
5354 Return false for normal event dispatching. The default
5355 implementation returns false.
5357 It is only the directly addressed messages that are filtered.
5358 You must install an event filter directly on the event
5359 dispatcher, which is returned by
5360 QAbstractEventDispatcher::instance(), to handle system wide
5363 \sa x11ProcessEvent()
5366 /*! \fn void QApplication::winFocus(QWidget *widget, bool gotFocus)
5370 If \a gotFocus is true, \a widget will become the active window.
5371 Otherwise the active window is reset to 0.
5374 /*! \fn void QApplication::winMouseButtonUp()
5378 /*! \fn void QApplication::syncX()
5379 Synchronizes with the X server in the X11 implementation.
5380 This normally takes some time. Does nothing on other platforms.
5383 void QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent)
5385 for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
5386 QTouchEvent::TouchPoint &touchPoint = touchEvent->_touchPoints[i];
5388 // preserve the sub-pixel resolution
5389 QRectF rect = touchPoint.screenRect();
5390 const QPointF screenPos = rect.center();
5391 const QPointF delta = screenPos - screenPos.toPoint();
5393 rect.moveCenter(widget->mapFromGlobal(screenPos.toPoint()) + delta);
5394 touchPoint.d->rect = rect;
5395 if (touchPoint.state() == Qt::TouchPointPressed) {
5396 touchPoint.d->startPos = widget->mapFromGlobal(touchPoint.startScreenPos().toPoint()) + delta;
5397 touchPoint.d->lastPos = widget->mapFromGlobal(touchPoint.lastScreenPos().toPoint()) + delta;
5402 void QApplicationPrivate::initializeMultitouch()
5404 widgetForTouchPointId.clear();
5405 appCurrentTouchPoints.clear();
5407 initializeMultitouch_sys();
5410 void QApplicationPrivate::cleanupMultitouch()
5412 cleanupMultitouch_sys();
5414 widgetForTouchPointId.clear();
5415 appCurrentTouchPoints.clear();
5418 int QApplicationPrivate::findClosestTouchPointId(const QPointF &screenPos)
5420 int closestTouchPointId = -1;
5421 qreal closestDistance = qreal(0.);
5422 foreach (const QTouchEvent::TouchPoint &touchPoint, appCurrentTouchPoints) {
5423 qreal distance = QLineF(screenPos, touchPoint.screenPos()).length();
5424 if (closestTouchPointId == -1 || distance < closestDistance) {
5425 closestTouchPointId = touchPoint.id();
5426 closestDistance = distance;
5429 return closestTouchPointId;
5432 void QApplicationPrivate::translateRawTouchEvent(QWidget *window,
5433 QTouchEvent::DeviceType deviceType,
5434 const QList<QTouchEvent::TouchPoint> &touchPoints)
5436 QApplicationPrivate *d = self;
5437 typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
5438 QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents;
5440 for (int i = 0; i < touchPoints.count(); ++i) {
5441 QTouchEvent::TouchPoint touchPoint = touchPoints.at(i);
5442 // explicitly detach from the original touch point that we got, so even
5443 // if the touchpoint structs are reused, we will make a copy that we'll
5444 // deliver to the user (which might want to store the struct for later use).
5445 touchPoint.d = touchPoint.d->detach();
5448 QWeakPointer<QWidget> widget;
5449 switch (touchPoint.state()) {
5450 case Qt::TouchPointPressed:
5452 if (deviceType == QTouchEvent::TouchPad) {
5453 // on touch-pads, send all touch points to the same widget
5454 widget = d->widgetForTouchPointId.isEmpty()
5455 ? QWeakPointer<QWidget>()
5456 : d->widgetForTouchPointId.constBegin().value();
5460 // determine which widget this event will go to
5462 window = QApplication::topLevelAt(touchPoint.screenPos().toPoint());
5465 widget = window->childAt(window->mapFromGlobal(touchPoint.screenPos().toPoint()));
5470 if (deviceType == QTouchEvent::TouchScreen) {
5471 int closestTouchPointId = d->findClosestTouchPointId(touchPoint.screenPos());
5472 QWidget *closestWidget = d->widgetForTouchPointId.value(closestTouchPointId).data();
5474 && (widget.data()->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget.data()))) {
5475 widget = closestWidget;
5479 d->widgetForTouchPointId[touchPoint.id()] = widget;
5480 touchPoint.d->startScreenPos = touchPoint.screenPos();
5481 touchPoint.d->lastScreenPos = touchPoint.screenPos();
5482 touchPoint.d->startNormalizedPos = touchPoint.normalizedPos();
5483 touchPoint.d->lastNormalizedPos = touchPoint.normalizedPos();
5484 if (touchPoint.pressure() < qreal(0.))
5485 touchPoint.d->pressure = qreal(1.);
5487 d->appCurrentTouchPoints.insert(touchPoint.id(), touchPoint);
5490 case Qt::TouchPointReleased:
5492 widget = d->widgetForTouchPointId.take(touchPoint.id());
5496 QTouchEvent::TouchPoint previousTouchPoint = d->appCurrentTouchPoints.take(touchPoint.id());
5497 touchPoint.d->startScreenPos = previousTouchPoint.startScreenPos();
5498 touchPoint.d->lastScreenPos = previousTouchPoint.screenPos();
5499 touchPoint.d->startPos = previousTouchPoint.startPos();
5500 touchPoint.d->lastPos = previousTouchPoint.pos();
5501 touchPoint.d->startNormalizedPos = previousTouchPoint.startNormalizedPos();
5502 touchPoint.d->lastNormalizedPos = previousTouchPoint.normalizedPos();
5503 if (touchPoint.pressure() < qreal(0.))
5504 touchPoint.d->pressure = qreal(0.);
5508 widget = d->widgetForTouchPointId.value(touchPoint.id());
5512 Q_ASSERT(d->appCurrentTouchPoints.contains(touchPoint.id()));
5513 QTouchEvent::TouchPoint previousTouchPoint = d->appCurrentTouchPoints.value(touchPoint.id());
5514 touchPoint.d->startScreenPos = previousTouchPoint.startScreenPos();
5515 touchPoint.d->lastScreenPos = previousTouchPoint.screenPos();
5516 touchPoint.d->startPos = previousTouchPoint.startPos();
5517 touchPoint.d->lastPos = previousTouchPoint.pos();
5518 touchPoint.d->startNormalizedPos = previousTouchPoint.startNormalizedPos();
5519 touchPoint.d->lastNormalizedPos = previousTouchPoint.normalizedPos();
5520 if (touchPoint.pressure() < qreal(0.))
5521 touchPoint.d->pressure = qreal(1.);
5522 d->appCurrentTouchPoints[touchPoint.id()] = touchPoint;
5525 Q_ASSERT(widget.data() != 0);
5527 // make the *scene* functions return the same as the *screen* functions
5528 touchPoint.d->sceneRect = touchPoint.screenRect();
5529 touchPoint.d->startScenePos = touchPoint.startScreenPos();
5530 touchPoint.d->lastScenePos = touchPoint.lastScreenPos();
5532 StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[widget.data()];
5533 maskAndPoints.first |= touchPoint.state();
5534 if (touchPoint.isPrimary())
5535 maskAndPoints.first |= Qt::TouchPointPrimary;
5536 maskAndPoints.second.append(touchPoint);
5539 if (widgetsNeedingEvents.isEmpty())
5542 QHash<QWidget *, StatesAndTouchPoints>::ConstIterator it = widgetsNeedingEvents.constBegin();
5543 const QHash<QWidget *, StatesAndTouchPoints>::ConstIterator end = widgetsNeedingEvents.constEnd();
5544 for (; it != end; ++it) {
5545 QWidget *widget = it.key();
5546 if (!QApplicationPrivate::tryModalHelper(widget, 0))
5549 QEvent::Type eventType;
5550 switch (it.value().first & Qt::TouchPointStateMask) {
5551 case Qt::TouchPointPressed:
5552 eventType = QEvent::TouchBegin;
5554 case Qt::TouchPointReleased:
5555 eventType = QEvent::TouchEnd;
5557 case Qt::TouchPointStationary:
5558 // don't send the event if nothing changed
5561 eventType = QEvent::TouchUpdate;
5565 QTouchEvent touchEvent(eventType,
5567 QApplication::keyboardModifiers(),
5570 updateTouchPointsForWidget(widget, &touchEvent);
5572 switch (touchEvent.type()) {
5573 case QEvent::TouchBegin:
5575 // if the TouchBegin handler recurses, we assume that means the event
5576 // has been implicitly accepted and continue to send touch events
5577 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
5578 (void ) QApplication::sendSpontaneousEvent(widget, &touchEvent);
5582 if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent)) {
5583 if (touchEvent.type() == QEvent::TouchEnd)
5584 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, false);
5585 (void) QApplication::sendSpontaneousEvent(widget, &touchEvent);
5592 Q_WIDGETS_EXPORT void qt_translateRawTouchEvent(QWidget *window,
5593 QTouchEvent::DeviceType deviceType,
5594 const QList<QTouchEvent::TouchPoint> &touchPoints)
5596 QApplicationPrivate::translateRawTouchEvent(window, deviceType, touchPoints);
5599 #ifndef QT_NO_GESTURES
5600 QGestureManager* QGestureManager::instance()
5602 QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
5605 if (!qAppPriv->gestureManager)
5606 qAppPriv->gestureManager = new QGestureManager(qApp);
5607 return qAppPriv->gestureManager;
5609 #endif // QT_NO_GESTURES
5613 #include "moc_qapplication.cpp"