1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
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 "qstyleoption.h"
60 #include "qstylefactory.h"
61 #include "qtextcodec.h"
62 #include "qtranslator.h"
65 #include "private/qdnd_p.h"
66 #include "private/qguiapplication_p.h"
67 #include "qcolormap.h"
69 #include "private/qstylesheetstyle_p.h"
70 #include "private/qstyle_p.h"
71 #include "qmessagebox.h"
72 #include "qwidgetwindow_qpa_p.h"
73 #include <QtWidgets/qgraphicsproxywidget.h>
74 #include <QtGui/qstylehints.h>
75 #include <QtGui/qinputmethod.h>
76 #include <qpa/qplatformtheme.h>
78 #include "private/qkeymapper_p.h"
81 #include <private/qthread_p.h>
83 #include <private/qfont_p.h>
87 #include "qapplication_p.h"
88 #include "private/qevent_p.h"
89 #include "qwidget_p.h"
92 #include "private/qgesturemanager_p.h"
93 #include <qpa/qplatformfontdatabase.h>
98 #include "qdatetime.h"
101 extern bool qt_wince_is_smartphone(); //qguifunctions_wince.cpp
102 extern bool qt_wince_is_mobile(); //qguifunctions_wince.cpp
103 extern bool qt_wince_is_pocket_pc(); //qguifunctions_wince.cpp
106 #include <qpa/qplatformwindow.h>
108 //#define ALIEN_DEBUG
110 static void initResources()
112 #if defined(Q_OS_WINCE)
113 Q_INIT_RESOURCE_EXTERN(qstyle_wince)
114 Q_INIT_RESOURCE(qstyle_wince);
116 Q_INIT_RESOURCE_EXTERN(qstyle)
117 Q_INIT_RESOURCE(qstyle);
119 Q_INIT_RESOURCE_EXTERN(qmessagebox)
120 Q_INIT_RESOURCE(qmessagebox);
126 Q_CORE_EXPORT void qt_call_post_routines();
128 QApplicationPrivate *QApplicationPrivate::self = 0;
130 static void initSystemPalette()
132 if (!QApplicationPrivate::sys_pal) {
133 QPalette defaultPlatte;
134 if (QApplicationPrivate::app_style)
135 defaultPlatte = QApplicationPrivate::app_style->standardPalette();
136 if (const QPalette *themePalette = QGuiApplicationPrivate::platformTheme()->palette()) {
137 QApplicationPrivate::setSystemPalette(themePalette->resolve(defaultPlatte));
138 QApplicationPrivate::initializeWidgetPaletteHash();
140 QApplicationPrivate::setSystemPalette(defaultPlatte);
145 static void clearSystemPalette()
147 delete QApplicationPrivate::sys_pal;
148 QApplicationPrivate::sys_pal = 0;
152 int QApplicationPrivate::autoMaximizeThreshold = -1;
153 bool QApplicationPrivate::autoSipEnabled = false;
155 bool QApplicationPrivate::autoSipEnabled = true;
158 QApplicationPrivate::QApplicationPrivate(int &argc, char **argv, QApplication::Type type, int flags)
159 : QApplicationPrivateBase(argc, argv, flags)
161 application_type = type;
163 #ifndef QT_NO_SESSIONMANAGER
164 is_session_restored = false;
167 #ifndef QT_NO_GESTURES
170 #endif // QT_NO_GESTURES
176 QApplicationPrivate::~QApplicationPrivate()
184 \brief The QApplication class manages the GUI application's control
185 flow and main settings.
189 QApplication specializes QGuiApplication with some functionality needed
190 for QWidget-based applications. It handles widget specific initialization,
191 finalization, and provides session management.
193 For any GUI application using Qt, there is precisely \b one QApplication
194 object, no matter whether the application has 0, 1, 2 or more windows at
195 any given time. For non-QWidget based Qt applications, use QGuiApplication instead,
196 as it does not depend on the \l QtWidgets library.
198 The QApplication object is accessible through the instance() function that
199 returns a pointer equivalent to the global qApp pointer.
201 QApplication's main areas of responsibility are:
203 \li It initializes the application with the user's desktop settings
204 such as palette(), font() and doubleClickInterval(). It keeps
205 track of these properties in case the user changes the desktop
206 globally, for example through some kind of control panel.
208 \li It performs event handling, meaning that it receives events
209 from the underlying window system and dispatches them to the
210 relevant widgets. By using sendEvent() and postEvent() you can
211 send your own events to widgets.
213 \li It parses common command line arguments and sets its internal
214 state accordingly. See the \l{QApplication::QApplication()}
215 {constructor documentation} below for more details.
217 \li It defines the application's look and feel, which is
218 encapsulated in a QStyle object. This can be changed at runtime
221 \li It specifies how the application is to allocate colors. See
222 setColorSpec() for details.
224 \li It provides localization of strings that are visible to the
225 user via translate().
227 \li It provides some magical objects like the desktop() and the
230 \li It knows about the application's windows. You can ask which
231 widget is at a certain position using widgetAt(), get a list of
232 topLevelWidgets() and closeAllWindows(), etc.
234 \li It manages the application's mouse cursor handling, see
237 \li It provides support for sophisticated \l{Session Management}
238 {session management}. This makes it possible for applications
239 to terminate gracefully when the user logs out, to cancel a
240 shutdown process if termination isn't possible and even to
241 preserve the entire application's state for a future session.
242 See isSessionRestored(), sessionId() and commitData() and
243 saveState() for details.
246 Since the QApplication object does so much initialization, it \e{must} be
247 created before any other objects related to the user interface are created.
248 QApplication also deals with common command line arguments. Hence, it is
249 usually a good idea to create it \e before any interpretation or
250 modification of \c argv is done in the application itself.
254 \li{2,1} Groups of functions
258 \li desktopSettingsAware(),
259 setDesktopSettingsAware(),
261 setCursorFlashTime(),
262 doubleClickInterval(),
263 setDoubleClickInterval(),
264 setKeyboardInputInterval(),
266 setWheelScrollLines(),
282 removePostedEvents(),
298 \li installTranslator(),
315 \li Advanced cursor handling
316 \li overrideCursor(),
318 restoreOverrideCursor().
321 \li Session management
322 \li isSessionRestored(),
329 \li closeAllWindows(),
335 \sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
339 \enum QApplication::ColorSpec
341 \value NormalColor the default color allocation policy
342 \value CustomColor the same as NormalColor for X11; allocates colors
343 to a palette on demand under Windows
344 \value ManyColor the right choice for applications that use thousands of
347 See setColorSpec() for full details.
351 \fn QWidget *QApplication::topLevelAt(const QPoint &point)
353 Returns the top-level widget at the given \a point; returns 0 if
354 there is no such widget.
358 \fn QWidget *QApplication::topLevelAt(int x, int y)
362 Returns the top-level widget at the point (\a{x}, \a{y}); returns
363 0 if there is no such widget.
368 The qt_init() and qt_cleanup() functions are implemented in the
369 qapplication_xyz.cpp file.
372 void qt_init(QApplicationPrivate *priv, int type
376 QStyle *QApplicationPrivate::app_style = 0; // default application style
377 QString QApplicationPrivate::styleOverride; // style override
379 #ifndef QT_NO_STYLE_STYLESHEET
380 QString QApplicationPrivate::styleSheet; // default application stylesheet
382 QPointer<QWidget> QApplicationPrivate::leaveAfterRelease = 0;
384 int QApplicationPrivate::app_cspec = QApplication::NormalColor;
386 QPalette *QApplicationPrivate::sys_pal = 0; // default system palette
387 QPalette *QApplicationPrivate::set_pal = 0; // default palette set by programmer
389 QFont *QApplicationPrivate::sys_font = 0; // default system font
390 QFont *QApplicationPrivate::set_font = 0; // default font set by programmer
392 QIcon *QApplicationPrivate::app_icon = 0;
393 QWidget *QApplicationPrivate::main_widget = 0; // main application widget
394 QWidget *QApplicationPrivate::focus_widget = 0; // has keyboard input focus
395 QWidget *QApplicationPrivate::hidden_focus_widget = 0; // will get keyboard input focus after show()
396 QWidget *QApplicationPrivate::active_window = 0; // toplevel with keyboard focus
397 #ifndef QT_NO_WHEELEVENT
398 int QApplicationPrivate::wheel_scroll_lines; // number of lines to scroll
400 bool qt_in_tab_key_event = false;
401 int qt_antialiasing_threshold = -1;
402 QSize QApplicationPrivate::app_strut = QSize(0,0); // no default application strut
403 int QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
404 bool QApplicationPrivate::widgetCount = false;
405 bool QApplicationPrivate::load_testability = false;
406 #ifdef QT_KEYPAD_NAVIGATION
407 Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadTabOrder;
408 QWidget *QApplicationPrivate::oldEditFocus = 0;
411 bool qt_tabletChokeMouse = false;
413 inline bool QApplicationPrivate::isAlien(QWidget *widget)
415 return widget && !widget->isWindow();
418 bool Q_WIDGETS_EXPORT qt_tab_all_widgets()
420 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
421 return theme->themeHint(QPlatformTheme::TabAllWidgets).toBool();
425 // ######## move to QApplicationPrivate
426 // Default application palettes and fonts (per widget type)
427 Q_GLOBAL_STATIC(PaletteHash, app_palettes)
428 PaletteHash *qt_app_palettes_hash()
430 return app_palettes();
433 Q_GLOBAL_STATIC(FontHash, app_fonts)
434 FontHash *qt_app_fonts_hash()
439 QWidgetList *QApplicationPrivate::popupWidgets = 0; // has keyboard input focus
441 QDesktopWidget *qt_desktopWidget = 0; // root window widgets
446 void QApplicationPrivate::process_cmdline()
448 // process platform-indep command line
449 if (!qt_is_gui_used || !argc)
455 for (i=1; i<argc; i++) { // if you add anything here, modify QCoreApplication::arguments()
456 if (argv[i] && *argv[i] != '-') {
460 QByteArray arg = argv[i];
463 if (arg == "-qdevel" || arg == "-qdebug") {
465 } else if (arg.indexOf("-style=", 0) != -1) {
466 s = QString::fromLocal8Bit(arg.right(arg.length() - 7).toLower());
467 } else if (arg == "-style" && i < argc-1) {
468 s = QString::fromLocal8Bit(argv[++i]).toLower();
469 #ifndef QT_NO_SESSIONMANAGER
470 } else if (arg == "-session" && i < argc-1) {
472 if (argv[i] && *argv[i]) {
473 session_id = QString::fromLatin1(argv[i]);
474 int p = session_id.indexOf(QLatin1Char('_'));
476 session_key = session_id.mid(p +1);
477 session_id = session_id.left(p);
479 is_session_restored = true;
482 #ifndef QT_NO_STYLE_STYLESHEET
483 } else if (arg == "-stylesheet" && i < argc -1) {
484 styleSheet = QLatin1String("file:///");
485 styleSheet.append(QString::fromLocal8Bit(argv[++i]));
486 } else if (arg.indexOf("-stylesheet=") != -1) {
487 styleSheet = QLatin1String("file:///");
488 styleSheet.append(QString::fromLocal8Bit(arg.right(arg.length() - 12)));
490 } else if (qstrcmp(arg, "-widgetcount") == 0) {
492 } else if (qstrcmp(arg, "-testability") == 0) {
493 load_testability = true;
513 Initializes the window system and constructs an application object with
514 \a argc command line arguments in \a argv.
516 \warning The data referred to by \a argc and \a argv must stay valid for
517 the entire lifetime of the QApplication object. In addition, \a argc must
518 be greater than zero and \a argv must contain at least one valid character
521 The global \c qApp pointer refers to this application object. Only one
522 application object should be created.
524 This application object must be constructed before any \l{QPaintDevice}
525 {paint devices} (including widgets, pixmaps, bitmaps etc.).
527 \note \a argc and \a argv might be changed as Qt removes command line
528 arguments that it recognizes.
530 All Qt programs automatically support the following command line options:
532 \li -style= \e style, sets the application GUI style. Possible values
533 depend on your system configuration. If you compiled Qt with
534 additional styles or have additional styles as plugins these will
535 be available to the \c -style command line option.
536 \li -style \e style, is the same as listed above.
537 \li -stylesheet= \e stylesheet, sets the application \l styleSheet. The
538 value must be a path to a file that contains the Style Sheet.
539 \note Relative URLs in the Style Sheet file are relative to the
540 Style Sheet file's path.
541 \li -stylesheet \e stylesheet, is the same as listed above.
542 \li -session= \e session, restores the application from an earlier
543 \l{Session Management}{session}.
544 \li -session \e session, is the same as listed above.
545 \li -widgetcount, prints debug message at the end about number of
546 widgets left undestroyed and maximum number of widgets existed at
548 \li -reverse, sets the application's layout direction to
550 \li -qmljsdebugger=, activates the QML/JS debugger with a specified port.
551 The value must be of format port:1234[,block], where block is optional
552 and will make the application wait until a debugger connects to it.
559 QApplication::QApplication(int &argc, char **argv)
561 QApplication::QApplication(int &argc, char **argv, int _internal)
563 : QGuiApplication(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
564 { Q_D(QApplication); d->construct(); }
568 Constructs an application object with \a argc command line arguments in
571 \warning The data referred to by \a argc and \a argv must stay valid for
572 the entire lifetime of the QApplication object. In addition, \a argc must
573 be greater than zero and \a argv must contain at least one valid character
576 The following example shows how to create an application that uses a
577 graphical interface when available.
581 \snippet code/src_gui_kernel_qapplication.cpp 0
584 QApplication::QApplication(int &argc, char **argv, bool GUIenabled , int _internal)
585 : QGuiApplication(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, _internal))
586 { Q_D(QApplication); d->construct();}
591 Constructs an application object with \a argc command line arguments in
594 \warning The data referred to by \a argc and \a argv must stay valid for
595 the entire lifetime of the QApplication object. In addition, \a argc must
596 be greater than zero and \a argv must contain at least one valid character
599 QApplication::QApplication(int &argc, char **argv, Type type , int _internal)
600 : QGuiApplication(*new QApplicationPrivate(argc, argv, type, _internal))
601 { Q_D(QApplication); d->construct(); }
606 void QApplicationPrivate::construct()
610 qt_is_gui_used = (application_type != QApplication::Tty);
613 // Must be called before initialize()
614 qt_init(this, application_type);
616 eventDispatcher->startingUp();
619 extern void qt_gui_eval_init(uint);
620 qt_gui_eval_init(application_type);
623 #ifndef QT_NO_LIBRARY
624 if(load_testability) {
625 QLibrary testLib(QLatin1String("qttestability"));
626 if (testLib.load()) {
627 typedef void (*TasInitialize)(void);
628 TasInitialize initFunction = (TasInitialize)testLib.resolve("qt_testability_init");
632 qCritical("Library qttestability resolve failed!");
635 qCritical("Library qttestability load failed!");
641 #ifndef QT_NO_STATEMACHINE
642 void qRegisterGuiStateMachine();
643 void qUnregisterGuiStateMachine();
647 \fn void QApplicationPrivate::initialize()
649 Initializes the QApplication object, called from the constructors.
651 void QApplicationPrivate::initialize()
653 QWidgetPrivate::mapper = new QWidgetMapper;
654 QWidgetPrivate::allWidgets = new QWidgetSet;
656 if (application_type != QApplication::Tty)
657 (void) QApplication::style(); // trigger creation of application style
658 #ifndef QT_NO_STATEMACHINE
659 // trigger registering of QStateMachine's GUI types
660 qRegisterGuiStateMachine();
663 is_app_running = true; // no longer starting up
666 #ifndef QT_NO_SESSIONMANAGER
667 // connect to the session manager
668 session_manager = new QSessionManager(q, session_id, session_key);
671 if (qgetenv("QT_USE_NATIVE_WINDOWS").toInt() > 0)
672 q->setAttribute(Qt::AA_NativeWindows);
675 #ifdef QT_AUTO_MAXIMIZE_THRESHOLD
676 autoMaximizeThreshold = QT_AUTO_MAXIMIZE_THRESHOLD;
678 if (qt_wince_is_mobile())
679 autoMaximizeThreshold = 50;
681 autoMaximizeThreshold = -1;
682 #endif //QT_AUTO_MAXIMIZE_THRESHOLD
685 #ifndef QT_NO_WHEELEVENT
686 QApplicationPrivate::wheel_scroll_lines = 3;
690 initializeMultitouch();
692 if (QApplication::desktopSettingsAware())
693 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
694 QApplicationPrivate::enabledAnimations = theme->themeHint(QPlatformTheme::UiEffects).toInt();
698 Returns the type of application (\l Tty, GuiClient, or
699 GuiServer). The type is set when constructing the QApplication
702 QApplication::Type QApplication::type()
704 if (QApplicationPrivate::instance())
705 return (QCoreApplication::Type)QApplicationPrivate::instance()->application_type;
709 /*****************************************************************************
710 Functions returning the active popup and modal widgets.
711 *****************************************************************************/
714 Returns the active popup widget.
716 A popup widget is a special top-level widget that sets the \c
717 Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application
718 opens a popup widget, all events are sent to the popup. Normal widgets and
719 modal widgets cannot be accessed before the popup widget is closed.
721 Only other popup widgets may be opened when a popup widget is shown. The
722 popup widgets are organized in a stack. This function returns the active
723 popup widget at the top of the stack.
725 \sa activeModalWidget(), topLevelWidgets()
728 QWidget *QApplication::activePopupWidget()
730 return QApplicationPrivate::popupWidgets && !QApplicationPrivate::popupWidgets->isEmpty() ?
731 QApplicationPrivate::popupWidgets->last() : 0;
736 Returns the active modal widget.
738 A modal widget is a special top-level widget which is a subclass of QDialog
739 that specifies the modal parameter of the constructor as true. A modal
740 widget must be closed before the user can continue with other parts of the
743 Modal widgets are organized in a stack. This function returns the active
744 modal widget at the top of the stack.
746 \sa activePopupWidget(), topLevelWidgets()
749 QWidget *QApplication::activeModalWidget()
751 QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(modalWindow());
752 return widgetWindow ? widgetWindow->widget() : 0;
756 Cleans up any window system resources that were allocated by this
757 application. Sets the global variable \c qApp to 0.
760 QApplication::~QApplication()
764 //### this should probable be done even later
765 qt_call_post_routines();
767 // kill timers before closing down the dispatcher
768 d->toolTipWakeUp.stop();
769 d->toolTipFallAsleep.stop();
771 QApplicationPrivate::is_app_closing = true;
772 QApplicationPrivate::is_app_running = false;
774 delete QWidgetPrivate::mapper;
775 QWidgetPrivate::mapper = 0;
777 // delete all widgets
778 if (QWidgetPrivate::allWidgets) {
779 QWidgetSet *mySet = QWidgetPrivate::allWidgets;
780 QWidgetPrivate::allWidgets = 0;
781 for (QWidgetSet::ConstIterator it = mySet->constBegin(); it != mySet->constEnd(); ++it) {
782 register QWidget *w = *it;
783 if (!w->parent()) // window
784 w->destroy(true, true);
789 delete qt_desktopWidget;
790 qt_desktopWidget = 0;
792 delete QApplicationPrivate::app_pal;
793 QApplicationPrivate::app_pal = 0;
794 clearSystemPalette();
795 delete QApplicationPrivate::set_pal;
796 QApplicationPrivate::set_pal = 0;
797 app_palettes()->clear();
799 delete QApplicationPrivate::sys_font;
800 QApplicationPrivate::sys_font = 0;
801 delete QApplicationPrivate::set_font;
802 QApplicationPrivate::set_font = 0;
803 app_fonts()->clear();
805 delete QApplicationPrivate::app_style;
806 QApplicationPrivate::app_style = 0;
807 delete QApplicationPrivate::app_icon;
808 QApplicationPrivate::app_icon = 0;
810 #ifndef QT_NO_DRAGANDDROP
812 delete QDragManager::self();
815 d->cleanupMultitouch();
819 if (QApplicationPrivate::widgetCount)
820 qDebug("Widgets left: %i Max widgets: %i \n", QWidgetPrivate::instanceCounter, QWidgetPrivate::maxInstances);
821 #ifndef QT_NO_SESSIONMANAGER
822 delete d->session_manager;
823 d->session_manager = 0;
824 #endif //QT_NO_SESSIONMANAGER
826 QApplicationPrivate::obey_desktop_settings = true;
828 QApplicationPrivate::app_strut = QSize(0, 0);
829 QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
830 QApplicationPrivate::widgetCount = false;
832 #ifndef QT_NO_STATEMACHINE
833 // trigger unregistering of QStateMachine's GUI types
834 qUnregisterGuiStateMachine();
840 \fn QWidget *QApplication::widgetAt(const QPoint &point)
842 Returns the widget at global screen position \a point, or 0 if there is no
845 This function can be slow.
847 \sa QCursor::pos(), QWidget::grabMouse(), QWidget::grabKeyboard()
849 QWidget *QApplication::widgetAt(const QPoint &p)
851 QWidget *window = QApplication::topLevelAt(p);
857 if (!window->testAttribute(Qt::WA_TransparentForMouseEvents))
858 child = window->childAt(window->mapFromGlobal(p));
863 if (window->testAttribute(Qt::WA_TransparentForMouseEvents)) {
864 //shoot a hole in the widget and try once again,
865 //suboptimal on Qt for Embedded Linux where we do
866 //know the stacking order of the toplevels.
869 QRegion oldmask = window->mask();
870 QPoint wpoint = window->mapFromGlobal(QPoint(x, y));
871 QRegion newmask = (oldmask.isEmpty() ? QRegion(window->rect()) : oldmask)
872 - QRegion(wpoint.x(), wpoint.y(), 1, 1);
873 window->setMask(newmask);
874 QWidget *recurse = 0;
875 if (QApplication::topLevelAt(p) != window) // verify recursion will terminate
876 recurse = widgetAt(x, y);
877 if (oldmask.isEmpty())
880 window->setMask(oldmask);
887 \fn QWidget *QApplication::widgetAt(int x, int y)
891 Returns the widget at global screen position (\a x, \a y), or 0 if there is
898 bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
900 if ((event->type() == QEvent::UpdateRequest
901 || event->type() == QEvent::LayoutRequest
902 || event->type() == QEvent::Resize
903 || event->type() == QEvent::Move
904 || event->type() == QEvent::LanguageChange
905 || event->type() == QEvent::InputMethod)) {
906 for (QPostEventList::const_iterator it = postedEvents->constBegin(); it != postedEvents->constEnd(); ++it) {
907 const QPostEvent &cur = *it;
908 if (cur.receiver != receiver || cur.event == 0 || cur.event->type() != event->type())
910 if (cur.event->type() == QEvent::LayoutRequest
911 || cur.event->type() == QEvent::UpdateRequest) {
913 } else if (cur.event->type() == QEvent::Resize) {
914 ((QResizeEvent *)(cur.event))->s = ((QResizeEvent *)event)->s;
915 } else if (cur.event->type() == QEvent::Move) {
916 ((QMoveEvent *)(cur.event))->p = ((QMoveEvent *)event)->p;
917 } else if (cur.event->type() == QEvent::LanguageChange) {
919 } else if ( cur.event->type() == QEvent::InputMethod ) {
920 *(QInputMethodEvent *)(cur.event) = *(QInputMethodEvent *)event;
929 return QGuiApplication::compressEvent(event, receiver, postedEvents);
933 \property QApplication::styleSheet
934 \brief the application style sheet
937 By default, this property returns an empty string unless the user specifies
938 the \c{-stylesheet} option on the command line when running the application.
940 \sa QWidget::setStyle(), {Qt Style Sheets}
944 \property QApplication::autoMaximizeThreshold
946 \brief defines a threshold for auto maximizing widgets
948 \b{The auto maximize threshold is only available as part of Qt for
951 This property defines a threshold for the size of a window as a percentage
952 of the screen size. If the minimum size hint of a window exceeds the
953 threshold, calling show() will cause the window to be maximized
956 Setting the threshold to 100 or greater means that the widget will always
957 be maximized. Alternatively, setting the threshold to 50 means that the
958 widget will be maximized only if the vertical minimum size hint is at least
959 50% of the vertical screen size.
961 Setting the threshold to -1 disables the feature.
963 On Windows CE the default is -1 (i.e., it is disabled).
964 On Windows Mobile the default is 40.
968 \property QApplication::autoSipEnabled
970 \brief toggles automatic SIP (software input panel) visibility
972 Set this property to \c true to automatically display the SIP when entering
973 widgets that accept keyboard input. This property only affects widgets with
974 the WA_InputMethodEnabled attribute set, and is typically used to launch
975 a virtual keyboard on devices which have very few or no keys.
977 \b{ The property only has an effect on platforms which use software input
978 panels, such as Windows CE.}
980 The default is platform dependent.
984 void QApplication::setAutoMaximizeThreshold(const int threshold)
986 QApplicationPrivate::autoMaximizeThreshold = threshold;
989 int QApplication::autoMaximizeThreshold() const
991 return QApplicationPrivate::autoMaximizeThreshold;
995 void QApplication::setAutoSipEnabled(const bool enabled)
997 QApplicationPrivate::autoSipEnabled = enabled;
1000 bool QApplication::autoSipEnabled() const
1002 return QApplicationPrivate::autoSipEnabled;
1005 #ifndef QT_NO_STYLE_STYLESHEET
1007 QString QApplication::styleSheet() const
1009 return QApplicationPrivate::styleSheet;
1012 void QApplication::setStyleSheet(const QString& styleSheet)
1014 QApplicationPrivate::styleSheet = styleSheet;
1015 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle*>(QApplicationPrivate::app_style);
1016 if (styleSheet.isEmpty()) { // application style sheet removed
1018 return; // there was no stylesheet before
1019 setStyle(proxy->base);
1020 } else if (proxy) { // style sheet update, just repolish
1021 proxy->repolish(qApp);
1022 } else { // stylesheet set the first time
1023 QStyleSheetStyle *newProxy = new QStyleSheetStyle(QApplicationPrivate::app_style);
1024 QApplicationPrivate::app_style->setParent(newProxy);
1029 #endif // QT_NO_STYLE_STYLESHEET
1032 Returns the application's style object.
1034 \sa setStyle(), QStyle
1036 QStyle *QApplication::style()
1038 if (QApplicationPrivate::app_style)
1039 return QApplicationPrivate::app_style;
1040 if (qApp->type() == QApplication::Tty) {
1041 Q_ASSERT(!"No style available in non-gui applications!");
1045 if (!QApplicationPrivate::app_style) {
1046 // Compile-time search for default style
1049 #ifdef QT_BUILD_INTERNAL
1050 QString envStyle = QString::fromLocal8Bit(qgetenv("QT_STYLE_OVERRIDE"));
1054 if (!QApplicationPrivate::styleOverride.isEmpty()) {
1055 style = QApplicationPrivate::styleOverride;
1056 } else if (!envStyle.isEmpty()) {
1059 style = QApplicationPrivate::desktopStyleKey();
1062 QStyle *&app_style = QApplicationPrivate::app_style;
1063 app_style = QStyleFactory::create(style);
1065 QStringList styles = QStyleFactory::keys();
1066 for (int i = 0; i < styles.size(); ++i) {
1067 if ((app_style = QStyleFactory::create(styles.at(i))))
1072 Q_ASSERT(!"No styles available!");
1076 // take ownership of the style
1077 QApplicationPrivate::app_style->setParent(qApp);
1079 initSystemPalette();
1081 if (QApplicationPrivate::set_pal) // repolish set palette with the new style
1082 QApplication::setPalette(*QApplicationPrivate::set_pal);
1084 #ifndef QT_NO_STYLE_STYLESHEET
1085 if (!QApplicationPrivate::styleSheet.isEmpty()) {
1086 qApp->setStyleSheet(QApplicationPrivate::styleSheet);
1089 QApplicationPrivate::app_style->polish(qApp);
1091 return QApplicationPrivate::app_style;
1095 Sets the application's GUI style to \a style. Ownership of the style object
1096 is transferred to QApplication, so QApplication will delete the style
1097 object on application exit or when a new style is set and the old style is
1098 still the parent of the application object.
1101 \snippet code/src_gui_kernel_qapplication.cpp 1
1103 When switching application styles, the color palette is set back to the
1104 initial colors or the system defaults. This is necessary since certain
1105 styles have to adapt the color palette to be fully style-guide compliant.
1107 Setting the style before a palette has been set, i.e., before creating
1108 QApplication, will cause the application to use QStyle::standardPalette()
1111 \warning Qt style sheets are currently not supported for custom QStyle
1112 subclasses. We plan to address this in some future release.
1114 \sa style(), QStyle, setPalette(), desktopSettingsAware()
1116 void QApplication::setStyle(QStyle *style)
1118 if (!style || style == QApplicationPrivate::app_style)
1121 QWidgetList all = allWidgets();
1123 // clean up the old style
1124 if (QApplicationPrivate::app_style) {
1125 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1126 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1127 register QWidget *w = *it;
1128 if (!(w->windowType() == Qt::Desktop) && // except desktop
1129 w->testAttribute(Qt::WA_WState_Polished)) { // has been polished
1130 QApplicationPrivate::app_style->unpolish(w);
1134 QApplicationPrivate::app_style->unpolish(qApp);
1137 QStyle *old = QApplicationPrivate::app_style; // save
1139 #ifndef QT_NO_STYLE_STYLESHEET
1140 if (!QApplicationPrivate::styleSheet.isEmpty() && !qobject_cast<QStyleSheetStyle *>(style)) {
1141 // we have a stylesheet already and a new style is being set
1142 QStyleSheetStyle *newProxy = new QStyleSheetStyle(style);
1143 style->setParent(newProxy);
1144 QApplicationPrivate::app_style = newProxy;
1146 #endif // QT_NO_STYLE_STYLESHEET
1147 QApplicationPrivate::app_style = style;
1148 QApplicationPrivate::app_style->setParent(qApp); // take ownership
1150 // take care of possible palette requirements of certain gui
1151 // styles. Do it before polishing the application since the style
1152 // might call QApplication::setPalette() itself
1153 if (QApplicationPrivate::set_pal) {
1154 QApplication::setPalette(*QApplicationPrivate::set_pal);
1155 } else if (QApplicationPrivate::sys_pal) {
1156 QApplicationPrivate::initializeWidgetPaletteHash();
1157 QApplicationPrivate::setPalette_helper(*QApplicationPrivate::sys_pal, /*className=*/0, /*clearWidgetPaletteHash=*/false);
1158 } else if (!QApplicationPrivate::sys_pal) {
1159 // Initialize the sys_pal if it hasn't happened yet...
1160 QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
1163 // initialize the application with the new style
1164 QApplicationPrivate::app_style->polish(qApp);
1166 // re-polish existing widgets if necessary
1167 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1168 for (QWidgetList::ConstIterator it1 = all.constBegin(); it1 != all.constEnd(); ++it1) {
1169 register QWidget *w = *it1;
1170 if (w->windowType() != Qt::Desktop && w->testAttribute(Qt::WA_WState_Polished)) {
1171 if (w->style() == QApplicationPrivate::app_style)
1172 QApplicationPrivate::app_style->polish(w); // repolish
1173 #ifndef QT_NO_STYLE_STYLESHEET
1175 w->setStyleSheet(w->styleSheet()); // touch
1180 for (QWidgetList::ConstIterator it2 = all.constBegin(); it2 != all.constEnd(); ++it2) {
1181 register QWidget *w = *it2;
1182 if (w->windowType() != Qt::Desktop && !w->testAttribute(Qt::WA_SetStyle)) {
1183 QEvent e(QEvent::StyleChange);
1184 QApplication::sendEvent(w, &e);
1190 #ifndef QT_NO_STYLE_STYLESHEET
1191 if (QStyleSheetStyle *oldProxy = qobject_cast<QStyleSheetStyle *>(old)) {
1195 if (old && old->parent() == qApp) {
1199 if (QApplicationPrivate::focus_widget) {
1200 QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
1201 QApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
1202 QApplicationPrivate::focus_widget->update();
1209 Requests a QStyle object for \a style from the QStyleFactory.
1211 The string must be one of the QStyleFactory::keys(), typically one of
1212 "windows", "fusion", "windowsxp", or "macintosh". Style
1213 names are case insensitive.
1215 Returns 0 if an unknown \a style is passed, otherwise the QStyle object
1216 returned is set as the application's GUI style.
1218 \warning To ensure that the application's style is set correctly, it is
1219 best to call this function before the QApplication constructor, if
1222 QStyle* QApplication::setStyle(const QString& style)
1224 QStyle *s = QStyleFactory::create(style);
1233 Returns the color specification.
1235 \sa QApplication::setColorSpec()
1238 int QApplication::colorSpec()
1240 return QApplicationPrivate::app_cspec;
1244 Sets the color specification for the application to \a spec.
1246 The color specification controls how the application allocates colors when
1247 run on a display with a limited amount of colors, e.g. 8 bit / 256 color
1250 The color specification must be set before you create the QApplication
1255 \li QApplication::NormalColor. This is the default color allocation
1256 strategy. Use this option if your application uses buttons, menus,
1257 texts and pixmaps with few colors. With this option, the
1258 application uses system global colors. This works fine for most
1259 applications under X11, but on the Windows platform, it may cause
1260 dithering of non-standard colors.
1261 \li QApplication::CustomColor. Use this option if your application
1262 needs a small number of custom colors. On X11, this option is the
1263 same as NormalColor. On Windows, Qt creates a Windows palette, and
1264 allocates colors to it on demand.
1265 \li QApplication::ManyColor. Use this option if your application is
1266 very color hungry, e.g., it requires thousands of colors. \br
1267 Under X11 the effect is:
1269 \li For 256-color displays which have at best a 256 color true
1270 color visual, the default visual is used, and colors are
1271 allocated from a color cube. The color cube is the 6x6x6
1272 (216 color) "Web palette" (the red, green, and blue
1273 components always have one of the following values: 0x00,
1274 0x33, 0x66, 0x99, 0xCC, or 0xFF), but the number of colors
1275 can be changed by the \e -ncols option. The user can force
1276 the application to use the true color visual with the
1277 \l{QApplication::QApplication()}{-visual} option.
1278 \li For 256-color displays which have a true color visual with
1279 more than 256 colors, use that visual. Silicon Graphics X
1280 servers this feature, for example. They provide an 8 bit
1281 visual by default but can deliver true color when asked.
1283 On Windows, Qt creates a Windows palette, and fills it with a color
1287 Be aware that the CustomColor and ManyColor choices may lead to colormap
1288 flashing: The foreground application gets (most) of the available colors,
1289 while the background windows will look less attractive.
1293 \snippet code/src_gui_kernel_qapplication.cpp 2
1298 void QApplication::setColorSpec(int spec)
1301 qWarning("QApplication::setColorSpec: This function must be "
1302 "called before the QApplication object is created");
1303 QApplicationPrivate::app_cspec = spec;
1307 \property QApplication::globalStrut
1308 \brief the minimum size that any GUI element that the user can interact
1311 For example, no button should be resized to be smaller than the global
1312 strut size. The strut size should be considered when reimplementing GUI
1313 controls that may be used on touch-screens or similar I/O devices.
1317 \snippet code/src_gui_kernel_qapplication.cpp 3
1319 By default, this property contains a QSize object with zero width and height.
1321 QSize QApplication::globalStrut()
1323 return QApplicationPrivate::app_strut;
1326 void QApplication::setGlobalStrut(const QSize& strut)
1328 QApplicationPrivate::app_strut = strut;
1333 \fn QPalette QApplication::palette(const QWidget* widget)
1336 If a \a widget is passed, the default palette for the widget's class is
1337 returned. This may or may not be the application palette. In most cases
1338 there is no special palette for certain types of widgets, but one notable
1339 exception is the popup menu under Windows, if the user has defined a
1340 special background color for menus in the display settings.
1342 \sa setPalette(), QWidget::palette()
1344 QPalette QApplication::palette(const QWidget* w)
1346 PaletteHash *hash = app_palettes();
1347 if (w && hash && hash->size()) {
1348 QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(w->metaObject()->className());
1349 if (it != hash->constEnd())
1351 for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1352 if (w->inherits(it.key()))
1362 Returns the palette for widgets of the given \a className.
1364 \sa setPalette(), QWidget::palette()
1366 QPalette QApplication::palette(const char *className)
1368 if (!QApplicationPrivate::app_pal)
1370 PaletteHash *hash = app_palettes();
1371 if (className && hash && hash->size()) {
1372 QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(className);
1373 if (it != hash->constEnd())
1376 return *QApplicationPrivate::app_pal;
1379 void QApplicationPrivate::setPalette_helper(const QPalette &palette, const char* className, bool clearWidgetPaletteHash)
1381 QPalette pal = palette;
1383 if (QApplicationPrivate::app_style)
1384 QApplicationPrivate::app_style->polish(pal); // NB: non-const reference
1387 PaletteHash *hash = app_palettes();
1389 if (QApplicationPrivate::app_pal && pal.isCopyOf(*QApplicationPrivate::app_pal))
1391 if (!QApplicationPrivate::app_pal)
1392 QApplicationPrivate::app_pal = new QPalette(pal);
1394 *QApplicationPrivate::app_pal = pal;
1395 if (hash && hash->size()) {
1397 if (clearWidgetPaletteHash)
1401 hash->insert(className, pal);
1404 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1405 // Send ApplicationPaletteChange to qApp itself, and to the widgets.
1406 QEvent e(QEvent::ApplicationPaletteChange);
1407 QApplication::sendEvent(QApplication::instance(), &e);
1409 QWidgetList wids = QApplication::allWidgets();
1410 for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1411 register QWidget *w = *it;
1412 if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1413 QApplication::sendEvent(w, &e);
1416 // Send to all scenes as well.
1417 #ifndef QT_NO_GRAPHICSVIEW
1418 QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1419 for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1420 it != scenes.constEnd(); ++it) {
1421 QApplication::sendEvent(*it, &e);
1423 #endif //QT_NO_GRAPHICSVIEW
1425 if (!className && (!QApplicationPrivate::sys_pal || !palette.isCopyOf(*QApplicationPrivate::sys_pal))) {
1426 if (!QApplicationPrivate::set_pal)
1427 QApplicationPrivate::set_pal = new QPalette(palette);
1429 *QApplicationPrivate::set_pal = palette;
1434 Changes the default application palette to \a palette.
1436 If \a className is passed, the change applies only to widgets that inherit
1437 \a className (as reported by QObject::inherits()). If \a className is left
1438 0, the change affects all widgets, thus overriding any previously set class
1441 The palette may be changed according to the current GUI style in
1444 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1445 When using style sheets, the palette of a widget can be customized using
1446 the "color", "background-color", "selection-color",
1447 "selection-background-color" and "alternate-background-color".
1449 \note Some styles do not use the palette for all drawing, for instance, if
1450 they make use of native theme engines. This is the case for the Windows XP,
1451 Windows Vista, and Mac OS X styles.
1453 \sa QWidget::setPalette(), palette(), QStyle::polish()
1456 void QApplication::setPalette(const QPalette &palette, const char* className)
1458 QApplicationPrivate::setPalette_helper(palette, className, /*clearWidgetPaletteHash=*/ true);
1463 void QApplicationPrivate::setSystemPalette(const QPalette &pal)
1468 // adjust the system palette to avoid dithering
1469 QColormap cmap = QColormap::instance();
1470 if (cmap.depths() > 4 && cmap.depths() < 24) {
1471 for (int g = 0; g < QPalette::NColorGroups; g++)
1472 for (int i = 0; i < QPalette::NColorRoles; i++) {
1473 QColor color = pal.color((QPalette::ColorGroup)g, (QPalette::ColorRole)i);
1474 color = cmap.colorAt(cmap.pixel(color));
1475 adjusted.setColor((QPalette::ColorGroup)g, (QPalette::ColorRole) i, color);
1483 sys_pal = new QPalette(adjusted);
1485 *sys_pal = adjusted;
1488 if (!QApplicationPrivate::set_pal)
1489 QApplication::setPalette(*sys_pal);
1493 Returns the default application font.
1495 \sa fontMetrics(), QWidget::font()
1497 QFont QApplication::font()
1499 return QGuiApplication::font();
1505 Returns the default font for the \a widget.
1507 \sa fontMetrics(), QWidget::setFont()
1510 QFont QApplication::font(const QWidget *widget)
1512 FontHash *hash = app_fonts();
1514 if (widget && hash && hash->size()) {
1515 QHash<QByteArray, QFont>::ConstIterator it =
1516 hash->constFind(widget->metaObject()->className());
1517 if (it != hash->constEnd())
1519 for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1520 if (widget->inherits(it.key()))
1530 Returns the font for widgets of the given \a className.
1532 \sa setFont(), QWidget::font()
1534 QFont QApplication::font(const char *className)
1536 FontHash *hash = app_fonts();
1537 if (className && hash && hash->size()) {
1538 QHash<QByteArray, QFont>::ConstIterator it = hash->constFind(className);
1539 if (it != hash->constEnd())
1547 Changes the default application font to \a font. If \a className is passed,
1548 the change applies only to classes that inherit \a className (as reported
1549 by QObject::inherits()).
1551 On application start-up, the default font depends on the window system. It
1552 can vary depending on both the window system version and the locale. This
1553 function lets you override the default font; but overriding may be a bad
1554 idea because, for example, some locales need extra large fonts to support
1555 their special characters.
1557 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1558 The font of an application can be customized using the "font" style sheet
1559 property. To set a bold font for all QPushButtons, set the application
1560 styleSheet() as "QPushButton { font: bold }"
1562 \sa font(), fontMetrics(), QWidget::setFont()
1565 void QApplication::setFont(const QFont &font, const char *className)
1568 FontHash *hash = app_fonts();
1570 QGuiApplication::setFont(font);
1571 if (hash && hash->size()) {
1576 hash->insert(className, font);
1578 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1579 // Send ApplicationFontChange to qApp itself, and to the widgets.
1580 QEvent e(QEvent::ApplicationFontChange);
1581 QApplication::sendEvent(QApplication::instance(), &e);
1583 QWidgetList wids = QApplication::allWidgets();
1584 for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1585 register QWidget *w = *it;
1586 if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1590 #ifndef QT_NO_GRAPHICSVIEW
1591 // Send to all scenes as well.
1592 QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1593 for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1594 it != scenes.constEnd(); ++it) {
1595 QApplication::sendEvent(*it, &e);
1597 #endif //QT_NO_GRAPHICSVIEW
1599 if (!className && (!QApplicationPrivate::sys_font || !font.isCopyOf(*QApplicationPrivate::sys_font))) {
1600 if (!QApplicationPrivate::set_font)
1601 QApplicationPrivate::set_font = new QFont(font);
1603 *QApplicationPrivate::set_font = font;
1609 void QApplicationPrivate::setSystemFont(const QFont &font)
1612 sys_font = new QFont(font);
1616 if (!QApplicationPrivate::set_font)
1617 QApplication::setFont(*sys_font);
1622 QString QApplicationPrivate::desktopStyleKey()
1624 // The platform theme might return a style that is not available, find
1626 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
1627 const QStringList availableKeys = QStyleFactory::keys();
1628 foreach (const QString &style, theme->themeHint(QPlatformTheme::StyleNames).toStringList())
1629 if (availableKeys.contains(style, Qt::CaseInsensitive))
1636 \property QApplication::windowIcon
1637 \brief the default window icon
1639 \sa QWidget::setWindowIcon(), {Setting the Application Icon}
1641 QIcon QApplication::windowIcon()
1643 return QApplicationPrivate::app_icon ? *QApplicationPrivate::app_icon : QIcon();
1646 void QApplication::setWindowIcon(const QIcon &icon)
1648 if (!QApplicationPrivate::app_icon)
1649 QApplicationPrivate::app_icon = new QIcon();
1650 *QApplicationPrivate::app_icon = icon;
1651 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1652 QEvent e(QEvent::ApplicationWindowIconChange);
1653 QWidgetList all = QApplication::allWidgets();
1654 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1655 register QWidget *w = *it;
1663 Returns a list of the top-level widgets (windows) in the application.
1665 \note Some of the top-level widgets may be hidden, for example a tooltip if
1666 no tooltip is currently shown.
1670 \snippet code/src_gui_kernel_qapplication.cpp 4
1672 \sa allWidgets(), QWidget::isWindow(), QWidget::isHidden()
1674 QWidgetList QApplication::topLevelWidgets()
1677 QWidgetList all = allWidgets();
1679 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1681 if (w->isWindow() && w->windowType() != Qt::Desktop)
1688 Returns a list of all the widgets in the application.
1690 The list is empty (QList::isEmpty()) if there are no widgets.
1692 \note Some of the widgets may be hidden.
1695 \snippet code/src_gui_kernel_qapplication.cpp 5
1697 \sa topLevelWidgets(), QWidget::isVisible()
1700 QWidgetList QApplication::allWidgets()
1702 if (QWidgetPrivate::allWidgets)
1703 return QWidgetPrivate::allWidgets->toList();
1704 return QWidgetList();
1708 Returns the application widget that has the keyboard input focus, or 0 if
1709 no widget in this application has the focus.
1711 \sa QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), focusChanged()
1714 QWidget *QApplication::focusWidget()
1716 return QApplicationPrivate::focus_widget;
1719 void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
1721 #ifndef QT_NO_GRAPHICSVIEW
1722 if (focus && focus->window()->graphicsProxyWidget())
1726 hidden_focus_widget = 0;
1728 if (focus != focus_widget) {
1729 if (focus && focus->isHidden()) {
1730 hidden_focus_widget = focus;
1734 if (focus && (reason == Qt::BacktabFocusReason || reason == Qt::TabFocusReason)
1735 && qt_in_tab_key_event)
1736 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1737 else if (focus && reason == Qt::ShortcutFocusReason) {
1738 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1740 QWidget *prev = focus_widget;
1741 focus_widget = focus;
1744 focus_widget->d_func()->setFocus_sys();
1746 if (reason != Qt::NoFocusReason) {
1750 #ifdef QT_KEYPAD_NAVIGATION
1751 if (QApplication::keypadNavigationEnabled()) {
1752 if (prev->hasEditFocus() && reason != Qt::PopupFocusReason)
1753 prev->setEditFocus(false);
1756 QFocusEvent out(QEvent::FocusOut, reason);
1757 QPointer<QWidget> that = prev;
1758 QApplication::sendEvent(prev, &out);
1760 QApplication::sendEvent(that->style(), &out);
1762 if(focus && QApplicationPrivate::focus_widget == focus) {
1763 QFocusEvent in(QEvent::FocusIn, reason);
1764 QPointer<QWidget> that = focus;
1765 QApplication::sendEvent(focus, &in);
1767 QApplication::sendEvent(that->style(), &in);
1769 emit qApp->focusChanged(prev, focus_widget);
1776 Returns the application top-level window that has the keyboard input focus,
1777 or 0 if no application window has the focus. There might be an
1778 activeWindow() even if there is no focusWidget(), for example if no widget
1779 in that window accepts key events.
1781 \sa QWidget::setFocus(), QWidget::hasFocus(), focusWidget()
1784 QWidget *QApplication::activeWindow()
1786 return QApplicationPrivate::active_window;
1790 Returns display (screen) font metrics for the application font.
1792 \sa font(), setFont(), QWidget::fontMetrics(), QPainter::fontMetrics()
1795 QFontMetrics QApplication::fontMetrics()
1797 return desktop()->fontMetrics();
1802 Closes all top-level windows.
1804 This function is particularly useful for applications with many top-level
1805 windows. It could, for example, be connected to a \uicontrol{Exit} entry in the
1806 \uicontrol{File} menu:
1808 \snippet mainwindows/mdi/mainwindow.cpp 0
1810 The windows are closed in random order, until one window does not accept
1811 the close event. The application quits when the last window was
1812 successfully closed; this can be turned off by setting
1813 \l quitOnLastWindowClosed to false.
1815 \sa quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(),
1816 QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(),
1819 void QApplication::closeAllWindows()
1821 bool did_close = true;
1823 while ((w = activeModalWidget()) && did_close) {
1824 if (!w->isVisible() || w->data->is_closing)
1826 did_close = w->close();
1828 QWidgetList list = QApplication::topLevelWidgets();
1829 for (int i = 0; did_close && i < list.size(); ++i) {
1832 && w->windowType() != Qt::Desktop
1833 && !w->data->is_closing) {
1834 did_close = w->close();
1835 list = QApplication::topLevelWidgets();
1842 Displays a simple message box about Qt. The message includes the version
1843 number of Qt being used by the application.
1845 This is useful for inclusion in the \uicontrol Help menu of an application, as
1846 shown in the \l{mainwindows/menus}{Menus} example.
1848 This function is a convenience slot for QMessageBox::aboutQt().
1850 void QApplication::aboutQt()
1852 #ifndef QT_NO_MESSAGEBOX
1853 QMessageBox::aboutQt(activeWindow());
1854 #endif // QT_NO_MESSAGEBOX
1859 \fn void QApplication::focusChanged(QWidget *old, QWidget *now)
1861 This signal is emitted when the widget that has keyboard focus changed from
1862 \a old to \a now, i.e., because the user pressed the tab-key, clicked into
1863 a widget or changed the active window. Both \a old and \a now can be the
1866 The signal is emitted after both widget have been notified about the change
1867 through QFocusEvent.
1869 \sa QWidget::setFocus(), QWidget::clearFocus(), Qt::FocusReason
1875 bool QApplication::event(QEvent *e)
1878 if(e->type() == QEvent::Close) {
1879 QCloseEvent *ce = static_cast<QCloseEvent*>(e);
1883 QWidgetList list = topLevelWidgets();
1884 for (int i = 0; i < list.size(); ++i) {
1885 QWidget *w = list.at(i);
1886 if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
1887 (!(w->windowType() == Qt::Dialog) || !w->parentWidget())) {
1892 if (ce->isAccepted()) {
1896 } else if (e->type() == QEvent::LocaleChange) {
1897 // on Windows the event propagation is taken care by the
1898 // WM_SETTINGCHANGE event handler.
1899 QWidgetList list = topLevelWidgets();
1900 for (int i = 0; i < list.size(); ++i) {
1901 QWidget *w = list.at(i);
1902 if (!(w->windowType() == Qt::Desktop)) {
1903 if (!w->testAttribute(Qt::WA_SetLocale))
1904 w->d_func()->setLocale_helper(QLocale(), true);
1908 } else if (e->type() == QEvent::Timer) {
1909 QTimerEvent *te = static_cast<QTimerEvent*>(e);
1911 if (te->timerId() == d->toolTipWakeUp.timerId()) {
1912 d->toolTipWakeUp.stop();
1913 if (d->toolTipWidget) {
1914 QWidget *w = d->toolTipWidget->window();
1915 // show tooltip if WA_AlwaysShowToolTips is set, or if
1916 // any ancestor of d->toolTipWidget is the active
1918 bool showToolTip = w->testAttribute(Qt::WA_AlwaysShowToolTips);
1919 while (w && !showToolTip) {
1920 showToolTip = w->isActiveWindow();
1921 w = w->parentWidget();
1922 w = w ? w->window() : 0;
1925 QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
1926 QApplication::sendEvent(d->toolTipWidget, &e);
1928 d->toolTipFallAsleep.start(2000, this);
1931 } else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
1932 d->toolTipFallAsleep.stop();
1936 if(e->type() == QEvent::LanguageChange) {
1937 QWidgetList list = topLevelWidgets();
1938 for (int i = 0; i < list.size(); ++i) {
1939 QWidget *w = list.at(i);
1940 if (!(w->windowType() == Qt::Desktop))
1941 postEvent(w, new QEvent(QEvent::LanguageChange));
1945 return QGuiApplication::event(e);
1949 \fn void QApplication::syncX()
1950 Was used to synchronize with the X server in 4.x, here for source compatibility.
1955 void QApplicationPrivate::notifyLayoutDirectionChange()
1957 QWidgetList list = QApplication::topLevelWidgets();
1958 for (int i = 0; i < list.size(); ++i) {
1959 QWidget *w = list.at(i);
1960 QEvent ev(QEvent::ApplicationLayoutDirectionChange);
1961 QCoreApplication::sendEvent(w, &ev);
1966 \fn void QApplication::setActiveWindow(QWidget* active)
1968 Sets the active window to the \a active widget in response to a system
1969 event. The function is called from the platform specific event handlers.
1971 \warning This function does \e not set the keyboard focus to the active
1972 widget. Call QWidget::activateWindow() instead.
1974 It sets the activeWindow() and focusWidget() attributes and sends proper
1975 \l{QEvent::WindowActivate}{WindowActivate}/\l{QEvent::WindowDeactivate}
1976 {WindowDeactivate} and \l{QEvent::FocusIn}{FocusIn}/\l{QEvent::FocusOut}
1977 {FocusOut} events to all appropriate widgets. The window will then be
1978 painted in active state (e.g. cursors in line edits will blink), and it
1979 will have tool tips enabled.
1981 \sa activeWindow(), QWidget::activateWindow()
1983 void QApplication::setActiveWindow(QWidget* act)
1985 QWidget* window = act?act->window():0;
1987 if (QApplicationPrivate::active_window == window)
1990 #ifndef QT_NO_GRAPHICSVIEW
1991 if (window && window->graphicsProxyWidget()) {
1992 // Activate the proxy's view->viewport() ?
1997 QWidgetList toBeActivated;
1998 QWidgetList toBeDeactivated;
2000 if (QApplicationPrivate::active_window) {
2001 if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2002 QWidgetList list = topLevelWidgets();
2003 for (int i = 0; i < list.size(); ++i) {
2004 QWidget *w = list.at(i);
2005 if (w->isVisible() && w->isActiveWindow())
2006 toBeDeactivated.append(w);
2009 toBeDeactivated.append(QApplicationPrivate::active_window);
2013 if (QApplicationPrivate::focus_widget) {
2014 if (QApplicationPrivate::focus_widget->testAttribute(Qt::WA_InputMethodEnabled))
2015 qApp->inputMethod()->commit();
2017 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, Qt::ActiveWindowFocusReason);
2018 QApplication::sendEvent(QApplicationPrivate::focus_widget, &focusAboutToChange);
2021 QApplicationPrivate::active_window = window;
2023 if (QApplicationPrivate::active_window) {
2024 if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2025 QWidgetList list = topLevelWidgets();
2026 for (int i = 0; i < list.size(); ++i) {
2027 QWidget *w = list.at(i);
2028 if (w->isVisible() && w->isActiveWindow())
2029 toBeActivated.append(w);
2032 toBeActivated.append(QApplicationPrivate::active_window);
2037 // first the activation/deactivation events
2038 QEvent activationChange(QEvent::ActivationChange);
2039 QEvent windowActivate(QEvent::WindowActivate);
2040 QEvent windowDeactivate(QEvent::WindowDeactivate);
2042 for (int i = 0; i < toBeActivated.size(); ++i) {
2043 QWidget *w = toBeActivated.at(i);
2044 sendSpontaneousEvent(w, &windowActivate);
2045 sendSpontaneousEvent(w, &activationChange);
2048 for(int i = 0; i < toBeDeactivated.size(); ++i) {
2049 QWidget *w = toBeDeactivated.at(i);
2050 sendSpontaneousEvent(w, &windowDeactivate);
2051 sendSpontaneousEvent(w, &activationChange);
2054 if (QApplicationPrivate::popupWidgets == 0) { // !inPopupMode()
2055 // then focus events
2056 if (!QApplicationPrivate::active_window && QApplicationPrivate::focus_widget) {
2057 QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2058 } else if (QApplicationPrivate::active_window) {
2059 QWidget *w = QApplicationPrivate::active_window->focusWidget();
2060 if (w && w->isVisible() /*&& w->focusPolicy() != QWidget::NoFocus*/)
2061 w->setFocus(Qt::ActiveWindowFocusReason);
2063 w = QApplicationPrivate::focusNextPrevChild_helper(QApplicationPrivate::active_window, true);
2065 w->setFocus(Qt::ActiveWindowFocusReason);
2067 // If the focus widget is not in the activate_window, clear the focus
2068 w = QApplicationPrivate::focus_widget;
2069 if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus)
2070 QApplicationPrivate::setFocusWidget(QApplicationPrivate::active_window, Qt::ActiveWindowFocusReason);
2071 else if (!QApplicationPrivate::active_window->isAncestorOf(w))
2072 QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2080 * Helper function that returns the new focus widget, but does not set the focus reason.
2081 * Returns 0 if a new focus widget could not be found.
2082 * Shared with QGraphicsProxyWidgetPrivate::findFocusChild()
2084 QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool next)
2086 uint focus_flag = qt_tab_all_widgets() ? Qt::TabFocus : Qt::StrongFocus;
2088 QWidget *f = toplevel->focusWidget();
2093 QWidget *test = f->d_func()->focus_next;
2094 while (test && test != f) {
2095 if ((test->focusPolicy() & focus_flag) == focus_flag
2096 && !(test->d_func()->extra && test->d_func()->extra->focus_proxy)
2097 && test->isVisibleTo(toplevel) && test->isEnabled()
2098 && !(w->windowType() == Qt::SubWindow && !w->isAncestorOf(test))
2099 && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))) {
2104 test = test->d_func()->focus_next;
2107 if (qt_in_tab_key_event) {
2108 w->window()->setAttribute(Qt::WA_KeyboardFocusChange);
2117 \fn void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave)
2120 Creates the proper Enter/Leave event when widget \a enter is entered and
2121 widget \a leave is left.
2123 void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave) {
2126 QEvent e(QEvent::Leave);
2127 QApplication::sendEvent(leave, & e);
2130 QEvent e(QEvent::Enter);
2131 QApplication::sendEvent(enter, & e);
2137 if ((!enter && !leave) || (enter == leave))
2140 qDebug() << "QApplicationPrivate::dispatchEnterLeave, ENTER:" << enter << "LEAVE:" << leave;
2142 QWidgetList leaveList;
2143 QWidgetList enterList;
2145 bool sameWindow = leave && enter && leave->window() == enter->window();
2146 if (leave && !sameWindow) {
2149 leaveList.append(w);
2150 } while (!w->isWindow() && (w = w->parentWidget()));
2152 if (enter && !sameWindow) {
2155 enterList.prepend(w);
2156 } while (!w->isWindow() && (w = w->parentWidget()));
2162 while (!w->isWindow() && (w = w->parentWidget()))
2165 while (!w->isWindow() && (w = w->parentWidget()))
2167 QWidget* wenter = enter;
2168 QWidget* wleave = leave;
2169 while (enterDepth > leaveDepth) {
2170 wenter = wenter->parentWidget();
2173 while (leaveDepth > enterDepth) {
2174 wleave = wleave->parentWidget();
2177 while (!wenter->isWindow() && wenter != wleave) {
2178 wenter = wenter->parentWidget();
2179 wleave = wleave->parentWidget();
2183 while (w != wleave) {
2184 leaveList.append(w);
2185 w = w->parentWidget();
2188 while (w != wenter) {
2189 enterList.prepend(w);
2190 w = w->parentWidget();
2194 QEvent leaveEvent(QEvent::Leave);
2195 for (int i = 0; i < leaveList.size(); ++i) {
2196 w = leaveList.at(i);
2197 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2198 QApplication::sendEvent(w, &leaveEvent);
2199 if (w->testAttribute(Qt::WA_Hover) &&
2200 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2201 Q_ASSERT(instance());
2202 QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos),
2203 QApplication::keyboardModifiers());
2204 qApp->d_func()->notify_helper(w, &he);
2208 QPoint posEnter = QCursor::pos();
2209 QEvent enterEvent(QEvent::Enter);
2210 for (int i = 0; i < enterList.size(); ++i) {
2211 w = enterList.at(i);
2212 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2213 QApplication::sendEvent(w, &enterEvent);
2214 if (w->testAttribute(Qt::WA_Hover) &&
2215 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2216 QHoverEvent he(QEvent::HoverEnter, w->mapFromGlobal(posEnter), QPoint(-1, -1),
2217 QApplication::keyboardModifiers());
2218 qApp->d_func()->notify_helper(w, &he);
2223 #ifndef QT_NO_CURSOR
2224 // Update cursor for alien/graphics widgets.
2226 const bool enterOnAlien = (enter && (isAlien(enter) || enter->testAttribute(Qt::WA_DontShowOnScreen)));
2227 // Whenever we leave an alien widget on X11/QPA, we need to reset its nativeParentWidget()'s cursor.
2228 // This is not required on Windows as the cursor is reset on every single mouse move.
2229 QWidget *parentOfLeavingCursor = 0;
2230 for (int i = 0; i < leaveList.size(); ++i) {
2231 w = leaveList.at(i);
2234 if (w->testAttribute(Qt::WA_SetCursor)) {
2235 QWidget *parent = w->parentWidget();
2236 while (parent && parent->d_func()->data.in_destructor)
2237 parent = parent->parentWidget();
2238 parentOfLeavingCursor = parent;
2239 //continue looping, we need to find the downest alien widget with a cursor.
2240 // (downest on the screen)
2243 //check that we will not call qt_x11_enforce_cursor twice with the same native widget
2244 if (parentOfLeavingCursor && (!enterOnAlien
2245 || parentOfLeavingCursor->effectiveWinId() != enter->effectiveWinId())) {
2246 #ifndef QT_NO_GRAPHICSVIEW
2247 if (!parentOfLeavingCursor->window()->graphicsProxyWidget())
2250 if (enter == QApplication::desktop()) {
2251 qt_qpa_set_cursor(enter, true);
2253 qt_qpa_set_cursor(parentOfLeavingCursor, true);
2258 QWidget *cursorWidget = enter;
2259 while (!cursorWidget->isWindow() && !cursorWidget->isEnabled())
2260 cursorWidget = cursorWidget->parentWidget();
2265 #ifndef QT_NO_GRAPHICSVIEW
2266 if (cursorWidget->window()->graphicsProxyWidget()) {
2267 QWidgetPrivate::nearestGraphicsProxyWidget(cursorWidget)->setCursor(cursorWidget->cursor());
2271 qt_qpa_set_cursor(cursorWidget, true);
2277 /* exported for the benefit of testing tools */
2278 Q_WIDGETS_EXPORT bool qt_tryModalHelper(QWidget *widget, QWidget **rettop)
2280 return QApplicationPrivate::tryModalHelper(widget, rettop);
2284 Returns true if \a widget is blocked by a modal window.
2286 bool QApplicationPrivate::isBlockedByModal(QWidget *widget)
2288 widget = widget->window();
2289 return self->isWindowBlocked(widget->windowHandle());
2292 bool QApplicationPrivate::isWindowBlocked(QWindow *window, QWindow **blockingWindow) const
2294 QWindow *unused = 0;
2295 if (!blockingWindow)
2296 blockingWindow = &unused;
2298 if (modalWindowList.isEmpty()) {
2299 *blockingWindow = 0;
2302 QWidget *popupWidget = QApplication::activePopupWidget();
2303 QWindow *popupWindow = popupWidget ? popupWidget->windowHandle() : 0;
2304 if (popupWindow == window) {
2305 *blockingWindow = 0;
2309 for (int i = 0; i < modalWindowList.count(); ++i) {
2310 QWindow *modalWindow = modalWindowList.at(i);
2313 // check if the modal window is our window or a (transient) parent of our window
2314 QWindow *w = window;
2316 if (w == modalWindow) {
2317 *blockingWindow = 0;
2320 QWindow *p = w->parent();
2322 p = w->transientParent();
2326 // Embedded in-process windows are not visible in normal parent-child chain,
2327 // so check the native parent chain, too.
2328 const QPlatformWindow *platWin = window->handle();
2329 const QPlatformWindow *modalPlatWin = modalWindow->handle();
2330 if (platWin && modalPlatWin && platWin->isEmbedded(modalPlatWin))
2334 Qt::WindowModality windowModality = modalWindow->windowModality();
2335 QWidgetWindow *modalWidgetWindow = qobject_cast<QWidgetWindow *>(modalWindow);
2336 if (windowModality == Qt::NonModal) {
2337 // determine the modality type if it hasn't been set on the
2338 // modalWindow's widget, this normally happens when waiting for a
2339 // native dialog. use WindowModal if we are the child of a group
2340 // leader; otherwise use ApplicationModal.
2341 QWidget *m = modalWidgetWindow ? modalWidgetWindow->widget() : 0;
2342 while (m && !m->testAttribute(Qt::WA_GroupLeader)) {
2343 m = m->parentWidget();
2347 windowModality = (m && m->testAttribute(Qt::WA_GroupLeader))
2349 : Qt::ApplicationModal;
2352 switch (windowModality) {
2353 case Qt::ApplicationModal:
2355 QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(window);
2356 QWidget *groupLeaderForWidget = widgetWindow ? widgetWindow->widget() : 0;
2357 while (groupLeaderForWidget && !groupLeaderForWidget->testAttribute(Qt::WA_GroupLeader))
2358 groupLeaderForWidget = groupLeaderForWidget->parentWidget();
2360 if (groupLeaderForWidget) {
2361 // if \a widget has WA_GroupLeader, it can only be blocked by ApplicationModal children
2362 QWidget *m = modalWidgetWindow ? modalWidgetWindow->widget() : 0;
2363 while (m && m != groupLeaderForWidget && !m->testAttribute(Qt::WA_GroupLeader))
2364 m = m->parentWidget();
2365 if (m == groupLeaderForWidget) {
2366 *blockingWindow = m->windowHandle();
2369 } else if (modalWindow != window) {
2370 *blockingWindow = modalWindow;
2375 case Qt::WindowModal:
2377 QWindow *w = window;
2379 QWindow *m = modalWindow;
2382 *blockingWindow = m;
2385 QWindow *p = m->parent();
2387 p = m->transientParent();
2390 QWindow *p = w->parent();
2392 p = w->transientParent();
2398 Q_ASSERT_X(false, "QApplication", "internal error, a modal window cannot be modeless");
2402 *blockingWindow = 0;
2408 Called from qapplication_\e{platform}.cpp, returns true
2409 if the widget should accept the event.
2411 bool QApplicationPrivate::tryModalHelper(QWidget *widget, QWidget **rettop)
2413 QWidget *top = QApplication::activeModalWidget();
2417 // the active popup widget always gets the input event
2418 if (QApplication::activePopupWidget())
2421 return !isBlockedByModal(widget->window());
2427 QWidget *QApplicationPrivate::pickMouseReceiver(QWidget *candidate, const QPoint &windowPos,
2428 QPoint *pos, QEvent::Type type,
2429 Qt::MouseButtons buttons, QWidget *buttonDown,
2430 QWidget *alienWidget)
2432 Q_ASSERT(candidate);
2434 QWidget *mouseGrabber = QWidget::mouseGrabber();
2435 if (((type == QEvent::MouseMove && buttons) || (type == QEvent::MouseButtonRelease))
2436 && !buttonDown && !mouseGrabber) {
2440 if (alienWidget && alienWidget->internalWinId())
2443 QWidget *receiver = candidate;
2446 mouseGrabber = (buttonDown && !isBlockedByModal(buttonDown)) ? buttonDown : alienWidget;
2448 if (mouseGrabber && mouseGrabber != candidate) {
2449 receiver = mouseGrabber;
2450 *pos = receiver->mapFromGlobal(candidate->mapToGlobal(windowPos));
2452 qDebug() << " ** receiver adjusted to:" << receiver << "pos:" << pos;
2463 bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
2464 QWidget *alienWidget, QWidget *nativeWidget,
2465 QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
2470 Q_ASSERT(nativeWidget);
2471 Q_ASSERT(buttonDown);
2473 if (alienWidget && !isAlien(alienWidget))
2476 QPointer<QWidget> receiverGuard = receiver;
2477 QPointer<QWidget> nativeGuard = nativeWidget;
2478 QPointer<QWidget> alienGuard = alienWidget;
2479 QPointer<QWidget> activePopupWidget = QApplication::activePopupWidget();
2481 const bool graphicsWidget = nativeWidget->testAttribute(Qt::WA_DontShowOnScreen);
2483 bool widgetUnderMouse = QRectF(receiver->rect()).contains(event->localPos());
2485 // Clear the obsolete leaveAfterRelease value, if mouse button has been released but
2486 // leaveAfterRelease has not been updated.
2487 // This happens e.g. when modal dialog or popup is shown as a response to button click.
2488 if (leaveAfterRelease && !*buttonDown && !event->buttons())
2489 leaveAfterRelease = 0;
2492 if (!graphicsWidget) {
2493 // Register the widget that shall receive a leave event
2494 // after the last button is released.
2495 if ((alienWidget || !receiver->internalWinId()) && !leaveAfterRelease && !QWidget::mouseGrabber())
2496 leaveAfterRelease = *buttonDown;
2497 if (event->type() == QEvent::MouseButtonRelease && !event->buttons())
2500 } else if (lastMouseReceiver && widgetUnderMouse) {
2501 // Dispatch enter/leave if we move:
2502 // 1) from an alien widget to another alien widget or
2503 // from a native widget to an alien widget (first OR case)
2504 // 2) from an alien widget to a native widget (second OR case)
2505 if ((alienWidget && alienWidget != lastMouseReceiver)
2506 || (isAlien(lastMouseReceiver) && !alienWidget)) {
2507 if (activePopupWidget) {
2508 if (!QWidget::mouseGrabber())
2509 dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver);
2511 dispatchEnterLeave(receiver, lastMouseReceiver);
2518 qDebug() << "QApplicationPrivate::sendMouseEvent: receiver:" << receiver
2519 << "pos:" << event->pos() << "alien" << alienWidget << "button down"
2520 << *buttonDown << "last" << lastMouseReceiver << "leave after release"
2521 << leaveAfterRelease;
2524 // We need this quard in case someone opens a modal dialog / popup. If that's the case
2525 // leaveAfterRelease is set to null, but we shall not update lastMouseReceiver.
2526 const bool wasLeaveAfterRelease = leaveAfterRelease != 0;
2529 result = QApplication::sendSpontaneousEvent(receiver, event);
2531 result = QApplication::sendEvent(receiver, event);
2533 if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease
2534 && !event->buttons() && QWidget::mouseGrabber() != leaveAfterRelease) {
2535 // Dispatch enter/leave if:
2536 // 1) the mouse grabber is an alien widget
2537 // 2) the button is released on an alien widget
2540 enter = alienGuard ? alienWidget : nativeWidget;
2541 else // The receiver is typically deleted on mouse release with drag'n'drop.
2542 enter = QApplication::widgetAt(event->globalPos());
2543 dispatchEnterLeave(enter, leaveAfterRelease);
2544 leaveAfterRelease = 0;
2545 lastMouseReceiver = enter;
2546 } else if (!wasLeaveAfterRelease) {
2547 if (activePopupWidget) {
2548 if (!QWidget::mouseGrabber())
2549 lastMouseReceiver = alienGuard ? alienWidget : (nativeGuard ? nativeWidget : 0);
2551 lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPos());
2559 This function should only be called when the widget changes visibility, i.e.
2560 when the \a widget is shown, hidden or deleted. This function does nothing
2561 if the widget is a top-level or native, i.e. not an alien widget. In that
2562 case enter/leave events are genereated by the underlying windowing system.
2564 extern QPointer<QWidget> qt_last_mouse_receiver;
2565 extern QWidget *qt_button_down;
2566 void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
2568 #ifndef QT_NO_CURSOR
2569 if (!widget || widget->isWindow())
2571 const bool widgetInShow = widget->isVisible() && !widget->data->in_destructor;
2572 if (!widgetInShow && widget != qt_last_mouse_receiver)
2573 return; // Widget was not under the cursor when it was hidden/deleted.
2575 if (widgetInShow && widget->parentWidget()->data->in_show)
2576 return; // Ingore recursive show.
2578 QWidget *mouseGrabber = QWidget::mouseGrabber();
2579 if (mouseGrabber && mouseGrabber != widget)
2580 return; // Someone else has the grab; enter/leave should not occur.
2582 QWidget *tlw = widget->window();
2583 if (tlw->data->in_destructor || tlw->data->is_closing)
2584 return; // Closing down the business.
2586 if (widgetInShow && (!qt_last_mouse_receiver || qt_last_mouse_receiver->window() != tlw))
2587 return; // Mouse cursor not inside the widget's top-level.
2589 const QPoint globalPos(QCursor::pos());
2590 QPoint windowPos = tlw->mapFromGlobal(globalPos);
2592 // Find the current widget under the mouse. If this function was called from
2593 // the widget's destructor, we have to make sure childAt() doesn't take into
2594 // account widgets that are about to be destructed.
2595 QWidget *widgetUnderCursor = tlw->d_func()->childAt_helper(windowPos, widget->data->in_destructor);
2596 if (!widgetUnderCursor)
2597 widgetUnderCursor = tlw;
2598 QPoint pos = widgetUnderCursor->mapFrom(tlw, windowPos);
2600 if (widgetInShow && widgetUnderCursor != widget && !widget->isAncestorOf(widgetUnderCursor))
2601 return; // Mouse cursor not inside the widget or any of its children.
2603 if (widget->data->in_destructor && qt_button_down == widget)
2606 // Send enter/leave events followed by a mouse move on the entered widget.
2607 QMouseEvent e(QEvent::MouseMove, pos, windowPos, globalPos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
2608 sendMouseEvent(widgetUnderCursor, &e, widgetUnderCursor, tlw, &qt_button_down, qt_last_mouse_receiver);
2609 #endif // QT_NO_CURSOR
2613 Returns the desktop widget (also called the root window).
2615 The desktop may be composed of multiple screens, so it would be incorrect,
2616 for example, to attempt to \e center some widget in the desktop's geometry.
2617 QDesktopWidget has various functions for obtaining useful geometries upon
2618 the desktop, such as QDesktopWidget::screenGeometry() and
2619 QDesktopWidget::availableGeometry().
2621 On X11, it is also possible to draw on the desktop.
2623 QDesktopWidget *QApplication::desktop()
2625 if (!qt_desktopWidget || // not created yet
2626 !(qt_desktopWidget->windowType() == Qt::Desktop)) { // reparented away
2627 qt_desktopWidget = new QDesktopWidget();
2629 return qt_desktopWidget;
2634 \fn bool QApplication::isSessionRestored() const
2636 Returns true if the application has been restored from an earlier
2637 \l{Session Management}{session}; otherwise returns false.
2639 \sa sessionId(), commitData(), saveState()
2644 \fn QString QApplication::sessionId() const
2646 Returns the current \l{Session Management}{session's} identifier.
2648 If the application has been restored from an earlier session, this
2649 identifier is the same as it was in that previous session. The session
2650 identifier is guaranteed to be unique both for different applications
2651 and for different instances of the same application.
2653 \sa isSessionRestored(), sessionKey(), commitData(), saveState()
2657 \fn QString QApplication::sessionKey() const
2659 Returns the session key in the current \l{Session Management}{session}.
2661 If the application has been restored from an earlier session, this key is
2662 the same as it was when the previous session ended.
2664 The session key changes with every call of commitData() or saveState().
2666 \sa isSessionRestored(), sessionId(), commitData(), saveState()
2668 #ifndef QT_NO_SESSIONMANAGER
2669 bool QApplication::isSessionRestored() const
2671 Q_D(const QApplication);
2672 return d->is_session_restored;
2675 QString QApplication::sessionId() const
2677 Q_D(const QApplication);
2678 return d->session_id;
2681 QString QApplication::sessionKey() const
2683 Q_D(const QApplication);
2684 return d->session_key;
2692 \fn void QApplication::commitDataRequest(QSessionManager &manager)
2694 This signal deals with \l{Session Management}{session management}. It is
2695 emitted when the QSessionManager wants the application to commit all its
2698 Usually this means saving all open files, after getting permission from
2699 the user. Furthermore you may want to provide a means by which the user
2700 can cancel the shutdown.
2702 You should not exit the application within this signal. Instead,
2703 the session manager may or may not do this afterwards, depending on the
2706 \warning Within this signal, no user interaction is possible, \e
2707 unless you ask the \a manager for explicit permission. See
2708 QSessionManager::allowsInteraction() and
2709 QSessionManager::allowsErrorInteraction() for details and example
2712 \note You should use Qt::DirectConnection when connecting to this signal.
2714 \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
2718 This function deals with \l{Session Management}{session management}. It is
2719 invoked when the QSessionManager wants the application to commit all its
2722 Usually this means saving all open files, after getting permission from the
2723 user. Furthermore you may want to provide a means by which the user can
2724 cancel the shutdown.
2726 You should not exit the application within this function. Instead, the
2727 session manager may or may not do this afterwards, depending on the
2730 \warning Within this function, no user interaction is possible, \e
2731 unless you ask the \a manager for explicit permission. See
2732 QSessionManager::allowsInteraction() and
2733 QSessionManager::allowsErrorInteraction() for details and example
2736 The default implementation requests interaction and sends a close event to
2737 all visible top-level widgets. If any event was rejected, the shutdown is
2740 \note The default implementation emits the commitDataRequest() signal,
2741 hence commitDataRequest() should be emitted when commitData() is
2744 \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
2746 #ifndef QT_NO_SESSIONMANAGER
2747 void QApplication::commitData(QSessionManager& manager )
2749 emit commitDataRequest(manager);
2750 if (manager.allowsInteraction()) {
2752 QWidgetList list = QApplication::topLevelWidgets();
2753 bool cancelled = false;
2754 for (int i = 0; !cancelled && i < list.size(); ++i) {
2755 QWidget* w = list.at(i);
2756 if (w->isVisible() && !done.contains(w)) {
2757 cancelled = !w->close();
2760 list = QApplication::topLevelWidgets();
2771 \fn void QApplication::saveStateRequest(QSessionManager &manager)
2773 This signal deals with \l{Session Management}{session management}. It is
2774 invoked when the \l{QSessionManager}{session manager} wants the application
2775 to preserve its state for a future session.
2777 For example, a text editor would create a temporary file that includes the
2778 current contents of its edit buffers, the location of the cursor and other
2779 aspects of the current editing session.
2781 You should never exit the application within this signal. Instead, the
2782 session manager may or may not do this afterwards, depending on the
2783 context. Futhermore, most session managers will very likely request a saved
2784 state immediately after the application has been started. This permits the
2785 session manager to learn about the application's restart policy.
2787 \warning Within this function, no user interaction is possible, \e
2788 unless you ask the \a manager for explicit permission. See
2789 QSessionManager::allowsInteraction() and
2790 QSessionManager::allowsErrorInteraction() for details.
2792 \note You should use Qt::DirectConnection when connecting to this signal.
2794 \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
2798 This function deals with \l{Session Management}{session management}. It is
2799 invoked when the \l{QSessionManager}{session manager} wants the application
2800 to preserve its state for a future session.
2802 For example, a text editor would create a temporary file that includes the
2803 current contents of its edit buffers, the location of the cursor and other
2804 aspects of the current editing session.
2806 You should never exit the application within this function. Instead, the
2807 session manager may or may not do this afterwards, depending on the
2808 context. Futhermore, most session managers will very likely request a saved
2809 state immediately after the application has been started. This permits the
2810 session manager to learn about the application's restart policy.
2812 \warning Within this function, no user interaction is possible, \e
2813 unless you ask the \a manager for explicit permission. See
2814 QSessionManager::allowsInteraction() and
2815 QSessionManager::allowsErrorInteraction() for details.
2817 \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
2820 void QApplication::saveState(QSessionManager &manager)
2822 emit saveStateRequest(manager);
2824 #endif //QT_NO_SESSIONMANAGER
2826 Sets the time after which a drag should start to \a ms ms.
2831 void QApplication::setStartDragTime(int ms)
2837 \property QApplication::startDragTime
2838 \brief the time in milliseconds that a mouse button must be held down
2839 before a drag and drop operation will begin
2841 If you support drag and drop in your application, and want to start a drag
2842 and drop operation after the user has held down a mouse button for a
2843 certain amount of time, you should use this property's value as the delay.
2845 Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for
2848 The default value is 500 ms.
2850 \sa startDragDistance(), {Drag and Drop}
2853 int QApplication::startDragTime()
2855 return qApp->styleHints()->startDragTime();
2859 Sets the distance after which a drag should start to \a l pixels.
2861 \sa startDragDistance()
2864 void QApplication::setStartDragDistance(int l)
2870 \property QApplication::startDragDistance
2872 If you support drag and drop in your application, and want to start a drag
2873 and drop operation after the user has moved the cursor a certain distance
2874 with a button held down, you should use this property's value as the
2875 minimum distance required.
2877 For example, if the mouse position of the click is stored in \c startPos
2878 and the current position (e.g. in the mouse move event) is \c currentPos,
2879 you can find out if a drag should be started with code like this:
2881 \snippet code/src_gui_kernel_qapplication.cpp 7
2883 Qt uses this value internally, e.g. in QFileDialog.
2885 The default value is 4 pixels.
2887 \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop}
2890 int QApplication::startDragDistance()
2892 return qApp->styleHints()->startDragDistance();
2896 Enters the main event loop and waits until exit() is called, then returns
2897 the value that was set to exit() (which is 0 if exit() is called via
2900 It is necessary to call this function to start event handling. The main
2901 event loop receives events from the window system and dispatches these to
2902 the application widgets.
2904 Generally, no user interaction can take place before calling exec(). As a
2905 special case, modal widgets like QMessageBox can be used before calling
2906 exec(), because modal widgets call exec() to start a local event loop.
2908 To make your application perform idle processing, i.e., executing a special
2909 function whenever there are no pending events, use a QTimer with 0 timeout.
2910 More advanced idle processing schemes can be achieved using processEvents().
2912 We recommend that you connect clean-up code to the
2913 \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
2914 application's \c{main()} function. This is because, on some platforms the
2915 QApplication::exec() call may not return. For example, on the Windows
2916 platform, when the user logs off, the system terminates the process after Qt
2917 closes all top-level windows. Hence, there is \e{no guarantee} that the
2918 application will have time to exit its event loop and execute code at the
2919 end of the \c{main()} function, after the QApplication::exec() call.
2921 \sa quitOnLastWindowClosed, quit(), exit(), processEvents(),
2922 QCoreApplication::exec()
2924 int QApplication::exec()
2926 #ifndef QT_NO_ACCESSIBILITY
2927 QAccessible::setRootObject(qApp);
2929 return QGuiApplication::exec();
2932 bool QApplicationPrivate::shouldQuit()
2934 /* if there is no non-withdrawn primary window left (except
2935 the ones without QuitOnClose), we emit the lastWindowClosed
2937 QWidgetList list = QApplication::topLevelWidgets();
2938 for (int i = 0; i < list.size(); ++i) {
2939 QWidget *w = list.at(i);
2940 if (w->isVisible() && !w->parentWidget() && w->testAttribute(Qt::WA_QuitOnClose))
2943 return QGuiApplicationPrivate::shouldQuit();
2946 static inline void closeAllPopups()
2948 // Close all popups: In case some popup refuses to close,
2949 // we give up after 1024 attempts (to avoid an infinite loop).
2952 while ((popup = QApplication::activePopupWidget()) && maxiter--)
2958 bool QApplication::notify(QObject *receiver, QEvent *e)
2961 // no events are delivered after ~QCoreApplication() has started
2962 if (QApplicationPrivate::is_app_closing)
2965 if (receiver == 0) { // serious error
2966 qWarning("QApplication::notify: Unexpected null receiver");
2971 d->checkReceiverThread(receiver);
2974 if (receiver->isWindowType())
2975 QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(static_cast<QWindow *>(receiver), e);
2977 // capture the current mouse/keyboard state
2978 if(e->spontaneous()) {
2979 if (e->type() == QEvent::MouseButtonPress
2980 || e->type() == QEvent::MouseButtonRelease) {
2981 QMouseEvent *me = static_cast<QMouseEvent*>(e);
2982 if(me->type() == QEvent::MouseButtonPress)
2983 QApplicationPrivate::mouse_buttons |= me->button();
2985 QApplicationPrivate::mouse_buttons &= ~me->button();
2989 #ifndef QT_NO_GESTURES
2990 // walk through parents and check for gestures
2991 if (d->gestureManager) {
2992 switch (e->type()) {
2994 case QEvent::MetaCall:
2995 case QEvent::DeferredDelete:
2996 case QEvent::DragEnter: case QEvent::DragMove: case QEvent::DragLeave:
2997 case QEvent::Drop: case QEvent::DragResponse:
2998 case QEvent::ChildAdded: case QEvent::ChildPolished:
2999 case QEvent::ChildRemoved:
3000 case QEvent::UpdateRequest:
3001 case QEvent::UpdateLater:
3002 case QEvent::LocaleChange:
3004 case QEvent::IconDrag:
3005 case QEvent::StyleChange:
3006 case QEvent::GraphicsSceneDragEnter:
3007 case QEvent::GraphicsSceneDragMove:
3008 case QEvent::GraphicsSceneDragLeave:
3009 case QEvent::GraphicsSceneDrop:
3010 case QEvent::DynamicPropertyChange:
3011 case QEvent::NetworkReplyUpdated:
3014 if (receiver->isWidgetType()) {
3015 if (d->gestureManager->filterEvent(static_cast<QWidget *>(receiver), e))
3018 // a special case for events that go to QGesture objects.
3019 // We pass the object to the gesture manager and it'll figure
3020 // out if it's QGesture or not.
3021 if (d->gestureManager->filterEvent(receiver, e))
3026 #endif // QT_NO_GESTURES
3028 switch (e->type()) {
3029 case QEvent::ApplicationDeactivate:
3030 // Close all popups (triggers when switching applications
3031 // by pressing ALT-TAB on Windows, which is not receive as key event.
3034 case QEvent::Wheel: // User input and window activation makes tooltips sleep
3035 case QEvent::ActivationChange:
3036 case QEvent::KeyPress:
3037 case QEvent::KeyRelease:
3038 case QEvent::FocusOut:
3039 case QEvent::FocusIn:
3040 case QEvent::MouseButtonPress:
3041 case QEvent::MouseButtonRelease:
3042 case QEvent::MouseButtonDblClick:
3043 d->toolTipFallAsleep.stop();
3046 d->toolTipWakeUp.stop();
3052 if (!receiver->isWidgetType()) {
3053 res = d->notify_helper(receiver, e);
3054 } else switch (e->type()) {
3055 case QEvent::ShortcutOverride:
3056 case QEvent::KeyPress:
3057 case QEvent::KeyRelease:
3059 bool isWidget = receiver->isWidgetType();
3060 bool isGraphicsWidget = false;
3061 #ifndef QT_NO_GRAPHICSVIEW
3062 isGraphicsWidget = !isWidget && qobject_cast<QGraphicsWidget *>(receiver);
3064 if (!isWidget && !isGraphicsWidget) {
3065 res = d->notify_helper(receiver, e);
3069 QKeyEvent* key = static_cast<QKeyEvent*>(e);
3070 if (key->type()==QEvent::KeyPress) {
3071 #ifndef QT_NO_SHORTCUT
3072 // Try looking for a Shortcut before sending key events
3073 if ((res = qApp->d_func()->shortcutMap.tryShortcutEvent(receiver, key)))
3076 qt_in_tab_key_event = (key->key() == Qt::Key_Backtab
3077 || key->key() == Qt::Key_Tab
3078 || key->key() == Qt::Key_Left
3079 || key->key() == Qt::Key_Up
3080 || key->key() == Qt::Key_Right
3081 || key->key() == Qt::Key_Down);
3083 bool def = key->isAccepted();
3084 QPointer<QObject> pr = receiver;
3090 res = d->notify_helper(receiver, e);
3091 QWidget *w = isWidget ? static_cast<QWidget *>(receiver) : 0;
3092 #ifndef QT_NO_GRAPHICSVIEW
3093 QGraphicsWidget *gw = isGraphicsWidget ? static_cast<QGraphicsWidget *>(receiver) : 0;
3096 if ((res && key->isAccepted())
3098 QLineEdit will emit a signal on Key_Return, but
3099 ignore the event, and sometimes the connected
3100 slot deletes the QLineEdit (common in itemview
3101 delegates), so we have to check if the widget
3102 was destroyed even if the event was ignored (to
3105 note that we don't have to reset pw while
3106 propagating (because the original receiver will
3107 be destroyed if one of its ancestors is)
3110 || (isWidget && (w->isWindow() || !w->parentWidget()))
3111 #ifndef QT_NO_GRAPHICSVIEW
3112 || (isGraphicsWidget && (gw->isWindow() || !gw->parentWidget()))
3118 #ifndef QT_NO_GRAPHICSVIEW
3119 receiver = w ? (QObject *)w->parentWidget() : (QObject *)gw->parentWidget();
3121 receiver = w->parentWidget();
3124 qt_in_tab_key_event = false;
3127 case QEvent::MouseButtonPress:
3128 case QEvent::MouseButtonRelease:
3129 case QEvent::MouseButtonDblClick:
3130 case QEvent::MouseMove:
3132 QWidget* w = static_cast<QWidget *>(receiver);
3134 QMouseEvent* mouse = static_cast<QMouseEvent*>(e);
3135 QPoint relpos = mouse->pos();
3137 if (e->spontaneous()) {
3139 if (e->type() == QEvent::MouseButtonPress) {
3140 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3142 Qt::MouseFocusReason);
3145 // ### Qt 5 These dynamic tool tips should be an OPT-IN feature. Some platforms
3146 // like Mac OS X (probably others too), can optimize their views by not
3147 // dispatching mouse move events. We have attributes to control hover,
3148 // and mouse tracking, but as long as we are deciding to implement this
3149 // feature without choice of opting-in or out, you ALWAYS have to have
3150 // tracking enabled. Therefore, the other properties give a false sense of
3151 // performance enhancement.
3152 if (e->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3153 d->toolTipWidget = w;
3154 d->toolTipPos = relpos;
3155 d->toolTipGlobalPos = mouse->globalPos();
3156 d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive()?20:700, this);
3160 bool eventAccepted = mouse->isAccepted();
3162 QPointer<QWidget> pw = w;
3164 QMouseEvent me(mouse->type(), relpos, mouse->windowPos(), mouse->globalPos(), mouse->button(), mouse->buttons(),
3165 mouse->modifiers());
3166 me.spont = mouse->spontaneous();
3167 me.setTimestamp(mouse->timestamp());
3168 // throw away any mouse-tracking-only mouse events
3169 if (!w->hasMouseTracking()
3170 && mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3171 // but still send them through all application event filters (normally done by notify_helper)
3172 for (int i = 0; d->extraData && i < d->extraData->eventFilters.size(); ++i) {
3173 register QObject *obj = d->extraData->eventFilters.at(i);
3176 if (obj->d_func()->threadData != w->d_func()->threadData) {
3177 qWarning("QApplication: Object event filter cannot be in a different thread.");
3180 if (obj->eventFilter(w, w == receiver ? mouse : &me))
3185 w->setAttribute(Qt::WA_NoMouseReplay, false);
3186 res = d->notify_helper(w, w == receiver ? mouse : &me);
3189 eventAccepted = (w == receiver ? mouse : &me)->isAccepted();
3190 if (res && eventAccepted)
3192 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3195 w = w->parentWidget();
3198 mouse->setAccepted(eventAccepted);
3200 if (e->type() == QEvent::MouseMove) {
3204 w = static_cast<QWidget *>(receiver);
3205 relpos = mouse->pos();
3206 QPoint diff = relpos - w->mapFromGlobal(d->hoverGlobalPos);
3208 if (w->testAttribute(Qt::WA_Hover) &&
3209 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
3210 QHoverEvent he(QEvent::HoverMove, relpos, relpos - diff, mouse->modifiers());
3211 d->notify_helper(w, &he);
3213 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3216 w = w->parentWidget();
3220 d->hoverGlobalPos = mouse->globalPos();
3223 #ifndef QT_NO_WHEELEVENT
3226 QWidget* w = static_cast<QWidget *>(receiver);
3227 QWheelEvent* wheel = static_cast<QWheelEvent*>(e);
3228 QPoint relpos = wheel->pos();
3229 bool eventAccepted = wheel->isAccepted();
3231 if (e->spontaneous()) {
3232 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3234 Qt::MouseFocusReason);
3238 QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
3239 wheel->modifiers());
3240 we.spont = wheel->spontaneous();
3241 res = d->notify_helper(w, w == receiver ? wheel : &we);
3242 eventAccepted = ((w == receiver) ? wheel : &we)->isAccepted();
3244 if ((res && eventAccepted)
3245 || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3249 w = w->parentWidget();
3251 wheel->setAccepted(eventAccepted);
3255 #ifndef QT_NO_CONTEXTMENU
3256 case QEvent::ContextMenu:
3258 QWidget* w = static_cast<QWidget *>(receiver);
3259 QContextMenuEvent *context = static_cast<QContextMenuEvent*>(e);
3260 QPoint relpos = context->pos();
3261 bool eventAccepted = context->isAccepted();
3263 QContextMenuEvent ce(context->reason(), relpos, context->globalPos(), context->modifiers());
3264 ce.spont = e->spontaneous();
3265 res = d->notify_helper(w, w == receiver ? context : &ce);
3266 eventAccepted = ((w == receiver) ? context : &ce)->isAccepted();
3269 if ((res && eventAccepted)
3270 || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3274 w = w->parentWidget();
3276 context->setAccepted(eventAccepted);
3279 #endif // QT_NO_CONTEXTMENU
3280 #ifndef QT_NO_TABLETEVENT
3281 case QEvent::TabletMove:
3282 case QEvent::TabletPress:
3283 case QEvent::TabletRelease:
3285 QWidget *w = static_cast<QWidget *>(receiver);
3286 QTabletEvent *tablet = static_cast<QTabletEvent*>(e);
3287 QPointF relpos = tablet->posF();
3288 bool eventAccepted = tablet->isAccepted();
3290 QTabletEvent te(tablet->type(), relpos, tablet->globalPosF(),
3291 tablet->device(), tablet->pointerType(),
3292 tablet->pressure(), tablet->xTilt(), tablet->yTilt(),
3293 tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
3294 tablet->modifiers(), tablet->uniqueId());
3295 te.spont = e->spontaneous();
3296 res = d->notify_helper(w, w == receiver ? tablet : &te);
3297 eventAccepted = ((w == receiver) ? tablet : &te)->isAccepted();
3299 if ((res && eventAccepted)
3301 || w->testAttribute(Qt::WA_NoMousePropagation))
3305 w = w->parentWidget();
3307 tablet->setAccepted(eventAccepted);
3308 qt_tabletChokeMouse = tablet->isAccepted();
3311 #endif // QT_NO_TABLETEVENT
3313 #if !defined(QT_NO_TOOLTIP) || !defined(QT_NO_WHATSTHIS)
3314 case QEvent::ToolTip:
3315 case QEvent::WhatsThis:
3316 case QEvent::QueryWhatsThis:
3318 QWidget* w = static_cast<QWidget *>(receiver);
3319 QHelpEvent *help = static_cast<QHelpEvent*>(e);
3320 QPoint relpos = help->pos();
3321 bool eventAccepted = help->isAccepted();
3323 QHelpEvent he(help->type(), relpos, help->globalPos());
3324 he.spont = e->spontaneous();
3325 res = d->notify_helper(w, w == receiver ? help : &he);
3327 eventAccepted = (w == receiver ? help : &he)->isAccepted();
3328 if ((res && eventAccepted) || w->isWindow())
3332 w = w->parentWidget();
3334 help->setAccepted(eventAccepted);
3338 #if !defined(QT_NO_STATUSTIP) || !defined(QT_NO_WHATSTHIS)
3339 case QEvent::StatusTip:
3340 case QEvent::WhatsThisClicked:
3342 QWidget *w = static_cast<QWidget *>(receiver);
3344 res = d->notify_helper(w, e);
3345 if ((res && e->isAccepted()) || w->isWindow())
3347 w = w->parentWidget();
3353 #ifndef QT_NO_DRAGANDDROP
3354 case QEvent::DragEnter: {
3355 QWidget* w = static_cast<QWidget *>(receiver);
3356 QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent *>(e);
3357 #ifndef QT_NO_GRAPHICSVIEW
3358 // QGraphicsProxyWidget handles its own propagation,
3359 // and we must not change QDragManagers currentTarget.
3360 QWExtra *extra = w->window()->d_func()->extra;
3361 if (extra && extra->proxyWidget) {
3362 res = d->notify_helper(w, dragEvent);
3367 if (w->isEnabled() && w->acceptDrops()) {
3368 res = d->notify_helper(w, dragEvent);
3369 if (res && dragEvent->isAccepted()) {
3370 QDragManager::self()->setCurrentTarget(w);
3376 dragEvent->p = w->mapToParent(dragEvent->p.toPoint());
3377 w = w->parentWidget();
3381 case QEvent::DragMove:
3383 case QEvent::DragLeave: {
3384 QWidget* w = static_cast<QWidget *>(receiver);
3385 #ifndef QT_NO_GRAPHICSVIEW
3386 // QGraphicsProxyWidget handles its own propagation,
3387 // and we must not change QDragManagers currentTarget.
3388 QWExtra *extra = w->window()->d_func()->extra;
3389 bool isProxyWidget = extra && extra->proxyWidget;
3392 w = qobject_cast<QWidget *>(QDragManager::self()->currentTarget());
3397 if (e->type() == QEvent::DragMove || e->type() == QEvent::Drop) {
3398 QDropEvent *dragEvent = static_cast<QDropEvent *>(e);
3399 QWidget *origReciver = static_cast<QWidget *>(receiver);
3400 while (origReciver && w != origReciver) {
3401 dragEvent->p = origReciver->mapToParent(dragEvent->p.toPoint());
3402 origReciver = origReciver->parentWidget();
3405 res = d->notify_helper(w, e);
3406 if (e->type() != QEvent::DragMove
3407 #ifndef QT_NO_GRAPHICSVIEW
3411 QDragManager::self()->setCurrentTarget(0, e->type() == QEvent::Drop);
3416 case QEvent::TouchUpdate:
3417 case QEvent::TouchEnd:
3419 QWidget *widget = static_cast<QWidget *>(receiver);
3420 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
3421 const bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
3423 touchEvent->setTarget(widget);
3424 touchEvent->setAccepted(acceptTouchEvents);
3426 res = acceptTouchEvents && d->notify_helper(widget, touchEvent);
3428 // If the touch event wasn't accepted, synthesize a mouse event and see if the widget wants it.
3429 if (!touchEvent->isAccepted())
3430 res = d->translateTouchToMouse(widget, touchEvent);
3434 case QEvent::TouchBegin:
3435 // Note: TouchUpdate and TouchEnd events are never propagated
3437 QWidget *widget = static_cast<QWidget *>(receiver);
3438 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
3439 bool eventAccepted = touchEvent->isAccepted();
3440 if (widget->testAttribute(Qt::WA_AcceptTouchEvents) && e->spontaneous()) {
3441 // give the widget focus if the focus policy allows it
3442 QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget,
3444 Qt::MouseFocusReason);
3448 // first, try to deliver the touch event
3449 bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
3450 touchEvent->setTarget(widget);
3451 touchEvent->setAccepted(acceptTouchEvents);
3452 QPointer<QWidget> p = widget;
3453 res = acceptTouchEvents && d->notify_helper(widget, touchEvent);
3455 // If the touch event wasn't accepted, synthesize a mouse event and see if the widget wants it.
3456 if (!touchEvent->isAccepted()) {
3457 res = d->translateTouchToMouse(widget, touchEvent);
3458 eventAccepted = touchEvent->isAccepted();
3463 eventAccepted = touchEvent->isAccepted();
3465 // widget was deleted
3468 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
3470 touchEvent->spont = false;
3471 if (res && eventAccepted) {
3472 // the first widget to accept the TouchBegin gets an implicit grab.
3473 for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
3474 const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i);
3475 d->activeTouchPoints[QGuiApplicationPrivate::ActiveTouchPointsKey(touchEvent->device(), touchPoint.id())].target = widget;
3478 } else if (p.isNull() || widget->isWindow() || widget->testAttribute(Qt::WA_NoMousePropagation)) {
3481 QPoint offset = widget->pos();
3482 widget = widget->parentWidget();
3483 touchEvent->setTarget(widget);
3484 for (int i = 0; i < touchEvent->_touchPoints.size(); ++i) {
3485 QTouchEvent::TouchPoint &pt = touchEvent->_touchPoints[i];
3486 QRectF rect = pt.rect();
3487 rect.moveCenter(offset);
3489 pt.d->startPos = pt.startPos() + offset;
3490 pt.d->lastPos = pt.lastPos() + offset;
3494 touchEvent->setAccepted(eventAccepted);
3497 case QEvent::RequestSoftwareInputPanel:
3498 inputMethod()->show();
3500 case QEvent::CloseSoftwareInputPanel:
3501 inputMethod()->hide();
3504 #ifndef QT_NO_GESTURES
3505 case QEvent::NativeGesture:
3507 // only propagate the first gesture event (after the GID_BEGIN)
3508 QWidget *w = static_cast<QWidget *>(receiver);
3511 res = d->notify_helper(w, e);
3512 if ((res && e->isAccepted()) || w->isWindow())
3514 w = w->parentWidget();
3518 case QEvent::Gesture:
3519 case QEvent::GestureOverride:
3521 if (receiver->isWidgetType()) {
3522 QWidget *w = static_cast<QWidget *>(receiver);
3523 QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(e);
3524 QList<QGesture *> allGestures = gestureEvent->gestures();
3526 bool eventAccepted = gestureEvent->isAccepted();
3527 bool wasAccepted = eventAccepted;
3529 // send only gestures the widget expects
3530 QList<QGesture *> gestures;
3531 QWidgetPrivate *wd = w->d_func();
3532 for (int i = 0; i < allGestures.size();) {
3533 QGesture *g = allGestures.at(i);
3534 Qt::GestureType type = g->gestureType();
3535 QMap<Qt::GestureType, Qt::GestureFlags>::iterator contextit =
3536 wd->gestureContext.find(type);
3537 bool deliver = contextit != wd->gestureContext.end() &&
3538 (g->state() == Qt::GestureStarted || w == receiver ||
3539 (contextit.value() & Qt::ReceivePartialGestures));
3541 allGestures.removeAt(i);
3547 if (!gestures.isEmpty()) { // we have gestures for this w
3548 QGestureEvent ge(gestures);
3549 ge.t = gestureEvent->t;
3550 ge.spont = gestureEvent->spont;
3551 ge.m_accept = wasAccepted;
3552 ge.m_accepted = gestureEvent->m_accepted;
3553 res = d->notify_helper(w, &ge);
3554 gestureEvent->spont = false;
3555 eventAccepted = ge.isAccepted();
3556 for (int i = 0; i < gestures.size(); ++i) {
3557 QGesture *g = gestures.at(i);
3558 // Ignore res [event return value] because handling of multiple gestures
3559 // packed into a single QEvent depends on not consuming the event
3560 if (eventAccepted || ge.isAccepted(g)) {
3561 // if the gesture was accepted, mark the target widget for it
3562 gestureEvent->m_targetWidgets[g->gestureType()] = w;
3563 gestureEvent->setAccepted(g, true);
3565 // if the gesture was explicitly ignored by the application,
3566 // put it back so a parent can get it
3567 allGestures.append(g);
3571 if (allGestures.isEmpty()) // everything delivered
3575 w = w->parentWidget();
3577 foreach (QGesture *g, allGestures)
3578 gestureEvent->setAccepted(g, false);
3579 gestureEvent->m_accept = false; // to make sure we check individual gestures
3581 res = d->notify_helper(receiver, e);
3585 #endif // QT_NO_GESTURES
3587 res = d->notify_helper(receiver, e);
3594 bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
3596 // send to all application event filters
3597 if (sendThroughApplicationEventFilters(receiver, e))
3600 if (receiver->isWidgetType()) {
3601 QWidget *widget = static_cast<QWidget *>(receiver);
3603 #if !defined(Q_OS_WINCE) || (defined(GWES_ICONCURS) && !defined(QT_NO_CURSOR))
3604 // toggle HasMouse widget state on enter and leave
3605 if ((e->type() == QEvent::Enter || e->type() == QEvent::DragEnter) &&
3606 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == widget->window()))
3607 widget->setAttribute(Qt::WA_UnderMouse, true);
3608 else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave)
3609 widget->setAttribute(Qt::WA_UnderMouse, false);
3612 if (QLayout *layout=widget->d_func()->layout) {
3613 layout->widgetEvent(e);
3617 // send to all receiver event filters
3618 if (sendThroughObjectEventFilters(receiver, e))
3621 // deliver the event
3622 bool consumed = receiver->event(e);
3627 bool QApplicationPrivate::inPopupMode()
3629 return QApplicationPrivate::popupWidgets != 0;
3632 #ifdef QT_KEYPAD_NAVIGATION
3634 Sets the kind of focus navigation Qt should use to \a mode.
3636 This feature is available in Qt for Embedded Linux, and Windows CE
3639 \note On Windows CE this feature is disabled by default for touch device
3640 mkspecs. To enable keypad navigation, build Qt with
3641 QT_KEYPAD_NAVIGATION defined.
3645 \sa keypadNavigationEnabled()
3647 void QApplication::setNavigationMode(Qt::NavigationMode mode)
3649 QApplicationPrivate::navigationMode = mode;
3653 Returns what kind of focus navigation Qt is using.
3655 This feature is available in Qt for Embedded Linux, and Windows CE only.
3657 \note On Windows CE this feature is disabled by default for touch device
3658 mkspecs. To enable keypad navigation, build Qt with
3659 QT_KEYPAD_NAVIGATION defined.
3663 \sa keypadNavigationEnabled()
3665 Qt::NavigationMode QApplication::navigationMode()
3667 return QApplicationPrivate::navigationMode;
3671 Sets whether Qt should use focus navigation suitable for use with a
3674 This feature is available in Qt for Embedded Linux, and Windows CE only.
3676 \note On Windows CE this feature is disabled by default for touch device
3677 mkspecs. To enable keypad navigation, build Qt with
3678 QT_KEYPAD_NAVIGATION defined.
3682 \sa setNavigationMode()
3684 void QApplication::setKeypadNavigationEnabled(bool enable)
3687 QApplication::setNavigationMode(Qt::NavigationModeKeypadTabOrder);
3689 QApplication::setNavigationMode(Qt::NavigationModeNone);
3694 Returns true if Qt is set to use keypad navigation; otherwise returns
3695 false. The default value is false.
3697 This feature is available in Qt for Embedded Linux, and Windows CE only.
3699 \note On Windows CE this feature is disabled by default for touch device
3700 mkspecs. To enable keypad navigation, build Qt with
3701 QT_KEYPAD_NAVIGATION defined.
3705 \sa navigationMode()
3707 bool QApplication::keypadNavigationEnabled()
3709 return QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadTabOrder ||
3710 QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadDirectional;
3715 \fn void QApplication::alert(QWidget *widget, int msec)
3718 Causes an alert to be shown for \a widget if the window is not the active
3719 window. The alert is shown for \a msec miliseconds. If \a msec is zero (the
3720 default), then the alert is shown indefinitely until the window becomes
3723 Currently this function does nothing on Qt for Embedded Linux.
3725 On Mac OS X, this works more at the application level and will cause the
3726 application icon to bounce in the dock.
3728 On Windows, this causes the window's taskbar entry to flash for a time. If
3729 \a msec is zero, the flashing will stop and the taskbar entry will turn a
3730 different color (currently orange).
3732 On X11, this will cause the window to be marked as "demands attention", the
3733 window must not be hidden (i.e. not have hide() called on it, but be
3734 visible in some sort of way) in order for this to work.
3738 \property QApplication::cursorFlashTime
3739 \brief the text cursor's flash (blink) time in milliseconds
3741 The flash time is the time required to display, invert and restore the
3742 caret display. Usually the text cursor is displayed for half the cursor
3743 flash time, then hidden for the same amount of time, but this may vary.
3745 The default value on X11 is 1000 milliseconds. On Windows, the
3746 \uicontrol{Control Panel} value is used and setting this property sets the cursor
3747 flash time for all applications.
3749 We recommend that widgets do not cache this value as it may change at any
3750 time if the user changes the global desktop settings.
3752 void QApplication::setCursorFlashTime(int msecs)
3757 int QApplication::cursorFlashTime()
3759 return qApp->styleHints()->cursorFlashTime();
3763 \property QApplication::doubleClickInterval
3764 \brief the time limit in milliseconds that distinguishes a double click
3765 from two consecutive mouse clicks
3767 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
3768 operating system's value is used.
3770 Setting the interval is not supported anymore in Qt 5.
3772 void QApplication::setDoubleClickInterval(int ms)
3777 int QApplication::doubleClickInterval()
3779 return qApp->styleHints()->mouseDoubleClickInterval();
3783 \fn QApplication::keyboardInputDirection()
3787 Returns the current keyboard input direction. Replaced with QInputPanel::inputDirection()
3788 \sa QInputPanel::inputDirection()
3792 \property QApplication::keyboardInputInterval
3793 \brief the time limit in milliseconds that distinguishes a key press
3794 from two consecutive key presses
3797 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
3798 operating system's value is used.
3800 void QApplication::setKeyboardInputInterval(int ms)
3805 int QApplication::keyboardInputInterval()
3807 return qApp->styleHints()->keyboardInputInterval();
3811 \property QApplication::wheelScrollLines
3812 \brief the number of lines to scroll a widget, when the
3813 mouse wheel is rotated.
3815 If the value exceeds the widget's number of visible lines, the widget
3816 should interpret the scroll operation as a single \e{page up} or
3817 \e{page down}. If the widget is an \l{QAbstractItemView}{item view class},
3818 then the result of scrolling one \e line depends on the setting of the
3819 widget's \l{QAbstractItemView::verticalScrollMode()}{scroll mode}. Scroll
3820 one \e line can mean \l{QAbstractItemView::ScrollPerItem}{scroll one item}
3821 or \l{QAbstractItemView::ScrollPerPixel}{scroll one pixel}.
3823 By default, this property has a value of 3.
3827 \fn void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
3829 Enables the UI effect \a effect if \a enable is true, otherwise the effect
3832 \note All effects are disabled on screens running at less than 16-bit color
3835 \sa isEffectEnabled(), Qt::UIEffect, setDesktopSettingsAware()
3839 \fn bool QApplication::isEffectEnabled(Qt::UIEffect effect)
3841 Returns true if \a effect is enabled; otherwise returns false.
3843 By default, Qt will try to use the desktop settings. To prevent this, call
3844 setDesktopSettingsAware(false).
3846 \note All effects are disabled on screens running at less than 16-bit color
3849 \sa setEffectEnabled(), Qt::UIEffect
3853 \fn void QApplication::beep()
3855 Sounds the bell, using the default volume and sound. The function is \e not
3856 available in Qt for Embedded Linux.
3861 \relates QApplication
3863 A global pointer referring to the unique application object. It is
3864 equivalent to the pointer returned by the QCoreApplication::instance()
3865 function except that, in GUI applications, it is a pointer to a
3866 QApplication instance.
3868 Only one application object can be created.
3870 \sa QCoreApplication::instance()
3874 \fn QLocale QApplication::keyboardInputLocale()
3878 Returns the current keyboard input locale. Replaced with QInputMethod::locale()
3881 bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
3883 return QGuiApplication::sendSpontaneousEvent(receiver, event);
3887 void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget,
3888 Qt::FocusPolicy focusPolicy,
3889 Qt::FocusReason focusReason)
3891 QWidget *focusWidget = widget;
3892 while (focusWidget) {
3893 if (focusWidget->isEnabled()
3894 && QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) {
3895 focusWidget->setFocus(focusReason);
3898 if (focusWidget->isWindow())
3900 focusWidget = focusWidget->parentWidget();
3904 bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy)
3907 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
3908 f = f->d_func()->extra->focus_proxy;
3910 if ((w->focusPolicy() & policy) != policy)
3912 if (w != f && (f->focusPolicy() & policy) != policy)
3917 void QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent)
3919 for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
3920 QTouchEvent::TouchPoint &touchPoint = touchEvent->_touchPoints[i];
3922 // preserve the sub-pixel resolution
3923 QRectF rect = touchPoint.screenRect();
3924 const QPointF screenPos = rect.center();
3925 const QPointF delta = screenPos - screenPos.toPoint();
3927 rect.moveCenter(widget->mapFromGlobal(screenPos.toPoint()) + delta);
3928 touchPoint.d->rect = rect;
3929 touchPoint.d->startPos = widget->mapFromGlobal(touchPoint.startScreenPos().toPoint()) + delta;
3930 touchPoint.d->lastPos = widget->mapFromGlobal(touchPoint.lastScreenPos().toPoint()) + delta;
3934 void QApplicationPrivate::initializeMultitouch()
3936 initializeMultitouch_sys();
3939 void QApplicationPrivate::cleanupMultitouch()
3941 cleanupMultitouch_sys();
3944 QWidget *QApplicationPrivate::findClosestTouchPointTarget(QTouchDevice *device, const QPointF &screenPos)
3946 int closestTouchPointId = -1;
3947 QObject *closestTarget = 0;
3948 qreal closestDistance = qreal(0.);
3949 QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it = activeTouchPoints.constBegin(),
3950 ite = activeTouchPoints.constEnd();
3952 if (it.key().device == device) {
3953 const QTouchEvent::TouchPoint &touchPoint = it->touchPoint;
3954 qreal dx = screenPos.x() - touchPoint.screenPos().x();
3955 qreal dy = screenPos.y() - touchPoint.screenPos().y();
3956 qreal distance = dx * dx + dy * dy;
3957 if (closestTouchPointId == -1 || distance < closestDistance) {
3958 closestTouchPointId = touchPoint.id();
3959 closestDistance = distance;
3960 closestTarget = it.value().target.data();
3965 return static_cast<QWidget *>(closestTarget);
3968 class WidgetAttributeSaver
3971 explicit WidgetAttributeSaver(QWidget *widget, Qt::WidgetAttribute attribute, bool forcedValue)
3973 m_attribute(attribute),
3974 m_savedValue(widget->testAttribute(attribute))
3976 widget->setAttribute(attribute, forcedValue);
3979 ~WidgetAttributeSaver()
3981 m_widget->setAttribute(m_attribute, m_savedValue);
3985 QWidget * const m_widget;
3986 const Qt::WidgetAttribute m_attribute;
3987 const bool m_savedValue;
3990 bool QApplicationPrivate::translateTouchToMouse(QWidget *widget, QTouchEvent *event)
3994 // Check if the platform wants synthesized mouse events.
3995 if (!QGuiApplicationPrivate::platformIntegration()->styleHint(QPlatformIntegration::SynthesizeMouseFromTouchEvents).toBool())
3998 Q_FOREACH (const QTouchEvent::TouchPoint &p, event->touchPoints()) {
3999 const QEvent::Type eventType = (p.state() & Qt::TouchPointPressed) ? QEvent::MouseButtonPress
4000 : (p.state() & Qt::TouchPointReleased) ? QEvent::MouseButtonRelease
4001 : (p.state() & Qt::TouchPointMoved) ? QEvent::MouseMove
4004 if (eventType == QEvent::None)
4007 const QPoint pos = widget->mapFromGlobal(p.screenPos().toPoint());
4009 QMouseEvent mouseEvent(eventType, pos,
4010 Qt::LeftButton, Qt::LeftButton,
4011 event->modifiers());
4012 mouseEvent.setAccepted(true);
4013 mouseEvent.setTimestamp(event->timestamp());
4015 // Make sure our synthesized mouse event doesn't propagate
4016 // we want to control the propagation ourself to get a chance to
4017 // deliver a proper touch event higher up in the hierarchy if that
4018 // widget doesn't pick up the mouse event either.
4019 WidgetAttributeSaver saver(widget, Qt::WA_NoMousePropagation, true);
4021 // Note it has to be a spontaneous event if we want the focus management
4022 // and input method support to behave properly. Quite some of the code
4023 // related to those aspect check for the spontaneous flag.
4024 const bool res = q->sendSpontaneousEvent(widget, &mouseEvent);
4025 event->setAccepted(mouseEvent.isAccepted());
4027 if (mouseEvent.isAccepted())
4034 void QApplicationPrivate::translateRawTouchEvent(QWidget *window,
4035 QTouchDevice *device,
4036 const QList<QTouchEvent::TouchPoint> &touchPoints,
4039 QApplicationPrivate *d = self;
4040 typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
4041 QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents;
4043 for (int i = 0; i < touchPoints.count(); ++i) {
4044 QTouchEvent::TouchPoint touchPoint = touchPoints.at(i);
4045 // explicitly detach from the original touch point that we got, so even
4046 // if the touchpoint structs are reused, we will make a copy that we'll
4047 // deliver to the user (which might want to store the struct for later use).
4048 touchPoint.d = touchPoint.d->detach();
4051 QPointer<QObject> target;
4052 ActiveTouchPointsKey touchInfoKey(device, touchPoint.id());
4053 ActiveTouchPointsValue &touchInfo = d->activeTouchPoints[touchInfoKey];
4054 if (touchPoint.state() == Qt::TouchPointPressed) {
4055 if (device->type() == QTouchDevice::TouchPad) {
4056 // on touch-pads, send all touch points to the same widget
4057 target = d->activeTouchPoints.isEmpty()
4058 ? QPointer<QObject>()
4059 : d->activeTouchPoints.constBegin().value().target;
4063 // determine which widget this event will go to
4065 window = QApplication::topLevelAt(touchPoint.screenPos().toPoint());
4068 target = window->childAt(window->mapFromGlobal(touchPoint.screenPos().toPoint()));
4073 if (device->type() == QTouchDevice::TouchScreen) {
4074 QWidget *closestWidget = d->findClosestTouchPointTarget(device, touchPoint.screenPos());
4075 QWidget *widget = static_cast<QWidget *>(target.data());
4077 && (widget->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget))) {
4078 target = closestWidget;
4082 touchInfo.target = target;
4084 target = touchInfo.target;
4088 Q_ASSERT(target.data() != 0);
4090 StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[static_cast<QWidget *>(target.data())];
4091 maskAndPoints.first |= touchPoint.state();
4092 maskAndPoints.second.append(touchPoint);
4095 if (widgetsNeedingEvents.isEmpty())
4098 QHash<QWidget *, StatesAndTouchPoints>::ConstIterator it = widgetsNeedingEvents.constBegin();
4099 const QHash<QWidget *, StatesAndTouchPoints>::ConstIterator end = widgetsNeedingEvents.constEnd();
4100 for (; it != end; ++it) {
4101 QWidget *widget = it.key();
4102 if (!QApplicationPrivate::tryModalHelper(widget, 0))
4105 QEvent::Type eventType;
4106 switch (it.value().first) {
4107 case Qt::TouchPointPressed:
4108 eventType = QEvent::TouchBegin;
4110 case Qt::TouchPointReleased:
4111 eventType = QEvent::TouchEnd;
4113 case Qt::TouchPointStationary:
4114 // don't send the event if nothing changed
4117 eventType = QEvent::TouchUpdate;
4121 QTouchEvent touchEvent(eventType,
4123 QApplication::keyboardModifiers(),
4126 updateTouchPointsForWidget(widget, &touchEvent);
4127 touchEvent.setTimestamp(timestamp);
4128 touchEvent.setWindow(window->windowHandle());
4129 touchEvent.setTarget(widget);
4131 switch (touchEvent.type()) {
4132 case QEvent::TouchBegin:
4134 // if the TouchBegin handler recurses, we assume that means the event
4135 // has been implicitly accepted and continue to send touch events
4136 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
4137 (void ) QApplication::sendSpontaneousEvent(widget, &touchEvent);
4141 if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent)) {
4142 if (touchEvent.type() == QEvent::TouchEnd)
4143 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, false);
4144 (void) QApplication::sendSpontaneousEvent(widget, &touchEvent);
4151 void QApplicationPrivate::translateTouchCancel(QTouchDevice *device, ulong timestamp)
4153 QTouchEvent touchEvent(QEvent::TouchCancel, device, QApplication::keyboardModifiers());
4154 touchEvent.setTimestamp(timestamp);
4155 QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it
4156 = self->activeTouchPoints.constBegin(), ite = self->activeTouchPoints.constEnd();
4157 QSet<QWidget *> widgetsNeedingCancel;
4159 QWidget *widget = static_cast<QWidget *>(it->target.data());
4161 widgetsNeedingCancel.insert(widget);
4164 for (QSet<QWidget *>::const_iterator widIt = widgetsNeedingCancel.constBegin(),
4165 widItEnd = widgetsNeedingCancel.constEnd(); widIt != widItEnd; ++widIt) {
4166 QWidget *widget = *widIt;
4167 touchEvent.setWindow(widget->windowHandle());
4168 touchEvent.setTarget(widget);
4169 QApplication::sendSpontaneousEvent(widget, &touchEvent);
4173 void QApplicationPrivate::notifyThemeChanged()
4175 QGuiApplicationPrivate::notifyThemeChanged();
4176 clearSystemPalette();
4177 initSystemPalette();
4180 #ifndef QT_NO_DRAGANDDROP
4181 void QApplicationPrivate::notifyDragStarted(const QDrag *drag)
4183 // Prevent pickMouseReceiver() from using the widget where the drag was started after a drag operation.
4184 QGuiApplicationPrivate::notifyDragStarted(drag);
4187 #endif // QT_NO_DRAGANDDROP
4189 #ifndef QT_NO_GESTURES
4190 QGestureManager* QGestureManager::instance()
4192 QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
4195 if (!qAppPriv->gestureManager)
4196 qAppPriv->gestureManager = new QGestureManager(qApp);
4197 return qAppPriv->gestureManager;
4199 #endif // QT_NO_GESTURES
4201 QPixmap QApplicationPrivate::applyQIconStyleHelper(QIcon::Mode mode, const QPixmap& base) const
4203 QStyleOption opt(0);
4204 opt.palette = QGuiApplication::palette();
4205 return QApplication::style()->generatedIconPixmap(mode, base, &opt);
4210 #include "moc_qapplication.cpp"