1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qplatformdefs.h"
43 #include "qabstracteventdispatcher.h"
44 #include "qaccessible.h"
45 #include "qapplication.h"
46 #include "qclipboard.h"
48 #include "qdesktopwidget.h"
52 #include "qfileinfo.h"
53 #include "qgraphicsscene.h"
57 #include "qsessionmanager.h"
59 #include "qstylefactory.h"
60 #include "qtextcodec.h"
61 #include "qtranslator.h"
64 #include "private/qdnd_p.h"
65 #include "private/qguiapplication_p.h"
66 #include "qcolormap.h"
68 #include "private/qstylesheetstyle_p.h"
69 #include "private/qstyle_p.h"
70 #include "qmessagebox.h"
71 #include "qwidgetwindow_qpa_p.h"
72 #include <QtWidgets/qgraphicsproxywidget.h>
73 #include <QtGui/qstylehints.h>
74 #include <QtGui/qinputmethod.h>
75 #include <qpa/qplatformtheme.h>
77 #include "private/qkeymapper_p.h"
80 #include <private/qthread_p.h>
82 #include <private/qfont_p.h>
86 #include "qapplication_p.h"
87 #include "private/qevent_p.h"
88 #include "qwidget_p.h"
90 #include "qapplication.h"
93 #include "private/qgesturemanager_p.h"
94 #include "private/qguiapplication_p.h"
95 #include <qpa/qplatformfontdatabase.h>
101 #include "qdatetime.h"
102 extern bool qt_wince_is_smartphone(); //qguifunctions_wince.cpp
103 extern bool qt_wince_is_mobile(); //qguifunctions_wince.cpp
104 extern bool qt_wince_is_pocket_pc(); //qguifunctions_wince.cpp
107 #include "qdatetime.h"
109 //#define ALIEN_DEBUG
111 static void initResources()
113 #if defined(Q_OS_WINCE)
114 Q_INIT_RESOURCE_EXTERN(qstyle_wince)
115 Q_INIT_RESOURCE(qstyle_wince);
117 Q_INIT_RESOURCE_EXTERN(qstyle)
118 Q_INIT_RESOURCE(qstyle);
120 Q_INIT_RESOURCE_EXTERN(qmessagebox)
121 Q_INIT_RESOURCE(qmessagebox);
127 Q_CORE_EXPORT void qt_call_post_routines();
129 QApplicationPrivate *QApplicationPrivate::self = 0;
131 static void initSystemPalette()
133 if (!QApplicationPrivate::sys_pal) {
134 QPalette defaultPlatte;
135 if (QApplicationPrivate::app_style)
136 defaultPlatte = QApplicationPrivate::app_style->standardPalette();
137 if (const QPalette *themePalette = QGuiApplicationPrivate::platformTheme()->palette()) {
138 QApplicationPrivate::setSystemPalette(themePalette->resolve(defaultPlatte));
139 QApplicationPrivate::initializeWidgetPaletteHash();
141 QApplicationPrivate::setSystemPalette(defaultPlatte);
146 static void clearSystemPalette()
148 delete QApplicationPrivate::sys_pal;
149 QApplicationPrivate::sys_pal = 0;
153 int QApplicationPrivate::autoMaximizeThreshold = -1;
154 bool QApplicationPrivate::autoSipEnabled = false;
156 bool QApplicationPrivate::autoSipEnabled = true;
159 QApplicationPrivate::QApplicationPrivate(int &argc, char **argv, QApplication::Type type, int flags)
160 : QApplicationPrivateBase(argc, argv, flags)
162 application_type = type;
164 #ifndef QT_NO_SESSIONMANAGER
165 is_session_restored = false;
168 #ifndef QT_NO_GESTURES
171 #endif // QT_NO_GESTURES
177 QApplicationPrivate::~QApplicationPrivate()
185 \brief The QApplication class manages the GUI application's control
186 flow and main settings.
190 QApplication specializes QGuiApplication with some functionality needed
191 for QWidget-based applications. It handles widget specific initialization,
192 finalization, and provides session management.
194 For any GUI application using Qt, there is precisely \b one QApplication
195 object, no matter whether the application has 0, 1, 2 or more windows at
196 any given time. For non-QWidget based Qt applications, use QGuiApplication instead,
197 as it does not depend on the \l QtWidgets library.
199 The QApplication object is accessible through the instance() function that
200 returns a pointer equivalent to the global qApp pointer.
202 QApplication's main areas of responsibility are:
204 \li It initializes the application with the user's desktop settings
205 such as palette(), font() and doubleClickInterval(). It keeps
206 track of these properties in case the user changes the desktop
207 globally, for example through some kind of control panel.
209 \li It performs event handling, meaning that it receives events
210 from the underlying window system and dispatches them to the
211 relevant widgets. By using sendEvent() and postEvent() you can
212 send your own events to widgets.
214 \li It parses common command line arguments and sets its internal
215 state accordingly. See the \l{QApplication::QApplication()}
216 {constructor documentation} below for more details.
218 \li It defines the application's look and feel, which is
219 encapsulated in a QStyle object. This can be changed at runtime
222 \li It specifies how the application is to allocate colors. See
223 setColorSpec() for details.
225 \li It provides localization of strings that are visible to the
226 user via translate().
228 \li It provides some magical objects like the desktop() and the
231 \li It knows about the application's windows. You can ask which
232 widget is at a certain position using widgetAt(), get a list of
233 topLevelWidgets() and closeAllWindows(), etc.
235 \li It manages the application's mouse cursor handling, see
238 \li It provides support for sophisticated \l{Session Management}
239 {session management}. This makes it possible for applications
240 to terminate gracefully when the user logs out, to cancel a
241 shutdown process if termination isn't possible and even to
242 preserve the entire application's state for a future session.
243 See isSessionRestored(), sessionId() and commitData() and
244 saveState() for details.
247 Since the QApplication object does so much initialization, it \e{must} be
248 created before any other objects related to the user interface are created.
249 QApplication also deals with common command line arguments. Hence, it is
250 usually a good idea to create it \e before any interpretation or
251 modification of \c argv is done in the application itself.
255 \li{2,1} Groups of functions
259 \li desktopSettingsAware(),
260 setDesktopSettingsAware(),
262 setCursorFlashTime(),
263 doubleClickInterval(),
264 setDoubleClickInterval(),
265 setKeyboardInputInterval(),
267 setWheelScrollLines(),
283 removePostedEvents(),
299 \li installTranslator(),
316 \li Advanced cursor handling
317 \li overrideCursor(),
319 restoreOverrideCursor().
322 \li Session management
323 \li isSessionRestored(),
330 \li closeAllWindows(),
336 \sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
340 \enum QApplication::ColorSpec
342 \value NormalColor the default color allocation policy
343 \value CustomColor the same as NormalColor for X11; allocates colors
344 to a palette on demand under Windows
345 \value ManyColor the right choice for applications that use thousands of
348 See setColorSpec() for full details.
352 \fn QWidget *QApplication::topLevelAt(const QPoint &point)
354 Returns the top-level widget at the given \a point; returns 0 if
355 there is no such widget.
359 \fn QWidget *QApplication::topLevelAt(int x, int y)
363 Returns the top-level widget at the point (\a{x}, \a{y}); returns
364 0 if there is no such widget.
369 The qt_init() and qt_cleanup() functions are implemented in the
370 qapplication_xyz.cpp file.
373 void qt_init(QApplicationPrivate *priv, int type
377 QStyle *QApplicationPrivate::app_style = 0; // default application style
378 QString QApplicationPrivate::styleOverride; // style override
380 #ifndef QT_NO_STYLE_STYLESHEET
381 QString QApplicationPrivate::styleSheet; // default application stylesheet
383 QPointer<QWidget> QApplicationPrivate::leaveAfterRelease = 0;
385 int QApplicationPrivate::app_cspec = QApplication::NormalColor;
387 QPalette *QApplicationPrivate::sys_pal = 0; // default system palette
388 QPalette *QApplicationPrivate::set_pal = 0; // default palette set by programmer
390 QFont *QApplicationPrivate::sys_font = 0; // default system font
391 QFont *QApplicationPrivate::set_font = 0; // default font set by programmer
393 QIcon *QApplicationPrivate::app_icon = 0;
394 QWidget *QApplicationPrivate::main_widget = 0; // main application widget
395 QWidget *QApplicationPrivate::focus_widget = 0; // has keyboard input focus
396 QWidget *QApplicationPrivate::hidden_focus_widget = 0; // will get keyboard input focus after show()
397 QWidget *QApplicationPrivate::active_window = 0; // toplevel with keyboard focus
398 #ifndef QT_NO_WHEELEVENT
399 int QApplicationPrivate::wheel_scroll_lines; // number of lines to scroll
401 bool Q_WIDGETS_EXPORT qt_tab_all_widgets = true;
402 bool qt_in_tab_key_event = false;
403 int qt_antialiasing_threshold = -1;
404 QSize QApplicationPrivate::app_strut = QSize(0,0); // no default application strut
405 int QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
406 bool QApplicationPrivate::widgetCount = false;
407 bool QApplicationPrivate::load_testability = false;
408 #ifdef QT_KEYPAD_NAVIGATION
409 Qt::NavigationMode QApplicationPrivate::navigationMode = Qt::NavigationModeKeypadTabOrder;
410 QWidget *QApplicationPrivate::oldEditFocus = 0;
413 bool qt_tabletChokeMouse = false;
415 inline bool QApplicationPrivate::isAlien(QWidget *widget)
417 return widget && !widget->isWindow();
420 // ######## move to QApplicationPrivate
421 // Default application palettes and fonts (per widget type)
422 Q_GLOBAL_STATIC(PaletteHash, app_palettes)
423 PaletteHash *qt_app_palettes_hash()
425 return app_palettes();
428 Q_GLOBAL_STATIC(FontHash, app_fonts)
429 FontHash *qt_app_fonts_hash()
434 QWidgetList *QApplicationPrivate::popupWidgets = 0; // has keyboard input focus
436 QDesktopWidget *qt_desktopWidget = 0; // root window widgets
441 void QApplicationPrivate::process_cmdline()
443 // process platform-indep command line
444 if (!qt_is_gui_used || !argc)
450 for (i=1; i<argc; i++) { // if you add anything here, modify QCoreApplication::arguments()
451 if (argv[i] && *argv[i] != '-') {
455 QByteArray arg = argv[i];
458 if (arg == "-qdevel" || arg == "-qdebug") {
460 } else if (arg.indexOf("-style=", 0) != -1) {
461 s = QString::fromLocal8Bit(arg.right(arg.length() - 7).toLower());
462 } else if (arg == "-style" && i < argc-1) {
463 s = QString::fromLocal8Bit(argv[++i]).toLower();
464 #ifndef QT_NO_SESSIONMANAGER
465 } else if (arg == "-session" && i < argc-1) {
467 if (argv[i] && *argv[i]) {
468 session_id = QString::fromLatin1(argv[i]);
469 int p = session_id.indexOf(QLatin1Char('_'));
471 session_key = session_id.mid(p +1);
472 session_id = session_id.left(p);
474 is_session_restored = true;
477 #ifndef QT_NO_STYLE_STYLESHEET
478 } else if (arg == "-stylesheet" && i < argc -1) {
479 styleSheet = QLatin1String("file:///");
480 styleSheet.append(QString::fromLocal8Bit(argv[++i]));
481 } else if (arg.indexOf("-stylesheet=") != -1) {
482 styleSheet = QLatin1String("file:///");
483 styleSheet.append(QString::fromLocal8Bit(arg.right(arg.length() - 12)));
485 } else if (qstrcmp(arg, "-widgetcount") == 0) {
487 } else if (qstrcmp(arg, "-testability") == 0) {
488 load_testability = true;
508 Initializes the window system and constructs an application object with
509 \a argc command line arguments in \a argv.
511 \warning The data referred to by \a argc and \a argv must stay valid for
512 the entire lifetime of the QApplication object. In addition, \a argc must
513 be greater than zero and \a argv must contain at least one valid character
516 The global \c qApp pointer refers to this application object. Only one
517 application object should be created.
519 This application object must be constructed before any \l{QPaintDevice}
520 {paint devices} (including widgets, pixmaps, bitmaps etc.).
522 \note \a argc and \a argv might be changed as Qt removes command line
523 arguments that it recognizes.
525 All Qt programs automatically support the following command line options:
527 \li -style= \e style, sets the application GUI style. Possible values
528 are \c motif, \c windows, and \c platinum. If you compiled Qt with
529 additional styles or have additional styles as plugins these will
530 be available to the \c -style command line option.
531 \li -style \e style, is the same as listed above.
532 \li -stylesheet= \e stylesheet, sets the application \l styleSheet. The
533 value must be a path to a file that contains the Style Sheet.
534 \note Relative URLs in the Style Sheet file are relative to the
535 Style Sheet file's path.
536 \li -stylesheet \e stylesheet, is the same as listed above.
537 \li -session= \e session, restores the application from an earlier
538 \l{Session Management}{session}.
539 \li -session \e session, is the same as listed above.
540 \li -widgetcount, prints debug message at the end about number of
541 widgets left undestroyed and maximum number of widgets existed at
543 \li -reverse, sets the application's layout direction to
545 \li -qmljsdebugger=, activates the QML/JS debugger with a specified port.
546 The value must be of format port:1234[,block], where block is optional
547 and will make the application wait until a debugger connects to it.
553 QApplication::QApplication(int &argc, char **argv, int _internal)
554 : QGuiApplication(*new QApplicationPrivate(argc, argv, GuiClient, _internal))
555 { Q_D(QApplication); d->construct(); }
559 Constructs an application object with \a argc command line arguments in
562 \warning The data referred to by \a argc and \a argv must stay valid for
563 the entire lifetime of the QApplication object. In addition, \a argc must
564 be greater than zero and \a argv must contain at least one valid character
567 The following example shows how to create an application that uses a
568 graphical interface when available.
572 \snippet code/src_gui_kernel_qapplication.cpp 0
575 QApplication::QApplication(int &argc, char **argv, bool GUIenabled , int _internal)
576 : QGuiApplication(*new QApplicationPrivate(argc, argv, GUIenabled ? GuiClient : Tty, _internal))
577 { Q_D(QApplication); d->construct();}
582 Constructs an application object with \a argc command line arguments in
585 \warning The data referred to by \a argc and \a argv must stay valid for
586 the entire lifetime of the QApplication object. In addition, \a argc must
587 be greater than zero and \a argv must contain at least one valid character
590 QApplication::QApplication(int &argc, char **argv, Type type , int _internal)
591 : QGuiApplication(*new QApplicationPrivate(argc, argv, type, _internal))
592 { Q_D(QApplication); d->construct(); }
597 void QApplicationPrivate::construct()
601 qt_is_gui_used = (application_type != QApplication::Tty);
604 // Must be called before initialize()
605 qt_init(this, application_type);
607 eventDispatcher->startingUp();
610 extern void qt_gui_eval_init(uint);
611 qt_gui_eval_init(application_type);
614 #ifndef QT_NO_LIBRARY
615 if(load_testability) {
616 QLibrary testLib(QLatin1String("qttestability"));
617 if (testLib.load()) {
618 typedef void (*TasInitialize)(void);
619 TasInitialize initFunction = (TasInitialize)testLib.resolve("qt_testability_init");
623 qCritical("Library qttestability resolve failed!");
626 qCritical("Library qttestability load failed!");
632 #ifndef QT_NO_STATEMACHINE
633 void qRegisterGuiStateMachine();
634 void qUnregisterGuiStateMachine();
638 \fn void QApplicationPrivate::initialize()
640 Initializes the QApplication object, called from the constructors.
642 void QApplicationPrivate::initialize()
644 QWidgetPrivate::mapper = new QWidgetMapper;
645 QWidgetPrivate::allWidgets = new QWidgetSet;
647 if (application_type != QApplication::Tty)
648 (void) QApplication::style(); // trigger creation of application style
649 #ifndef QT_NO_STATEMACHINE
650 // trigger registering of QStateMachine's GUI types
651 qRegisterGuiStateMachine();
654 is_app_running = true; // no longer starting up
657 #ifndef QT_NO_SESSIONMANAGER
658 // connect to the session manager
659 session_manager = new QSessionManager(q, session_id, session_key);
662 if (qgetenv("QT_USE_NATIVE_WINDOWS").toInt() > 0)
663 q->setAttribute(Qt::AA_NativeWindows);
666 #ifdef QT_AUTO_MAXIMIZE_THRESHOLD
667 autoMaximizeThreshold = QT_AUTO_MAXIMIZE_THRESHOLD;
669 if (qt_wince_is_mobile())
670 autoMaximizeThreshold = 50;
672 autoMaximizeThreshold = -1;
673 #endif //QT_AUTO_MAXIMIZE_THRESHOLD
676 #ifndef QT_NO_WHEELEVENT
677 QApplicationPrivate::wheel_scroll_lines = 3;
681 initializeMultitouch();
683 if (QApplication::desktopSettingsAware())
684 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme())
685 QApplicationPrivate::enabledAnimations = theme->themeHint(QPlatformTheme::UiEffects).toInt();
689 Returns the type of application (\l Tty, GuiClient, or
690 GuiServer). The type is set when constructing the QApplication
693 QApplication::Type QApplication::type()
695 if (QApplicationPrivate::instance())
696 return (QCoreApplication::Type)QApplicationPrivate::instance()->application_type;
700 /*****************************************************************************
701 Functions returning the active popup and modal widgets.
702 *****************************************************************************/
705 Returns the active popup widget.
707 A popup widget is a special top-level widget that sets the \c
708 Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application
709 opens a popup widget, all events are sent to the popup. Normal widgets and
710 modal widgets cannot be accessed before the popup widget is closed.
712 Only other popup widgets may be opened when a popup widget is shown. The
713 popup widgets are organized in a stack. This function returns the active
714 popup widget at the top of the stack.
716 \sa activeModalWidget(), topLevelWidgets()
719 QWidget *QApplication::activePopupWidget()
721 return QApplicationPrivate::popupWidgets && !QApplicationPrivate::popupWidgets->isEmpty() ?
722 QApplicationPrivate::popupWidgets->last() : 0;
727 Returns the active modal widget.
729 A modal widget is a special top-level widget which is a subclass of QDialog
730 that specifies the modal parameter of the constructor as true. A modal
731 widget must be closed before the user can continue with other parts of the
734 Modal widgets are organized in a stack. This function returns the active
735 modal widget at the top of the stack.
737 \sa activePopupWidget(), topLevelWidgets()
740 QWidget *QApplication::activeModalWidget()
742 QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(modalWindow());
743 return widgetWindow ? widgetWindow->widget() : 0;
747 Cleans up any window system resources that were allocated by this
748 application. Sets the global variable \c qApp to 0.
751 QApplication::~QApplication()
755 //### this should probable be done even later
756 qt_call_post_routines();
758 // kill timers before closing down the dispatcher
759 d->toolTipWakeUp.stop();
760 d->toolTipFallAsleep.stop();
762 QApplicationPrivate::is_app_closing = true;
763 QApplicationPrivate::is_app_running = false;
765 delete QWidgetPrivate::mapper;
766 QWidgetPrivate::mapper = 0;
768 // delete all widgets
769 if (QWidgetPrivate::allWidgets) {
770 QWidgetSet *mySet = QWidgetPrivate::allWidgets;
771 QWidgetPrivate::allWidgets = 0;
772 for (QWidgetSet::ConstIterator it = mySet->constBegin(); it != mySet->constEnd(); ++it) {
773 register QWidget *w = *it;
774 if (!w->parent()) // window
775 w->destroy(true, true);
780 delete qt_desktopWidget;
781 qt_desktopWidget = 0;
783 delete QApplicationPrivate::app_pal;
784 QApplicationPrivate::app_pal = 0;
785 clearSystemPalette();
786 delete QApplicationPrivate::set_pal;
787 QApplicationPrivate::set_pal = 0;
788 app_palettes()->clear();
790 delete QApplicationPrivate::sys_font;
791 QApplicationPrivate::sys_font = 0;
792 delete QApplicationPrivate::set_font;
793 QApplicationPrivate::set_font = 0;
794 app_fonts()->clear();
796 delete QApplicationPrivate::app_style;
797 QApplicationPrivate::app_style = 0;
798 delete QApplicationPrivate::app_icon;
799 QApplicationPrivate::app_icon = 0;
801 #ifndef QT_NO_DRAGANDDROP
803 delete QDragManager::self();
806 d->cleanupMultitouch();
810 if (QApplicationPrivate::widgetCount)
811 qDebug("Widgets left: %i Max widgets: %i \n", QWidgetPrivate::instanceCounter, QWidgetPrivate::maxInstances);
812 #ifndef QT_NO_SESSIONMANAGER
813 delete d->session_manager;
814 d->session_manager = 0;
815 #endif //QT_NO_SESSIONMANAGER
817 QApplicationPrivate::obey_desktop_settings = true;
819 QApplicationPrivate::app_strut = QSize(0, 0);
820 QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
821 QApplicationPrivate::widgetCount = false;
823 #ifndef QT_NO_STATEMACHINE
824 // trigger unregistering of QStateMachine's GUI types
825 qUnregisterGuiStateMachine();
831 \fn QWidget *QApplication::widgetAt(const QPoint &point)
833 Returns the widget at global screen position \a point, or 0 if there is no
836 This function can be slow.
838 \sa QCursor::pos(), QWidget::grabMouse(), QWidget::grabKeyboard()
840 QWidget *QApplication::widgetAt(const QPoint &p)
842 QWidget *window = QApplication::topLevelAt(p);
848 if (!window->testAttribute(Qt::WA_TransparentForMouseEvents))
849 child = window->childAt(window->mapFromGlobal(p));
854 if (window->testAttribute(Qt::WA_TransparentForMouseEvents)) {
855 //shoot a hole in the widget and try once again,
856 //suboptimal on Qt for Embedded Linux where we do
857 //know the stacking order of the toplevels.
860 QRegion oldmask = window->mask();
861 QPoint wpoint = window->mapFromGlobal(QPoint(x, y));
862 QRegion newmask = (oldmask.isEmpty() ? QRegion(window->rect()) : oldmask)
863 - QRegion(wpoint.x(), wpoint.y(), 1, 1);
864 window->setMask(newmask);
865 QWidget *recurse = 0;
866 if (QApplication::topLevelAt(p) != window) // verify recursion will terminate
867 recurse = widgetAt(x, y);
868 if (oldmask.isEmpty())
871 window->setMask(oldmask);
878 \fn QWidget *QApplication::widgetAt(int x, int y)
882 Returns the widget at global screen position (\a x, \a y), or 0 if there is
887 \fn void QApplication::setArgs(int argc, char **argv)
896 bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
898 if ((event->type() == QEvent::UpdateRequest
899 || event->type() == QEvent::LayoutRequest
900 || event->type() == QEvent::Resize
901 || event->type() == QEvent::Move
902 || event->type() == QEvent::LanguageChange
903 || event->type() == QEvent::UpdateSoftKeys
904 || event->type() == QEvent::InputMethod)) {
905 for (QPostEventList::const_iterator it = postedEvents->constBegin(); it != postedEvents->constEnd(); ++it) {
906 const QPostEvent &cur = *it;
907 if (cur.receiver != receiver || cur.event == 0 || cur.event->type() != event->type())
909 if (cur.event->type() == QEvent::LayoutRequest
910 || cur.event->type() == QEvent::UpdateRequest) {
912 } else if (cur.event->type() == QEvent::Resize) {
913 ((QResizeEvent *)(cur.event))->s = ((QResizeEvent *)event)->s;
914 } else if (cur.event->type() == QEvent::Move) {
915 ((QMoveEvent *)(cur.event))->p = ((QMoveEvent *)event)->p;
916 } else if (cur.event->type() == QEvent::LanguageChange) {
918 } else if (cur.event->type() == QEvent::UpdateSoftKeys) {
920 } else if ( cur.event->type() == QEvent::InputMethod ) {
921 *(QInputMethodEvent *)(cur.event) = *(QInputMethodEvent *)event;
930 return QGuiApplication::compressEvent(event, receiver, postedEvents);
934 \property QApplication::styleSheet
935 \brief the application style sheet
938 By default, this property returns an empty string unless the user specifies
939 the \c{-stylesheet} option on the command line when running the application.
941 \sa QWidget::setStyle(), {Qt Style Sheets}
945 \property QApplication::autoMaximizeThreshold
947 \brief defines a threshold for auto maximizing widgets
949 \b{The auto maximize threshold is only available as part of Qt for
952 This property defines a threshold for the size of a window as a percentage
953 of the screen size. If the minimum size hint of a window exceeds the
954 threshold, calling show() will cause the window to be maximized
957 Setting the threshold to 100 or greater means that the widget will always
958 be maximized. Alternatively, setting the threshold to 50 means that the
959 widget will be maximized only if the vertical minimum size hint is at least
960 50% of the vertical screen size.
962 Setting the threshold to -1 disables the feature.
964 On Windows CE the default is -1 (i.e., it is disabled).
965 On Windows Mobile the default is 40.
969 \property QApplication::autoSipEnabled
971 \brief toggles automatic SIP (software input panel) visibility
973 Set this property to \c true to automatically display the SIP when entering
974 widgets that accept keyboard input. This property only affects widgets with
975 the WA_InputMethodEnabled attribute set, and is typically used to launch
976 a virtual keyboard on devices which have very few or no keys.
978 \b{ The property only has an effect on platforms which use software input
979 panels, such as Windows CE.}
981 The default is platform dependent.
985 void QApplication::setAutoMaximizeThreshold(const int threshold)
987 QApplicationPrivate::autoMaximizeThreshold = threshold;
990 int QApplication::autoMaximizeThreshold() const
992 return QApplicationPrivate::autoMaximizeThreshold;
996 void QApplication::setAutoSipEnabled(const bool enabled)
998 QApplicationPrivate::autoSipEnabled = enabled;
1001 bool QApplication::autoSipEnabled() const
1003 return QApplicationPrivate::autoSipEnabled;
1006 #ifndef QT_NO_STYLE_STYLESHEET
1008 QString QApplication::styleSheet() const
1010 return QApplicationPrivate::styleSheet;
1013 void QApplication::setStyleSheet(const QString& styleSheet)
1015 QApplicationPrivate::styleSheet = styleSheet;
1016 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle*>(QApplicationPrivate::app_style);
1017 if (styleSheet.isEmpty()) { // application style sheet removed
1019 return; // there was no stylesheet before
1020 setStyle(proxy->base);
1021 } else if (proxy) { // style sheet update, just repolish
1022 proxy->repolish(qApp);
1023 } else { // stylesheet set the first time
1024 QStyleSheetStyle *newProxy = new QStyleSheetStyle(QApplicationPrivate::app_style);
1025 QApplicationPrivate::app_style->setParent(newProxy);
1030 #endif // QT_NO_STYLE_STYLESHEET
1033 Returns the application's style object.
1035 \sa setStyle(), QStyle
1037 QStyle *QApplication::style()
1039 if (QApplicationPrivate::app_style)
1040 return QApplicationPrivate::app_style;
1041 if (qApp->type() == QApplication::Tty) {
1042 Q_ASSERT(!"No style available in non-gui applications!");
1046 if (!QApplicationPrivate::app_style) {
1047 // Compile-time search for default style
1050 #ifdef QT_BUILD_INTERNAL
1051 QString envStyle = QString::fromLocal8Bit(qgetenv("QT_STYLE_OVERRIDE"));
1055 if (!QApplicationPrivate::styleOverride.isEmpty()) {
1056 style = QApplicationPrivate::styleOverride;
1057 } else if (!envStyle.isEmpty()) {
1060 style = QApplicationPrivate::desktopStyleKey();
1063 QStyle *&app_style = QApplicationPrivate::app_style;
1064 app_style = QStyleFactory::create(style);
1066 QStringList styles = QStyleFactory::keys();
1067 for (int i = 0; i < styles.size(); ++i) {
1068 if ((app_style = QStyleFactory::create(styles.at(i))))
1073 Q_ASSERT(!"No styles available!");
1077 // take ownership of the style
1078 QApplicationPrivate::app_style->setParent(qApp);
1080 initSystemPalette();
1082 if (QApplicationPrivate::set_pal) // repolish set palette with the new style
1083 QApplication::setPalette(*QApplicationPrivate::set_pal);
1085 #ifndef QT_NO_STYLE_STYLESHEET
1086 if (!QApplicationPrivate::styleSheet.isEmpty()) {
1087 qApp->setStyleSheet(QApplicationPrivate::styleSheet);
1090 QApplicationPrivate::app_style->polish(qApp);
1092 return QApplicationPrivate::app_style;
1096 Sets the application's GUI style to \a style. Ownership of the style object
1097 is transferred to QApplication, so QApplication will delete the style
1098 object on application exit or when a new style is set and the old style is
1099 still the parent of the application object.
1102 \snippet code/src_gui_kernel_qapplication.cpp 1
1104 When switching application styles, the color palette is set back to the
1105 initial colors or the system defaults. This is necessary since certain
1106 styles have to adapt the color palette to be fully style-guide compliant.
1108 Setting the style before a palette has been se, i.e., before creating
1109 QApplication, will cause the application to use QStyle::standardPalette()
1112 \warning Qt style sheets are currently not supported for custom QStyle
1113 subclasses. We plan to address this in some future release.
1115 \sa style(), QStyle, setPalette(), desktopSettingsAware()
1117 void QApplication::setStyle(QStyle *style)
1119 if (!style || style == QApplicationPrivate::app_style)
1122 QWidgetList all = allWidgets();
1124 // clean up the old style
1125 if (QApplicationPrivate::app_style) {
1126 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1127 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1128 register QWidget *w = *it;
1129 if (!(w->windowType() == Qt::Desktop) && // except desktop
1130 w->testAttribute(Qt::WA_WState_Polished)) { // has been polished
1131 QApplicationPrivate::app_style->unpolish(w);
1135 QApplicationPrivate::app_style->unpolish(qApp);
1138 QStyle *old = QApplicationPrivate::app_style; // save
1140 #ifndef QT_NO_STYLE_STYLESHEET
1141 if (!QApplicationPrivate::styleSheet.isEmpty() && !qobject_cast<QStyleSheetStyle *>(style)) {
1142 // we have a stylesheet already and a new style is being set
1143 QStyleSheetStyle *newProxy = new QStyleSheetStyle(style);
1144 style->setParent(newProxy);
1145 QApplicationPrivate::app_style = newProxy;
1147 #endif // QT_NO_STYLE_STYLESHEET
1148 QApplicationPrivate::app_style = style;
1149 QApplicationPrivate::app_style->setParent(qApp); // take ownership
1151 // take care of possible palette requirements of certain gui
1152 // styles. Do it before polishing the application since the style
1153 // might call QApplication::setPalette() itself
1154 if (QApplicationPrivate::set_pal) {
1155 QApplication::setPalette(*QApplicationPrivate::set_pal);
1156 } else if (QApplicationPrivate::sys_pal) {
1157 QApplicationPrivate::initializeWidgetPaletteHash();
1158 QApplicationPrivate::setPalette_helper(*QApplicationPrivate::sys_pal, /*className=*/0, /*clearWidgetPaletteHash=*/false);
1159 } else if (!QApplicationPrivate::sys_pal) {
1160 // Initialize the sys_pal if it hasn't happened yet...
1161 QApplicationPrivate::setSystemPalette(QApplicationPrivate::app_style->standardPalette());
1164 // initialize the application with the new style
1165 QApplicationPrivate::app_style->polish(qApp);
1167 // re-polish existing widgets if necessary
1168 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1169 for (QWidgetList::ConstIterator it1 = all.constBegin(); it1 != all.constEnd(); ++it1) {
1170 register QWidget *w = *it1;
1171 if (w->windowType() != Qt::Desktop && w->testAttribute(Qt::WA_WState_Polished)) {
1172 if (w->style() == QApplicationPrivate::app_style)
1173 QApplicationPrivate::app_style->polish(w); // repolish
1174 #ifndef QT_NO_STYLE_STYLESHEET
1176 w->setStyleSheet(w->styleSheet()); // touch
1181 for (QWidgetList::ConstIterator it2 = all.constBegin(); it2 != all.constEnd(); ++it2) {
1182 register QWidget *w = *it2;
1183 if (w->windowType() != Qt::Desktop && !w->testAttribute(Qt::WA_SetStyle)) {
1184 QEvent e(QEvent::StyleChange);
1185 QApplication::sendEvent(w, &e);
1191 #ifndef QT_NO_STYLE_STYLESHEET
1192 if (QStyleSheetStyle *oldProxy = qobject_cast<QStyleSheetStyle *>(old)) {
1196 if (old && old->parent() == qApp) {
1200 if (QApplicationPrivate::focus_widget) {
1201 QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
1202 QApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
1203 QApplicationPrivate::focus_widget->update();
1210 Requests a QStyle object for \a style from the QStyleFactory.
1212 The string must be one of the QStyleFactory::keys(), typically one of
1213 "windows", "motif", "cde", "plastique", "windowsxp", or "macintosh". Style
1214 names are case insensitive.
1216 Returns 0 if an unknown \a style is passed, otherwise the QStyle object
1217 returned is set as the application's GUI style.
1219 \warning To ensure that the application's style is set correctly, it is
1220 best to call this function before the QApplication constructor, if
1223 QStyle* QApplication::setStyle(const QString& style)
1225 QStyle *s = QStyleFactory::create(style);
1234 Returns the color specification.
1236 \sa QApplication::setColorSpec()
1239 int QApplication::colorSpec()
1241 return QApplicationPrivate::app_cspec;
1245 Sets the color specification for the application to \a spec.
1247 The color specification controls how the application allocates colors when
1248 run on a display with a limited amount of colors, e.g. 8 bit / 256 color
1251 The color specification must be set before you create the QApplication
1256 \li QApplication::NormalColor. This is the default color allocation
1257 strategy. Use this option if your application uses buttons, menus,
1258 texts and pixmaps with few colors. With this option, the
1259 application uses system global colors. This works fine for most
1260 applications under X11, but on the Windows platform, it may cause
1261 dithering of non-standard colors.
1262 \li QApplication::CustomColor. Use this option if your application
1263 needs a small number of custom colors. On X11, this option is the
1264 same as NormalColor. On Windows, Qt creates a Windows palette, and
1265 allocates colors to it on demand.
1266 \li QApplication::ManyColor. Use this option if your application is
1267 very color hungry, e.g., it requires thousands of colors. \br
1268 Under X11 the effect is:
1270 \li For 256-color displays which have at best a 256 color true
1271 color visual, the default visual is used, and colors are
1272 allocated from a color cube. The color cube is the 6x6x6
1273 (216 color) "Web palette" (the red, green, and blue
1274 components always have one of the following values: 0x00,
1275 0x33, 0x66, 0x99, 0xCC, or 0xFF), but the number of colors
1276 can be changed by the \e -ncols option. The user can force
1277 the application to use the true color visual with the
1278 \l{QApplication::QApplication()}{-visual} option.
1279 \li For 256-color displays which have a true color visual with
1280 more than 256 colors, use that visual. Silicon Graphics X
1281 servers this feature, for example. They provide an 8 bit
1282 visual by default but can deliver true color when asked.
1284 On Windows, Qt creates a Windows palette, and fills it with a color
1288 Be aware that the CustomColor and ManyColor choices may lead to colormap
1289 flashing: The foreground application gets (most) of the available colors,
1290 while the background windows will look less attractive.
1294 \snippet code/src_gui_kernel_qapplication.cpp 2
1299 void QApplication::setColorSpec(int spec)
1302 qWarning("QApplication::setColorSpec: This function must be "
1303 "called before the QApplication object is created");
1304 QApplicationPrivate::app_cspec = spec;
1308 \property QApplication::globalStrut
1309 \brief the minimum size that any GUI element that the user can interact
1312 For example, no button should be resized to be smaller than the global
1313 strut size. The strut size should be considered when reimplementing GUI
1314 controls that may be used on touch-screens or similar I/O devices.
1318 \snippet code/src_gui_kernel_qapplication.cpp 3
1320 By default, this property contains a QSize object with zero width and height.
1322 QSize QApplication::globalStrut()
1324 return QApplicationPrivate::app_strut;
1327 void QApplication::setGlobalStrut(const QSize& strut)
1329 QApplicationPrivate::app_strut = strut;
1334 \fn QPalette QApplication::palette(const QWidget* widget)
1337 If a \a widget is passed, the default palette for the widget's class is
1338 returned. This may or may not be the application palette. In most cases
1339 there is no special palette for certain types of widgets, but one notable
1340 exception is the popup menu under Windows, if the user has defined a
1341 special background color for menus in the display settings.
1343 \sa setPalette(), QWidget::palette()
1345 QPalette QApplication::palette(const QWidget* w)
1347 PaletteHash *hash = app_palettes();
1348 if (w && hash && hash->size()) {
1349 QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(w->metaObject()->className());
1350 if (it != hash->constEnd())
1352 for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1353 if (w->inherits(it.key()))
1363 Returns the palette for widgets of the given \a className.
1365 \sa setPalette(), QWidget::palette()
1367 QPalette QApplication::palette(const char *className)
1369 if (!QApplicationPrivate::app_pal)
1371 PaletteHash *hash = app_palettes();
1372 if (className && hash && hash->size()) {
1373 QHash<QByteArray, QPalette>::ConstIterator it = hash->constFind(className);
1374 if (it != hash->constEnd())
1377 return *QApplicationPrivate::app_pal;
1380 void QApplicationPrivate::setPalette_helper(const QPalette &palette, const char* className, bool clearWidgetPaletteHash)
1382 QPalette pal = palette;
1384 if (QApplicationPrivate::app_style)
1385 QApplicationPrivate::app_style->polish(pal); // NB: non-const reference
1388 PaletteHash *hash = app_palettes();
1390 if (QApplicationPrivate::app_pal && pal.isCopyOf(*QApplicationPrivate::app_pal))
1392 if (!QApplicationPrivate::app_pal)
1393 QApplicationPrivate::app_pal = new QPalette(pal);
1395 *QApplicationPrivate::app_pal = pal;
1396 if (hash && hash->size()) {
1398 if (clearWidgetPaletteHash)
1402 hash->insert(className, pal);
1405 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1406 // Send ApplicationPaletteChange to qApp itself, and to the widgets.
1407 QEvent e(QEvent::ApplicationPaletteChange);
1408 QApplication::sendEvent(QApplication::instance(), &e);
1410 QWidgetList wids = QApplication::allWidgets();
1411 for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1412 register QWidget *w = *it;
1413 if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1414 QApplication::sendEvent(w, &e);
1417 // Send to all scenes as well.
1418 #ifndef QT_NO_GRAPHICSVIEW
1419 QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1420 for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1421 it != scenes.constEnd(); ++it) {
1422 QApplication::sendEvent(*it, &e);
1424 #endif //QT_NO_GRAPHICSVIEW
1426 if (!className && (!QApplicationPrivate::sys_pal || !palette.isCopyOf(*QApplicationPrivate::sys_pal))) {
1427 if (!QApplicationPrivate::set_pal)
1428 QApplicationPrivate::set_pal = new QPalette(palette);
1430 *QApplicationPrivate::set_pal = palette;
1435 Changes the default application palette to \a palette.
1437 If \a className is passed, the change applies only to widgets that inherit
1438 \a className (as reported by QObject::inherits()). If \a className is left
1439 0, the change affects all widgets, thus overriding any previously set class
1442 The palette may be changed according to the current GUI style in
1445 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1446 When using style sheets, the palette of a widget can be customized using
1447 the "color", "background-color", "selection-color",
1448 "selection-background-color" and "alternate-background-color".
1450 \note Some styles do not use the palette for all drawing, for instance, if
1451 they make use of native theme engines. This is the case for the Windows XP,
1452 Windows Vista, and Mac OS X styles.
1454 \sa QWidget::setPalette(), palette(), QStyle::polish()
1457 void QApplication::setPalette(const QPalette &palette, const char* className)
1459 QApplicationPrivate::setPalette_helper(palette, className, /*clearWidgetPaletteHash=*/ true);
1464 void QApplicationPrivate::setSystemPalette(const QPalette &pal)
1469 // adjust the system palette to avoid dithering
1470 QColormap cmap = QColormap::instance();
1471 if (cmap.depths() > 4 && cmap.depths() < 24) {
1472 for (int g = 0; g < QPalette::NColorGroups; g++)
1473 for (int i = 0; i < QPalette::NColorRoles; i++) {
1474 QColor color = pal.color((QPalette::ColorGroup)g, (QPalette::ColorRole)i);
1475 color = cmap.colorAt(cmap.pixel(color));
1476 adjusted.setColor((QPalette::ColorGroup)g, (QPalette::ColorRole) i, color);
1484 sys_pal = new QPalette(adjusted);
1486 *sys_pal = adjusted;
1489 if (!QApplicationPrivate::set_pal)
1490 QApplication::setPalette(*sys_pal);
1494 Returns the default application font.
1496 \sa fontMetrics(), QWidget::font()
1498 QFont QApplication::font()
1500 return QGuiApplication::font();
1506 Returns the default font for the \a widget.
1508 \sa fontMetrics(), QWidget::setFont()
1511 QFont QApplication::font(const QWidget *widget)
1513 FontHash *hash = app_fonts();
1515 if (widget && hash && hash->size()) {
1516 QHash<QByteArray, QFont>::ConstIterator it =
1517 hash->constFind(widget->metaObject()->className());
1518 if (it != hash->constEnd())
1520 for (it = hash->constBegin(); it != hash->constEnd(); ++it) {
1521 if (widget->inherits(it.key()))
1531 Returns the font for widgets of the given \a className.
1533 \sa setFont(), QWidget::font()
1535 QFont QApplication::font(const char *className)
1537 FontHash *hash = app_fonts();
1538 if (className && hash && hash->size()) {
1539 QHash<QByteArray, QFont>::ConstIterator it = hash->constFind(className);
1540 if (it != hash->constEnd())
1548 Changes the default application font to \a font. If \a className is passed,
1549 the change applies only to classes that inherit \a className (as reported
1550 by QObject::inherits()).
1552 On application start-up, the default font depends on the window system. It
1553 can vary depending on both the window system version and the locale. This
1554 function lets you override the default font; but overriding may be a bad
1555 idea because, for example, some locales need extra large fonts to support
1556 their special characters.
1558 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1559 The font of an application can be customized using the "font" style sheet
1560 property. To set a bold font for all QPushButtons, set the application
1561 styleSheet() as "QPushButton { font: bold }"
1563 \sa font(), fontMetrics(), QWidget::setFont()
1566 void QApplication::setFont(const QFont &font, const char *className)
1569 FontHash *hash = app_fonts();
1571 QGuiApplication::setFont(font);
1572 if (hash && hash->size()) {
1577 hash->insert(className, font);
1579 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1580 // Send ApplicationFontChange to qApp itself, and to the widgets.
1581 QEvent e(QEvent::ApplicationFontChange);
1582 QApplication::sendEvent(QApplication::instance(), &e);
1584 QWidgetList wids = QApplication::allWidgets();
1585 for (QWidgetList::ConstIterator it = wids.constBegin(); it != wids.constEnd(); ++it) {
1586 register QWidget *w = *it;
1587 if (all || (!className && w->isWindow()) || w->inherits(className)) // matching class
1591 #ifndef QT_NO_GRAPHICSVIEW
1592 // Send to all scenes as well.
1593 QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1594 for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1595 it != scenes.constEnd(); ++it) {
1596 QApplication::sendEvent(*it, &e);
1598 #endif //QT_NO_GRAPHICSVIEW
1600 if (!className && (!QApplicationPrivate::sys_font || !font.isCopyOf(*QApplicationPrivate::sys_font))) {
1601 if (!QApplicationPrivate::set_font)
1602 QApplicationPrivate::set_font = new QFont(font);
1604 *QApplicationPrivate::set_font = font;
1610 void QApplicationPrivate::setSystemFont(const QFont &font)
1613 sys_font = new QFont(font);
1617 if (!QApplicationPrivate::set_font)
1618 QApplication::setFont(*sys_font);
1623 QString QApplicationPrivate::desktopStyleKey()
1625 // The platform theme might return a style that is not available, find
1627 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
1628 const QStringList availableKeys = QStyleFactory::keys();
1629 foreach (const QString &style, theme->themeHint(QPlatformTheme::StyleNames).toStringList())
1630 if (availableKeys.contains(style, Qt::CaseInsensitive))
1637 \property QApplication::windowIcon
1638 \brief the default window icon
1640 \sa QWidget::setWindowIcon(), {Setting the Application Icon}
1642 QIcon QApplication::windowIcon()
1644 return QApplicationPrivate::app_icon ? *QApplicationPrivate::app_icon : QIcon();
1647 void QApplication::setWindowIcon(const QIcon &icon)
1649 if (!QApplicationPrivate::app_icon)
1650 QApplicationPrivate::app_icon = new QIcon();
1651 *QApplicationPrivate::app_icon = icon;
1652 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1653 QEvent e(QEvent::ApplicationWindowIconChange);
1654 QWidgetList all = QApplication::allWidgets();
1655 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1656 register QWidget *w = *it;
1664 Returns a list of the top-level widgets (windows) in the application.
1666 \note Some of the top-level widgets may be hidden, for example a tooltip if
1667 no tooltip is currently shown.
1671 \snippet code/src_gui_kernel_qapplication.cpp 4
1673 \sa allWidgets(), QWidget::isWindow(), QWidget::isHidden()
1675 QWidgetList QApplication::topLevelWidgets()
1678 QWidgetList all = allWidgets();
1680 for (QWidgetList::ConstIterator it = all.constBegin(); it != all.constEnd(); ++it) {
1682 if (w->isWindow() && w->windowType() != Qt::Desktop)
1689 Returns a list of all the widgets in the application.
1691 The list is empty (QList::isEmpty()) if there are no widgets.
1693 \note Some of the widgets may be hidden.
1696 \snippet code/src_gui_kernel_qapplication.cpp 5
1698 \sa topLevelWidgets(), QWidget::isVisible()
1701 QWidgetList QApplication::allWidgets()
1703 if (QWidgetPrivate::allWidgets)
1704 return QWidgetPrivate::allWidgets->toList();
1705 return QWidgetList();
1709 Returns the application widget that has the keyboard input focus, or 0 if
1710 no widget in this application has the focus.
1712 \sa QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), focusChanged()
1715 QWidget *QApplication::focusWidget()
1717 return QApplicationPrivate::focus_widget;
1720 void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
1722 #ifndef QT_NO_GRAPHICSVIEW
1723 if (focus && focus->window()->graphicsProxyWidget())
1727 hidden_focus_widget = 0;
1729 if (focus != focus_widget) {
1730 if (focus && focus->isHidden()) {
1731 hidden_focus_widget = focus;
1735 if (focus && (reason == Qt::BacktabFocusReason || reason == Qt::TabFocusReason)
1736 && qt_in_tab_key_event)
1737 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1738 else if (focus && reason == Qt::ShortcutFocusReason) {
1739 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1741 QWidget *prev = focus_widget;
1742 focus_widget = focus;
1745 focus_widget->d_func()->setFocus_sys();
1747 if (reason != Qt::NoFocusReason) {
1751 #ifdef QT_KEYPAD_NAVIGATION
1752 if (QApplication::keypadNavigationEnabled()) {
1753 if (prev->hasEditFocus() && reason != Qt::PopupFocusReason)
1754 prev->setEditFocus(false);
1757 QFocusEvent out(QEvent::FocusOut, reason);
1758 QPointer<QWidget> that = prev;
1759 QApplication::sendEvent(prev, &out);
1761 QApplication::sendEvent(that->style(), &out);
1763 if(focus && QApplicationPrivate::focus_widget == focus) {
1764 QFocusEvent in(QEvent::FocusIn, reason);
1765 QPointer<QWidget> that = focus;
1766 QApplication::sendEvent(focus, &in);
1768 QApplication::sendEvent(that->style(), &in);
1770 emit qApp->focusChanged(prev, focus_widget);
1777 Returns the application top-level window that has the keyboard input focus,
1778 or 0 if no application window has the focus. There might be an
1779 activeWindow() even if there is no focusWidget(), for example if no widget
1780 in that window accepts key events.
1782 \sa QWidget::setFocus(), QWidget::hasFocus(), focusWidget()
1785 QWidget *QApplication::activeWindow()
1787 return QApplicationPrivate::active_window;
1791 Returns display (screen) font metrics for the application font.
1793 \sa font(), setFont(), QWidget::fontMetrics(), QPainter::fontMetrics()
1796 QFontMetrics QApplication::fontMetrics()
1798 return desktop()->fontMetrics();
1803 Closes all top-level windows.
1805 This function is particularly useful for applications with many top-level
1806 windows. It could, for example, be connected to a \uicontrol{Exit} entry in the
1807 \uicontrol{File} menu:
1809 \snippet mainwindows/mdi/mainwindow.cpp 0
1811 The windows are closed in random order, until one window does not accept
1812 the close event. The application quits when the last window was
1813 successfully closed; this can be turned off by setting
1814 \l quitOnLastWindowClosed to false.
1816 \sa quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(),
1817 QWidget::closeEvent(), lastWindowClosed(), quit(), topLevelWidgets(),
1820 void QApplication::closeAllWindows()
1822 bool did_close = true;
1824 while ((w = activeModalWidget()) && did_close) {
1825 if (!w->isVisible() || w->data->is_closing)
1827 did_close = w->close();
1829 QWidgetList list = QApplication::topLevelWidgets();
1830 for (int i = 0; did_close && i < list.size(); ++i) {
1833 && w->windowType() != Qt::Desktop
1834 && !w->data->is_closing) {
1835 did_close = w->close();
1836 list = QApplication::topLevelWidgets();
1843 Displays a simple message box about Qt. The message includes the version
1844 number of Qt being used by the application.
1846 This is useful for inclusion in the \uicontrol Help menu of an application, as
1847 shown in the \l{mainwindows/menus}{Menus} example.
1849 This function is a convenience slot for QMessageBox::aboutQt().
1851 void QApplication::aboutQt()
1853 #ifndef QT_NO_MESSAGEBOX
1854 QMessageBox::aboutQt(activeWindow());
1855 #endif // QT_NO_MESSAGEBOX
1860 \fn void QApplication::focusChanged(QWidget *old, QWidget *now)
1862 This signal is emitted when the widget that has keyboard focus changed from
1863 \a old to \a now, i.e., because the user pressed the tab-key, clicked into
1864 a widget or changed the active window. Both \a old and \a now can be the
1867 The signal is emitted after both widget have been notified about the change
1868 through QFocusEvent.
1870 \sa QWidget::setFocus(), QWidget::clearFocus(), Qt::FocusReason
1876 bool QApplication::event(QEvent *e)
1879 if(e->type() == QEvent::Close) {
1880 QCloseEvent *ce = static_cast<QCloseEvent*>(e);
1884 QWidgetList list = topLevelWidgets();
1885 for (int i = 0; i < list.size(); ++i) {
1886 QWidget *w = list.at(i);
1887 if (w->isVisible() && !(w->windowType() == Qt::Desktop) && !(w->windowType() == Qt::Popup) &&
1888 (!(w->windowType() == Qt::Dialog) || !w->parentWidget())) {
1893 if (ce->isAccepted()) {
1897 } else if (e->type() == QEvent::LocaleChange) {
1898 // on Windows the event propagation is taken care by the
1899 // WM_SETTINGCHANGE event handler.
1900 QWidgetList list = topLevelWidgets();
1901 for (int i = 0; i < list.size(); ++i) {
1902 QWidget *w = list.at(i);
1903 if (!(w->windowType() == Qt::Desktop)) {
1904 if (!w->testAttribute(Qt::WA_SetLocale))
1905 w->d_func()->setLocale_helper(QLocale(), true);
1909 } else if (e->type() == QEvent::Timer) {
1910 QTimerEvent *te = static_cast<QTimerEvent*>(e);
1912 if (te->timerId() == d->toolTipWakeUp.timerId()) {
1913 d->toolTipWakeUp.stop();
1914 if (d->toolTipWidget) {
1915 QWidget *w = d->toolTipWidget->window();
1916 // show tooltip if WA_AlwaysShowToolTips is set, or if
1917 // any ancestor of d->toolTipWidget is the active
1919 bool showToolTip = w->testAttribute(Qt::WA_AlwaysShowToolTips);
1920 while (w && !showToolTip) {
1921 showToolTip = w->isActiveWindow();
1922 w = w->parentWidget();
1923 w = w ? w->window() : 0;
1926 QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
1927 QApplication::sendEvent(d->toolTipWidget, &e);
1929 d->toolTipFallAsleep.start(2000, this);
1932 } else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
1933 d->toolTipFallAsleep.stop();
1937 if(e->type() == QEvent::LanguageChange) {
1938 QWidgetList list = topLevelWidgets();
1939 for (int i = 0; i < list.size(); ++i) {
1940 QWidget *w = list.at(i);
1941 if (!(w->windowType() == Qt::Desktop))
1942 postEvent(w, new QEvent(QEvent::LanguageChange));
1946 return QGuiApplication::event(e);
1950 \fn void QApplication::syncX()
1951 Was used to synchronize with the X server in 4.x, here for source compatibility.
1956 void QApplicationPrivate::notifyLayoutDirectionChange()
1958 QWidgetList list = QApplication::topLevelWidgets();
1959 for (int i = 0; i < list.size(); ++i) {
1960 QWidget *w = list.at(i);
1961 QEvent ev(QEvent::ApplicationLayoutDirectionChange);
1962 QCoreApplication::sendEvent(w, &ev);
1967 \fn Qt::WindowsVersion QApplication::winVersion()
1969 Use \l QSysInfo::WindowsVersion instead.
1973 \fn void QApplication::setActiveWindow(QWidget* active)
1975 Sets the active window to the \a active widget in response to a system
1976 event. The function is called from the platform specific event handlers.
1978 \warning This function does \e not set the keyboard focus to the active
1979 widget. Call QWidget::activateWindow() instead.
1981 It sets the activeWindow() and focusWidget() attributes and sends proper
1982 \l{QEvent::WindowActivate}{WindowActivate}/\l{QEvent::WindowDeactivate}
1983 {WindowDeactivate} and \l{QEvent::FocusIn}{FocusIn}/\l{QEvent::FocusOut}
1984 {FocusOut} events to all appropriate widgets. The window will then be
1985 painted in active state (e.g. cursors in line edits will blink), and it
1986 will have tool tips enabled.
1988 \sa activeWindow(), QWidget::activateWindow()
1990 void QApplication::setActiveWindow(QWidget* act)
1992 QWidget* window = act?act->window():0;
1994 if (QApplicationPrivate::active_window == window)
1997 #ifndef QT_NO_GRAPHICSVIEW
1998 if (window && window->graphicsProxyWidget()) {
1999 // Activate the proxy's view->viewport() ?
2004 QWidgetList toBeActivated;
2005 QWidgetList toBeDeactivated;
2007 if (QApplicationPrivate::active_window) {
2008 if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2009 QWidgetList list = topLevelWidgets();
2010 for (int i = 0; i < list.size(); ++i) {
2011 QWidget *w = list.at(i);
2012 if (w->isVisible() && w->isActiveWindow())
2013 toBeDeactivated.append(w);
2016 toBeDeactivated.append(QApplicationPrivate::active_window);
2020 if (QApplicationPrivate::focus_widget) {
2021 if (QApplicationPrivate::focus_widget->testAttribute(Qt::WA_InputMethodEnabled))
2022 qApp->inputMethod()->commit();
2024 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, Qt::ActiveWindowFocusReason);
2025 QApplication::sendEvent(QApplicationPrivate::focus_widget, &focusAboutToChange);
2028 QApplicationPrivate::active_window = window;
2030 if (QApplicationPrivate::active_window) {
2031 if (style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, QApplicationPrivate::active_window)) {
2032 QWidgetList list = topLevelWidgets();
2033 for (int i = 0; i < list.size(); ++i) {
2034 QWidget *w = list.at(i);
2035 if (w->isVisible() && w->isActiveWindow())
2036 toBeActivated.append(w);
2039 toBeActivated.append(QApplicationPrivate::active_window);
2044 // first the activation/deactivation events
2045 QEvent activationChange(QEvent::ActivationChange);
2046 QEvent windowActivate(QEvent::WindowActivate);
2047 QEvent windowDeactivate(QEvent::WindowDeactivate);
2049 for (int i = 0; i < toBeActivated.size(); ++i) {
2050 QWidget *w = toBeActivated.at(i);
2051 sendSpontaneousEvent(w, &windowActivate);
2052 sendSpontaneousEvent(w, &activationChange);
2055 for(int i = 0; i < toBeDeactivated.size(); ++i) {
2056 QWidget *w = toBeDeactivated.at(i);
2057 sendSpontaneousEvent(w, &windowDeactivate);
2058 sendSpontaneousEvent(w, &activationChange);
2061 if (QApplicationPrivate::popupWidgets == 0) { // !inPopupMode()
2062 // then focus events
2063 if (!QApplicationPrivate::active_window && QApplicationPrivate::focus_widget) {
2064 QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2065 } else if (QApplicationPrivate::active_window) {
2066 QWidget *w = QApplicationPrivate::active_window->focusWidget();
2067 if (w && w->isVisible() /*&& w->focusPolicy() != QWidget::NoFocus*/)
2068 w->setFocus(Qt::ActiveWindowFocusReason);
2070 w = QApplicationPrivate::focusNextPrevChild_helper(QApplicationPrivate::active_window, true);
2072 w->setFocus(Qt::ActiveWindowFocusReason);
2074 // If the focus widget is not in the activate_window, clear the focus
2075 w = QApplicationPrivate::focus_widget;
2076 if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus)
2077 QApplicationPrivate::setFocusWidget(QApplicationPrivate::active_window, Qt::ActiveWindowFocusReason);
2078 else if (!QApplicationPrivate::active_window->isAncestorOf(w))
2079 QApplicationPrivate::setFocusWidget(0, Qt::ActiveWindowFocusReason);
2087 * Helper function that returns the new focus widget, but does not set the focus reason.
2088 * Returns 0 if a new focus widget could not be found.
2089 * Shared with QGraphicsProxyWidgetPrivate::findFocusChild()
2091 QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool next)
2093 uint focus_flag = qt_tab_all_widgets ? Qt::TabFocus : Qt::StrongFocus;
2095 QWidget *f = toplevel->focusWidget();
2100 QWidget *test = f->d_func()->focus_next;
2101 while (test && test != f) {
2102 if ((test->focusPolicy() & focus_flag) == focus_flag
2103 && !(test->d_func()->extra && test->d_func()->extra->focus_proxy)
2104 && test->isVisibleTo(toplevel) && test->isEnabled()
2105 && !(w->windowType() == Qt::SubWindow && !w->isAncestorOf(test))
2106 && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))) {
2111 test = test->d_func()->focus_next;
2114 if (qt_in_tab_key_event) {
2115 w->window()->setAttribute(Qt::WA_KeyboardFocusChange);
2124 \fn void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave)
2127 Creates the proper Enter/Leave event when widget \a enter is entered and
2128 widget \a leave is left.
2130 void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave) {
2133 QEvent e(QEvent::Leave);
2134 QApplication::sendEvent(leave, & e);
2137 QEvent e(QEvent::Enter);
2138 QApplication::sendEvent(enter, & e);
2144 if ((!enter && !leave) || (enter == leave))
2147 qDebug() << "QApplicationPrivate::dispatchEnterLeave, ENTER:" << enter << "LEAVE:" << leave;
2149 QWidgetList leaveList;
2150 QWidgetList enterList;
2152 bool sameWindow = leave && enter && leave->window() == enter->window();
2153 if (leave && !sameWindow) {
2156 leaveList.append(w);
2157 } while (!w->isWindow() && (w = w->parentWidget()));
2159 if (enter && !sameWindow) {
2162 enterList.prepend(w);
2163 } while (!w->isWindow() && (w = w->parentWidget()));
2169 while (!w->isWindow() && (w = w->parentWidget()))
2172 while (!w->isWindow() && (w = w->parentWidget()))
2174 QWidget* wenter = enter;
2175 QWidget* wleave = leave;
2176 while (enterDepth > leaveDepth) {
2177 wenter = wenter->parentWidget();
2180 while (leaveDepth > enterDepth) {
2181 wleave = wleave->parentWidget();
2184 while (!wenter->isWindow() && wenter != wleave) {
2185 wenter = wenter->parentWidget();
2186 wleave = wleave->parentWidget();
2190 while (w != wleave) {
2191 leaveList.append(w);
2192 w = w->parentWidget();
2195 while (w != wenter) {
2196 enterList.prepend(w);
2197 w = w->parentWidget();
2201 QEvent leaveEvent(QEvent::Leave);
2202 for (int i = 0; i < leaveList.size(); ++i) {
2203 w = leaveList.at(i);
2204 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2205 QApplication::sendEvent(w, &leaveEvent);
2206 if (w->testAttribute(Qt::WA_Hover) &&
2207 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2208 Q_ASSERT(instance());
2209 QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos),
2210 QApplication::keyboardModifiers());
2211 qApp->d_func()->notify_helper(w, &he);
2215 QPoint posEnter = QCursor::pos();
2216 QEvent enterEvent(QEvent::Enter);
2217 for (int i = 0; i < enterList.size(); ++i) {
2218 w = enterList.at(i);
2219 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) {
2220 QApplication::sendEvent(w, &enterEvent);
2221 if (w->testAttribute(Qt::WA_Hover) &&
2222 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2223 QHoverEvent he(QEvent::HoverEnter, w->mapFromGlobal(posEnter), QPoint(-1, -1),
2224 QApplication::keyboardModifiers());
2225 qApp->d_func()->notify_helper(w, &he);
2230 #ifndef QT_NO_CURSOR
2231 // Update cursor for alien/graphics widgets.
2233 const bool enterOnAlien = (enter && (isAlien(enter) || enter->testAttribute(Qt::WA_DontShowOnScreen)));
2234 // Whenever we leave an alien widget on X11/QPA, we need to reset its nativeParentWidget()'s cursor.
2235 // This is not required on Windows as the cursor is reset on every single mouse move.
2236 QWidget *parentOfLeavingCursor = 0;
2237 for (int i = 0; i < leaveList.size(); ++i) {
2238 w = leaveList.at(i);
2241 if (w->testAttribute(Qt::WA_SetCursor)) {
2242 QWidget *parent = w->parentWidget();
2243 while (parent && parent->d_func()->data.in_destructor)
2244 parent = parent->parentWidget();
2245 parentOfLeavingCursor = parent;
2246 //continue looping, we need to find the downest alien widget with a cursor.
2247 // (downest on the screen)
2250 //check that we will not call qt_x11_enforce_cursor twice with the same native widget
2251 if (parentOfLeavingCursor && (!enterOnAlien
2252 || parentOfLeavingCursor->effectiveWinId() != enter->effectiveWinId())) {
2253 #ifndef QT_NO_GRAPHICSVIEW
2254 if (!parentOfLeavingCursor->window()->graphicsProxyWidget())
2257 if (enter == QApplication::desktop()) {
2258 qt_qpa_set_cursor(enter, true);
2260 qt_qpa_set_cursor(parentOfLeavingCursor, true);
2265 QWidget *cursorWidget = enter;
2266 while (!cursorWidget->isWindow() && !cursorWidget->isEnabled())
2267 cursorWidget = cursorWidget->parentWidget();
2272 #ifndef QT_NO_GRAPHICSVIEW
2273 if (cursorWidget->window()->graphicsProxyWidget()) {
2274 QWidgetPrivate::nearestGraphicsProxyWidget(cursorWidget)->setCursor(cursorWidget->cursor());
2278 qt_qpa_set_cursor(cursorWidget, true);
2284 /* exported for the benefit of testing tools */
2285 Q_WIDGETS_EXPORT bool qt_tryModalHelper(QWidget *widget, QWidget **rettop)
2287 return QApplicationPrivate::tryModalHelper(widget, rettop);
2291 Returns true if \a widget is blocked by a modal window.
2293 bool QApplicationPrivate::isBlockedByModal(QWidget *widget)
2295 widget = widget->window();
2296 return self->isWindowBlocked(widget->windowHandle());
2299 bool QApplicationPrivate::isWindowBlocked(QWindow *window, QWindow **blockingWindow) const
2301 QWindow *unused = 0;
2302 if (!blockingWindow)
2303 blockingWindow = &unused;
2305 if (modalWindowList.isEmpty()) {
2306 *blockingWindow = 0;
2309 QWidget *popupWidget = QApplication::activePopupWidget();
2310 QWindow *popupWindow = popupWidget ? popupWidget->windowHandle() : 0;
2311 if (popupWindow == window) {
2312 *blockingWindow = 0;
2316 for (int i = 0; i < modalWindowList.count(); ++i) {
2317 QWindow *modalWindow = modalWindowList.at(i);
2320 // check if the modal window is our window or a (transient) parent of our window
2321 QWindow *w = window;
2323 if (w == modalWindow) {
2324 *blockingWindow = 0;
2327 QWindow *p = w->parent();
2329 p = w->transientParent();
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);
2484 if (!graphicsWidget) {
2485 // Register the widget that shall receive a leave event
2486 // after the last button is released.
2487 if ((alienWidget || !receiver->internalWinId()) && !leaveAfterRelease && !QWidget::mouseGrabber())
2488 leaveAfterRelease = *buttonDown;
2489 if (event->type() == QEvent::MouseButtonRelease && !event->buttons())
2492 } else if (lastMouseReceiver) {
2493 // Dispatch enter/leave if we move:
2494 // 1) from an alien widget to another alien widget or
2495 // from a native widget to an alien widget (first OR case)
2496 // 2) from an alien widget to a native widget (second OR case)
2497 if ((alienWidget && alienWidget != lastMouseReceiver)
2498 || (isAlien(lastMouseReceiver) && !alienWidget)) {
2499 if (activePopupWidget) {
2500 if (!QWidget::mouseGrabber())
2501 dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver);
2503 dispatchEnterLeave(receiver, lastMouseReceiver);
2510 qDebug() << "QApplicationPrivate::sendMouseEvent: receiver:" << receiver
2511 << "pos:" << event->pos() << "alien" << alienWidget << "button down"
2512 << *buttonDown << "last" << lastMouseReceiver << "leave after release"
2513 << leaveAfterRelease;
2516 // We need this quard in case someone opens a modal dialog / popup. If that's the case
2517 // leaveAfterRelease is set to null, but we shall not update lastMouseReceiver.
2518 const bool wasLeaveAfterRelease = leaveAfterRelease != 0;
2521 result = QApplication::sendSpontaneousEvent(receiver, event);
2523 result = QApplication::sendEvent(receiver, event);
2525 if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease
2526 && !event->buttons() && QWidget::mouseGrabber() != leaveAfterRelease) {
2527 // Dispatch enter/leave if:
2528 // 1) the mouse grabber is an alien widget
2529 // 2) the button is released on an alien widget
2532 enter = alienGuard ? alienWidget : nativeWidget;
2533 else // The receiver is typically deleted on mouse release with drag'n'drop.
2534 enter = QApplication::widgetAt(event->globalPos());
2535 dispatchEnterLeave(enter, leaveAfterRelease);
2536 leaveAfterRelease = 0;
2537 lastMouseReceiver = enter;
2538 } else if (!wasLeaveAfterRelease) {
2539 if (activePopupWidget) {
2540 if (!QWidget::mouseGrabber())
2541 lastMouseReceiver = alienGuard ? alienWidget : (nativeGuard ? nativeWidget : 0);
2543 lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPos());
2551 This function should only be called when the widget changes visibility, i.e.
2552 when the \a widget is shown, hidden or deleted. This function does nothing
2553 if the widget is a top-level or native, i.e. not an alien widget. In that
2554 case enter/leave events are genereated by the underlying windowing system.
2556 extern QPointer<QWidget> qt_last_mouse_receiver;
2557 extern QWidget *qt_button_down;
2558 void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
2560 #ifndef QT_NO_CURSOR
2561 if (!widget || widget->isWindow())
2563 const bool widgetInShow = widget->isVisible() && !widget->data->in_destructor;
2564 if (!widgetInShow && widget != qt_last_mouse_receiver)
2565 return; // Widget was not under the cursor when it was hidden/deleted.
2567 if (widgetInShow && widget->parentWidget()->data->in_show)
2568 return; // Ingore recursive show.
2570 QWidget *mouseGrabber = QWidget::mouseGrabber();
2571 if (mouseGrabber && mouseGrabber != widget)
2572 return; // Someone else has the grab; enter/leave should not occur.
2574 QWidget *tlw = widget->window();
2575 if (tlw->data->in_destructor || tlw->data->is_closing)
2576 return; // Closing down the business.
2578 if (widgetInShow && (!qt_last_mouse_receiver || qt_last_mouse_receiver->window() != tlw))
2579 return; // Mouse cursor not inside the widget's top-level.
2581 const QPoint globalPos(QCursor::pos());
2582 QPoint windowPos = tlw->mapFromGlobal(globalPos);
2584 // Find the current widget under the mouse. If this function was called from
2585 // the widget's destructor, we have to make sure childAt() doesn't take into
2586 // account widgets that are about to be destructed.
2587 QWidget *widgetUnderCursor = tlw->d_func()->childAt_helper(windowPos, widget->data->in_destructor);
2588 if (!widgetUnderCursor)
2589 widgetUnderCursor = tlw;
2590 QPoint pos = widgetUnderCursor->mapFrom(tlw, windowPos);
2592 if (widgetInShow && widgetUnderCursor != widget && !widget->isAncestorOf(widgetUnderCursor))
2593 return; // Mouse cursor not inside the widget or any of its children.
2595 if (widget->data->in_destructor && qt_button_down == widget)
2598 // Send enter/leave events followed by a mouse move on the entered widget.
2599 QMouseEvent e(QEvent::MouseMove, pos, windowPos, globalPos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
2600 sendMouseEvent(widgetUnderCursor, &e, widgetUnderCursor, tlw, &qt_button_down, qt_last_mouse_receiver);
2601 #endif // QT_NO_CURSOR
2605 Returns the desktop widget (also called the root window).
2607 The desktop may be composed of multiple screens, so it would be incorrect,
2608 for example, to attempt to \e center some widget in the desktop's geometry.
2609 QDesktopWidget has various functions for obtaining useful geometries upon
2610 the desktop, such as QDesktopWidget::screenGeometry() and
2611 QDesktopWidget::availableGeometry().
2613 On X11, it is also possible to draw on the desktop.
2615 QDesktopWidget *QApplication::desktop()
2617 if (!qt_desktopWidget || // not created yet
2618 !(qt_desktopWidget->windowType() == Qt::Desktop)) { // reparented away
2619 qt_desktopWidget = new QDesktopWidget();
2621 return qt_desktopWidget;
2626 \fn bool QApplication::isSessionRestored() const
2628 Returns true if the application has been restored from an earlier
2629 \l{Session Management}{session}; otherwise returns false.
2631 \sa sessionId(), commitData(), saveState()
2636 \fn QString QApplication::sessionId() const
2638 Returns the current \l{Session Management}{session's} identifier.
2640 If the application has been restored from an earlier session, this
2641 identifier is the same as it was in that previous session. The session
2642 identifier is guaranteed to be unique both for different applications
2643 and for different instances of the same application.
2645 \sa isSessionRestored(), sessionKey(), commitData(), saveState()
2649 \fn QString QApplication::sessionKey() const
2651 Returns the session key in the current \l{Session Management}{session}.
2653 If the application has been restored from an earlier session, this key is
2654 the same as it was when the previous session ended.
2656 The session key changes with every call of commitData() or saveState().
2658 \sa isSessionRestored(), sessionId(), commitData(), saveState()
2660 #ifndef QT_NO_SESSIONMANAGER
2661 bool QApplication::isSessionRestored() const
2663 Q_D(const QApplication);
2664 return d->is_session_restored;
2667 QString QApplication::sessionId() const
2669 Q_D(const QApplication);
2670 return d->session_id;
2673 QString QApplication::sessionKey() const
2675 Q_D(const QApplication);
2676 return d->session_key;
2684 \fn void QApplication::commitDataRequest(QSessionManager &manager)
2686 This signal deals with \l{Session Management}{session management}. It is
2687 emitted when the QSessionManager wants the application to commit all its
2690 Usually this means saving all open files, after getting permission from
2691 the user. Furthermore you may want to provide a means by which the user
2692 can cancel the shutdown.
2694 You should not exit the application within this signal. Instead,
2695 the session manager may or may not do this afterwards, depending on the
2698 \warning Within this signal, no user interaction is possible, \e
2699 unless you ask the \a manager for explicit permission. See
2700 QSessionManager::allowsInteraction() and
2701 QSessionManager::allowsErrorInteraction() for details and example
2704 \note You should use Qt::DirectConnection when connecting to this signal.
2706 \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
2710 This function deals with \l{Session Management}{session management}. It is
2711 invoked when the QSessionManager wants the application to commit all its
2714 Usually this means saving all open files, after getting permission from the
2715 user. Furthermore you may want to provide a means by which the user can
2716 cancel the shutdown.
2718 You should not exit the application within this function. Instead, the
2719 session manager may or may not do this afterwards, depending on the
2722 \warning Within this function, no user interaction is possible, \e
2723 unless you ask the \a manager for explicit permission. See
2724 QSessionManager::allowsInteraction() and
2725 QSessionManager::allowsErrorInteraction() for details and example
2728 The default implementation requests interaction and sends a close event to
2729 all visible top-level widgets. If any event was rejected, the shutdown is
2732 \sa isSessionRestored(), sessionId(), saveState(), {Session Management}
2734 #ifndef QT_NO_SESSIONMANAGER
2735 void QApplication::commitData(QSessionManager& manager )
2737 emit commitDataRequest(manager);
2738 if (manager.allowsInteraction()) {
2740 QWidgetList list = QApplication::topLevelWidgets();
2741 bool cancelled = false;
2742 for (int i = 0; !cancelled && i < list.size(); ++i) {
2743 QWidget* w = list.at(i);
2744 if (w->isVisible() && !done.contains(w)) {
2745 cancelled = !w->close();
2748 list = QApplication::topLevelWidgets();
2759 \fn void QApplication::saveStateRequest(QSessionManager &manager)
2761 This signal deals with \l{Session Management}{session management}. It is
2762 invoked when the \l{QSessionManager}{session manager} wants the application
2763 to preserve its state for a future session.
2765 For example, a text editor would create a temporary file that includes the
2766 current contents of its edit buffers, the location of the cursor and other
2767 aspects of the current editing session.
2769 You should never exit the application within this signal. Instead, the
2770 session manager may or may not do this afterwards, depending on the
2771 context. Futhermore, most session managers will very likely request a saved
2772 state immediately after the application has been started. This permits the
2773 session manager to learn about the application's restart policy.
2775 \warning Within this function, no user interaction is possible, \e
2776 unless you ask the \a manager for explicit permission. See
2777 QSessionManager::allowsInteraction() and
2778 QSessionManager::allowsErrorInteraction() for details.
2780 \note You should use Qt::DirectConnection when connecting to this signal.
2782 \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
2786 This function deals with \l{Session Management}{session management}. It is
2787 invoked when the \l{QSessionManager}{session manager} wants the application
2788 to preserve its state for a future session.
2790 For example, a text editor would create a temporary file that includes the
2791 current contents of its edit buffers, the location of the cursor and other
2792 aspects of the current editing session.
2794 You should never exit the application within this function. Instead, the
2795 session manager may or may not do this afterwards, depending on the
2796 context. Futhermore, most session managers will very likely request a saved
2797 state immediately after the application has been started. This permits the
2798 session manager to learn about the application's restart policy.
2800 \warning Within this function, no user interaction is possible, \e
2801 unless you ask the \a manager for explicit permission. See
2802 QSessionManager::allowsInteraction() and
2803 QSessionManager::allowsErrorInteraction() for details.
2805 \sa isSessionRestored(), sessionId(), commitData(), {Session Management}
2808 void QApplication::saveState(QSessionManager &manager)
2810 emit saveStateRequest(manager);
2812 #endif //QT_NO_SESSIONMANAGER
2814 Sets the time after which a drag should start to \a ms ms.
2819 void QApplication::setStartDragTime(int ms)
2825 \property QApplication::startDragTime
2826 \brief the time in milliseconds that a mouse button must be held down
2827 before a drag and drop operation will begin
2829 If you support drag and drop in your application, and want to start a drag
2830 and drop operation after the user has held down a mouse button for a
2831 certain amount of time, you should use this property's value as the delay.
2833 Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for
2836 The default value is 500 ms.
2838 \sa startDragDistance(), {Drag and Drop}
2841 int QApplication::startDragTime()
2843 return qApp->styleHints()->startDragTime();
2847 Sets the distance after which a drag should start to \a l pixels.
2849 \sa startDragDistance()
2852 void QApplication::setStartDragDistance(int l)
2858 \property QApplication::startDragDistance
2860 If you support drag and drop in your application, and want to start a drag
2861 and drop operation after the user has moved the cursor a certain distance
2862 with a button held down, you should use this property's value as the
2863 minimum distance required.
2865 For example, if the mouse position of the click is stored in \c startPos
2866 and the current position (e.g. in the mouse move event) is \c currentPos,
2867 you can find out if a drag should be started with code like this:
2869 \snippet code/src_gui_kernel_qapplication.cpp 7
2871 Qt uses this value internally, e.g. in QFileDialog.
2873 The default value is 4 pixels.
2875 \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop}
2878 int QApplication::startDragDistance()
2880 return qApp->styleHints()->startDragDistance();
2884 \fn void QApplication::setReverseLayout(bool reverse)
2886 Use setLayoutDirection() instead.
2890 \fn void QApplication::reverseLayout()
2892 Use layoutDirection() instead.
2899 Strips out vertical alignment flags and transforms an alignment \a align
2900 of Qt::AlignLeft into Qt::AlignLeft or Qt::AlignRight according to the
2906 Enters the main event loop and waits until exit() is called, then returns
2907 the value that was set to exit() (which is 0 if exit() is called via
2910 It is necessary to call this function to start event handling. The main
2911 event loop receives events from the window system and dispatches these to
2912 the application widgets.
2914 Generally, no user interaction can take place before calling exec(). As a
2915 special case, modal widgets like QMessageBox can be used before calling
2916 exec(), because modal widgets call exec() to start a local event loop.
2918 To make your application perform idle processing, i.e., executing a special
2919 function whenever there are no pending events, use a QTimer with 0 timeout.
2920 More advanced idle processing schemes can be achieved using processEvents().
2922 We recommend that you connect clean-up code to the
2923 \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
2924 application's \c{main()} function. This is because, on some platforms the
2925 QApplication::exec() call may not return. For example, on the Windows
2926 platform, when the user logs off, the system terminates the process after Qt
2927 closes all top-level windows. Hence, there is \e{no guarantee} that the
2928 application will have time to exit its event loop and execute code at the
2929 end of the \c{main()} function, after the QApplication::exec() call.
2931 \sa quitOnLastWindowClosed, quit(), exit(), processEvents(),
2932 QCoreApplication::exec()
2934 int QApplication::exec()
2936 #ifndef QT_NO_ACCESSIBILITY
2937 QAccessible::setRootObject(qApp);
2939 return QGuiApplication::exec();
2942 bool QApplicationPrivate::shouldQuit()
2944 /* if there is no non-withdrawn primary window left (except
2945 the ones without QuitOnClose), we emit the lastWindowClosed
2947 QWidgetList list = QApplication::topLevelWidgets();
2948 for (int i = 0; i < list.size(); ++i) {
2949 QWidget *w = list.at(i);
2950 if (w->isVisible() && !w->parentWidget() && w->testAttribute(Qt::WA_QuitOnClose))
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 QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(qobject_cast<QWindow *>(receiver), e);
2976 // capture the current mouse/keyboard state
2977 if(e->spontaneous()) {
2978 if (e->type() == QEvent::MouseButtonPress
2979 || e->type() == QEvent::MouseButtonRelease) {
2980 QMouseEvent *me = static_cast<QMouseEvent*>(e);
2981 if(me->type() == QEvent::MouseButtonPress)
2982 QApplicationPrivate::mouse_buttons |= me->button();
2984 QApplicationPrivate::mouse_buttons &= ~me->button();
2988 #ifndef QT_NO_GESTURES
2989 // walk through parents and check for gestures
2990 if (d->gestureManager) {
2991 switch (e->type()) {
2993 case QEvent::MetaCall:
2994 case QEvent::DeferredDelete:
2995 case QEvent::DragEnter: case QEvent::DragMove: case QEvent::DragLeave:
2996 case QEvent::Drop: case QEvent::DragResponse:
2997 case QEvent::ChildAdded: case QEvent::ChildPolished:
2998 case QEvent::ChildRemoved:
2999 case QEvent::UpdateRequest:
3000 case QEvent::UpdateLater:
3001 case QEvent::LocaleChange:
3003 case QEvent::IconDrag:
3004 case QEvent::StyleChange:
3005 case QEvent::GraphicsSceneDragEnter:
3006 case QEvent::GraphicsSceneDragMove:
3007 case QEvent::GraphicsSceneDragLeave:
3008 case QEvent::GraphicsSceneDrop:
3009 case QEvent::DynamicPropertyChange:
3010 case QEvent::NetworkReplyUpdated:
3013 if (receiver->isWidgetType()) {
3014 if (d->gestureManager->filterEvent(static_cast<QWidget *>(receiver), e))
3017 // a special case for events that go to QGesture objects.
3018 // We pass the object to the gesture manager and it'll figure
3019 // out if it's QGesture or not.
3020 if (d->gestureManager->filterEvent(receiver, e))
3025 #endif // QT_NO_GESTURES
3027 // User input and window activation makes tooltips sleep
3028 switch (e->type()) {
3030 case QEvent::ActivationChange:
3031 case QEvent::KeyPress:
3032 case QEvent::KeyRelease:
3033 case QEvent::FocusOut:
3034 case QEvent::FocusIn:
3035 case QEvent::MouseButtonPress:
3036 case QEvent::MouseButtonRelease:
3037 case QEvent::MouseButtonDblClick:
3038 d->toolTipFallAsleep.stop();
3041 d->toolTipWakeUp.stop();
3047 if (!receiver->isWidgetType()) {
3048 res = d->notify_helper(receiver, e);
3049 } else switch (e->type()) {
3050 case QEvent::ShortcutOverride:
3051 case QEvent::KeyPress:
3052 case QEvent::KeyRelease:
3054 bool isWidget = receiver->isWidgetType();
3055 bool isGraphicsWidget = false;
3056 #ifndef QT_NO_GRAPHICSVIEW
3057 isGraphicsWidget = !isWidget && qobject_cast<QGraphicsWidget *>(receiver);
3059 if (!isWidget && !isGraphicsWidget) {
3060 res = d->notify_helper(receiver, e);
3064 QKeyEvent* key = static_cast<QKeyEvent*>(e);
3065 if (key->type()==QEvent::KeyPress) {
3066 #ifndef QT_NO_SHORTCUT
3067 // Try looking for a Shortcut before sending key events
3068 if ((res = qApp->d_func()->shortcutMap.tryShortcutEvent(receiver, key)))
3071 qt_in_tab_key_event = (key->key() == Qt::Key_Backtab
3072 || key->key() == Qt::Key_Tab
3073 || key->key() == Qt::Key_Left
3074 || key->key() == Qt::Key_Up
3075 || key->key() == Qt::Key_Right
3076 || key->key() == Qt::Key_Down);
3078 bool def = key->isAccepted();
3079 QPointer<QObject> pr = receiver;
3085 res = d->notify_helper(receiver, e);
3086 QWidget *w = isWidget ? static_cast<QWidget *>(receiver) : 0;
3087 #ifndef QT_NO_GRAPHICSVIEW
3088 QGraphicsWidget *gw = isGraphicsWidget ? static_cast<QGraphicsWidget *>(receiver) : 0;
3091 if ((res && key->isAccepted())
3093 QLineEdit will emit a signal on Key_Return, but
3094 ignore the event, and sometimes the connected
3095 slot deletes the QLineEdit (common in itemview
3096 delegates), so we have to check if the widget
3097 was destroyed even if the event was ignored (to
3100 note that we don't have to reset pw while
3101 propagating (because the original receiver will
3102 be destroyed if one of its ancestors is)
3105 || (isWidget && (w->isWindow() || !w->parentWidget()))
3106 #ifndef QT_NO_GRAPHICSVIEW
3107 || (isGraphicsWidget && (gw->isWindow() || !gw->parentWidget()))
3113 #ifndef QT_NO_GRAPHICSVIEW
3114 receiver = w ? (QObject *)w->parentWidget() : (QObject *)gw->parentWidget();
3116 receiver = w->parentWidget();
3119 qt_in_tab_key_event = false;
3122 case QEvent::MouseButtonPress:
3123 case QEvent::MouseButtonRelease:
3124 case QEvent::MouseButtonDblClick:
3125 case QEvent::MouseMove:
3127 QWidget* w = static_cast<QWidget *>(receiver);
3129 QMouseEvent* mouse = static_cast<QMouseEvent*>(e);
3130 QPoint relpos = mouse->pos();
3132 if (e->spontaneous()) {
3134 if (e->type() == QEvent::MouseButtonPress) {
3135 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3137 Qt::MouseFocusReason);
3140 // ### Qt 5 These dynamic tool tips should be an OPT-IN feature. Some platforms
3141 // like Mac OS X (probably others too), can optimize their views by not
3142 // dispatching mouse move events. We have attributes to control hover,
3143 // and mouse tracking, but as long as we are deciding to implement this
3144 // feature without choice of opting-in or out, you ALWAYS have to have
3145 // tracking enabled. Therefore, the other properties give a false sense of
3146 // performance enhancement.
3147 if (e->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3148 d->toolTipWidget = w;
3149 d->toolTipPos = relpos;
3150 d->toolTipGlobalPos = mouse->globalPos();
3151 d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive()?20:700, this);
3155 bool eventAccepted = mouse->isAccepted();
3157 QPointer<QWidget> pw = w;
3159 QMouseEvent me(mouse->type(), relpos, mouse->windowPos(), mouse->globalPos(), mouse->button(), mouse->buttons(),
3160 mouse->modifiers());
3161 me.spont = mouse->spontaneous();
3162 me.setTimestamp(mouse->timestamp());
3163 // throw away any mouse-tracking-only mouse events
3164 if (!w->hasMouseTracking()
3165 && mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
3166 // but still send them through all application event filters (normally done by notify_helper)
3167 for (int i = 0; d->extraData && i < d->extraData->eventFilters.size(); ++i) {
3168 register QObject *obj = d->extraData->eventFilters.at(i);
3171 if (obj->d_func()->threadData != w->d_func()->threadData) {
3172 qWarning("QApplication: Object event filter cannot be in a different thread.");
3175 if (obj->eventFilter(w, w == receiver ? mouse : &me))
3180 w->setAttribute(Qt::WA_NoMouseReplay, false);
3181 res = d->notify_helper(w, w == receiver ? mouse : &me);
3184 eventAccepted = (w == receiver ? mouse : &me)->isAccepted();
3185 if (res && eventAccepted)
3187 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3190 w = w->parentWidget();
3193 mouse->setAccepted(eventAccepted);
3195 if (e->type() == QEvent::MouseMove) {
3199 w = static_cast<QWidget *>(receiver);
3200 relpos = mouse->pos();
3201 QPoint diff = relpos - w->mapFromGlobal(d->hoverGlobalPos);
3203 if (w->testAttribute(Qt::WA_Hover) &&
3204 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
3205 QHoverEvent he(QEvent::HoverMove, relpos, relpos - diff, mouse->modifiers());
3206 d->notify_helper(w, &he);
3208 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3211 w = w->parentWidget();
3215 d->hoverGlobalPos = mouse->globalPos();
3218 #ifndef QT_NO_WHEELEVENT
3221 QWidget* w = static_cast<QWidget *>(receiver);
3222 QWheelEvent* wheel = static_cast<QWheelEvent*>(e);
3223 QPoint relpos = wheel->pos();
3224 bool eventAccepted = wheel->isAccepted();
3226 if (e->spontaneous()) {
3227 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
3229 Qt::MouseFocusReason);
3233 QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
3234 wheel->modifiers());
3235 we.spont = wheel->spontaneous();
3236 res = d->notify_helper(w, w == receiver ? wheel : &we);
3237 eventAccepted = ((w == receiver) ? wheel : &we)->isAccepted();
3239 if ((res && eventAccepted)
3240 || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3244 w = w->parentWidget();
3246 wheel->setAccepted(eventAccepted);
3250 #ifndef QT_NO_CONTEXTMENU
3251 case QEvent::ContextMenu:
3253 QWidget* w = static_cast<QWidget *>(receiver);
3254 QContextMenuEvent *context = static_cast<QContextMenuEvent*>(e);
3255 QPoint relpos = context->pos();
3256 bool eventAccepted = context->isAccepted();
3258 QContextMenuEvent ce(context->reason(), relpos, context->globalPos(), context->modifiers());
3259 ce.spont = e->spontaneous();
3260 res = d->notify_helper(w, w == receiver ? context : &ce);
3261 eventAccepted = ((w == receiver) ? context : &ce)->isAccepted();
3264 if ((res && eventAccepted)
3265 || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3269 w = w->parentWidget();
3271 context->setAccepted(eventAccepted);
3274 #endif // QT_NO_CONTEXTMENU
3275 #ifndef QT_NO_TABLETEVENT
3276 case QEvent::TabletMove:
3277 case QEvent::TabletPress:
3278 case QEvent::TabletRelease:
3280 QWidget *w = static_cast<QWidget *>(receiver);
3281 QTabletEvent *tablet = static_cast<QTabletEvent*>(e);
3282 QPointF relpos = tablet->posF();
3283 bool eventAccepted = tablet->isAccepted();
3285 QTabletEvent te(tablet->type(), relpos, tablet->globalPosF(),
3286 tablet->device(), tablet->pointerType(),
3287 tablet->pressure(), tablet->xTilt(), tablet->yTilt(),
3288 tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
3289 tablet->modifiers(), tablet->uniqueId());
3290 te.spont = e->spontaneous();
3291 res = d->notify_helper(w, w == receiver ? tablet : &te);
3292 eventAccepted = ((w == receiver) ? tablet : &te)->isAccepted();
3294 if ((res && eventAccepted)
3296 || w->testAttribute(Qt::WA_NoMousePropagation))
3300 w = w->parentWidget();
3302 tablet->setAccepted(eventAccepted);
3303 qt_tabletChokeMouse = tablet->isAccepted();
3306 #endif // QT_NO_TABLETEVENT
3308 #if !defined(QT_NO_TOOLTIP) || !defined(QT_NO_WHATSTHIS)
3309 case QEvent::ToolTip:
3310 case QEvent::WhatsThis:
3311 case QEvent::QueryWhatsThis:
3313 QWidget* w = static_cast<QWidget *>(receiver);
3314 QHelpEvent *help = static_cast<QHelpEvent*>(e);
3315 QPoint relpos = help->pos();
3316 bool eventAccepted = help->isAccepted();
3318 QHelpEvent he(help->type(), relpos, help->globalPos());
3319 he.spont = e->spontaneous();
3320 res = d->notify_helper(w, w == receiver ? help : &he);
3322 eventAccepted = (w == receiver ? help : &he)->isAccepted();
3323 if ((res && eventAccepted) || w->isWindow())
3327 w = w->parentWidget();
3329 help->setAccepted(eventAccepted);
3333 #if !defined(QT_NO_STATUSTIP) || !defined(QT_NO_WHATSTHIS)
3334 case QEvent::StatusTip:
3335 case QEvent::WhatsThisClicked:
3337 QWidget *w = static_cast<QWidget *>(receiver);
3339 res = d->notify_helper(w, e);
3340 if ((res && e->isAccepted()) || w->isWindow())
3342 w = w->parentWidget();
3348 #ifndef QT_NO_DRAGANDDROP
3349 case QEvent::DragEnter: {
3350 QWidget* w = static_cast<QWidget *>(receiver);
3351 QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent *>(e);
3352 #ifndef QT_NO_GRAPHICSVIEW
3353 // QGraphicsProxyWidget handles its own propagation,
3354 // and we must not change QDragManagers currentTarget.
3355 QWExtra *extra = w->window()->d_func()->extra;
3356 if (extra && extra->proxyWidget) {
3357 res = d->notify_helper(w, dragEvent);
3362 if (w->isEnabled() && w->acceptDrops()) {
3363 res = d->notify_helper(w, dragEvent);
3364 if (res && dragEvent->isAccepted()) {
3365 QDragManager::self()->setCurrentTarget(w);
3371 dragEvent->p = w->mapToParent(dragEvent->p.toPoint());
3372 w = w->parentWidget();
3376 case QEvent::DragMove:
3378 case QEvent::DragLeave: {
3379 QWidget* w = static_cast<QWidget *>(receiver);
3380 #ifndef QT_NO_GRAPHICSVIEW
3381 // QGraphicsProxyWidget handles its own propagation,
3382 // and we must not change QDragManagers currentTarget.
3383 QWExtra *extra = w->window()->d_func()->extra;
3384 bool isProxyWidget = extra && extra->proxyWidget;
3387 w = qobject_cast<QWidget *>(QDragManager::self()->currentTarget());
3392 if (e->type() == QEvent::DragMove || e->type() == QEvent::Drop) {
3393 QDropEvent *dragEvent = static_cast<QDropEvent *>(e);
3394 QWidget *origReciver = static_cast<QWidget *>(receiver);
3395 while (origReciver && w != origReciver) {
3396 dragEvent->p = origReciver->mapToParent(dragEvent->p.toPoint());
3397 origReciver = origReciver->parentWidget();
3400 res = d->notify_helper(w, e);
3401 if (e->type() != QEvent::DragMove
3402 #ifndef QT_NO_GRAPHICSVIEW
3406 QDragManager::self()->setCurrentTarget(0, e->type() == QEvent::Drop);
3410 case QEvent::TouchBegin:
3411 // Note: TouchUpdate and TouchEnd events are never propagated
3413 QWidget *widget = static_cast<QWidget *>(receiver);
3414 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
3415 bool eventAccepted = touchEvent->isAccepted();
3416 if (widget->testAttribute(Qt::WA_AcceptTouchEvents) && e->spontaneous()) {
3417 // give the widget focus if the focus policy allows it
3418 QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget,
3420 Qt::MouseFocusReason);
3424 // first, try to deliver the touch event
3425 bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
3426 touchEvent->setTarget(widget);
3427 touchEvent->setAccepted(acceptTouchEvents);
3428 QWeakPointer<QWidget> p = widget;
3429 res = acceptTouchEvents && d->notify_helper(widget, touchEvent);
3430 eventAccepted = touchEvent->isAccepted();
3432 // widget was deleted
3435 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
3437 touchEvent->spont = false;
3438 if (res && eventAccepted) {
3439 // the first widget to accept the TouchBegin gets an implicit grab.
3440 for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
3441 const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().at(i);
3442 d->activeTouchPoints[QGuiApplicationPrivate::ActiveTouchPointsKey(touchEvent->device(), touchPoint.id())].target = widget;
3445 } else if (p.isNull() || widget->isWindow() || widget->testAttribute(Qt::WA_NoMousePropagation)) {
3448 QPoint offset = widget->pos();
3449 widget = widget->parentWidget();
3450 touchEvent->setTarget(widget);
3451 for (int i = 0; i < touchEvent->_touchPoints.size(); ++i) {
3452 QTouchEvent::TouchPoint &pt = touchEvent->_touchPoints[i];
3453 QRectF rect = pt.rect();
3454 rect.moveCenter(offset);
3456 pt.d->startPos = pt.startPos() + offset;
3457 pt.d->lastPos = pt.lastPos() + offset;
3461 touchEvent->setAccepted(eventAccepted);
3464 case QEvent::RequestSoftwareInputPanel:
3465 inputMethod()->show();
3467 case QEvent::CloseSoftwareInputPanel:
3468 inputMethod()->hide();
3471 #ifndef QT_NO_GESTURES
3472 case QEvent::NativeGesture:
3474 // only propagate the first gesture event (after the GID_BEGIN)
3475 QWidget *w = static_cast<QWidget *>(receiver);
3478 res = d->notify_helper(w, e);
3479 if ((res && e->isAccepted()) || w->isWindow())
3481 w = w->parentWidget();
3485 case QEvent::Gesture:
3486 case QEvent::GestureOverride:
3488 if (receiver->isWidgetType()) {
3489 QWidget *w = static_cast<QWidget *>(receiver);
3490 QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(e);
3491 QList<QGesture *> allGestures = gestureEvent->gestures();
3493 bool eventAccepted = gestureEvent->isAccepted();
3494 bool wasAccepted = eventAccepted;
3496 // send only gestures the widget expects
3497 QList<QGesture *> gestures;
3498 QWidgetPrivate *wd = w->d_func();
3499 for (int i = 0; i < allGestures.size();) {
3500 QGesture *g = allGestures.at(i);
3501 Qt::GestureType type = g->gestureType();
3502 QMap<Qt::GestureType, Qt::GestureFlags>::iterator contextit =
3503 wd->gestureContext.find(type);
3504 bool deliver = contextit != wd->gestureContext.end() &&
3505 (g->state() == Qt::GestureStarted || w == receiver ||
3506 (contextit.value() & Qt::ReceivePartialGestures));
3508 allGestures.removeAt(i);
3514 if (!gestures.isEmpty()) { // we have gestures for this w
3515 QGestureEvent ge(gestures);
3516 ge.t = gestureEvent->t;
3517 ge.spont = gestureEvent->spont;
3518 ge.m_accept = wasAccepted;
3519 ge.m_accepted = gestureEvent->m_accepted;
3520 res = d->notify_helper(w, &ge);
3521 gestureEvent->spont = false;
3522 eventAccepted = ge.isAccepted();
3523 for (int i = 0; i < gestures.size(); ++i) {
3524 QGesture *g = gestures.at(i);
3525 // Ignore res [event return value] because handling of multiple gestures
3526 // packed into a single QEvent depends on not consuming the event
3527 if (eventAccepted || ge.isAccepted(g)) {
3528 // if the gesture was accepted, mark the target widget for it
3529 gestureEvent->m_targetWidgets[g->gestureType()] = w;
3530 gestureEvent->setAccepted(g, true);
3532 // if the gesture was explicitly ignored by the application,
3533 // put it back so a parent can get it
3534 allGestures.append(g);
3538 if (allGestures.isEmpty()) // everything delivered
3542 w = w->parentWidget();
3544 foreach (QGesture *g, allGestures)
3545 gestureEvent->setAccepted(g, false);
3546 gestureEvent->m_accept = false; // to make sure we check individual gestures
3548 res = d->notify_helper(receiver, e);
3552 #endif // QT_NO_GESTURES
3554 res = d->notify_helper(receiver, e);
3561 bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
3563 // send to all application event filters
3564 if (sendThroughApplicationEventFilters(receiver, e))
3567 if (receiver->isWidgetType()) {
3568 QWidget *widget = static_cast<QWidget *>(receiver);
3570 #if !defined(Q_OS_WINCE) || (defined(GWES_ICONCURS) && !defined(QT_NO_CURSOR))
3571 // toggle HasMouse widget state on enter and leave
3572 if ((e->type() == QEvent::Enter || e->type() == QEvent::DragEnter) &&
3573 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == widget->window()))
3574 widget->setAttribute(Qt::WA_UnderMouse, true);
3575 else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave)
3576 widget->setAttribute(Qt::WA_UnderMouse, false);
3579 if (QLayout *layout=widget->d_func()->layout) {
3580 layout->widgetEvent(e);
3584 // send to all receiver event filters
3585 if (sendThroughObjectEventFilters(receiver, e))
3588 // deliver the event
3589 bool consumed = receiver->event(e);
3596 \class QSessionManager
3597 \brief The QSessionManager class provides access to the session manager.
3601 A session manager in a desktop environment (in which Qt GUI applications
3602 live) keeps track of a session, which is a group of running applications,
3603 each of which has a particular state. The state of an application contains
3604 (most notably) the documents the application has open and the position and
3605 size of its windows.
3607 The session manager is used to save the session, e.g., when the machine is
3608 shut down, and to restore a session, e.g., when the machine is started up.
3609 We recommend that you use QSettings to save an application's settings,
3610 for example, window positions, recently used files, etc. When the
3611 application is restarted by the session manager, you can restore the
3614 QSessionManager provides an interface between the application and the
3615 session manager so that the program can work well with the session manager.
3616 In Qt, session management requests for action are handled by the two
3617 virtual functions QApplication::commitData() and QApplication::saveState().
3618 Both provide a reference to a session manager object as argument, to allow
3619 the application to communicate with the session manager. The session
3620 manager can only be accessed through these functions.
3622 No user interaction is possible \e unless the application gets explicit
3623 permission from the session manager. You ask for permission by calling
3624 allowsInteraction() or, if it is really urgent, allowsErrorInteraction().
3625 Qt does not enforce this, but the session manager may.
3627 You can try to abort the shutdown process by calling cancel(). The default
3628 commitData() function does this if some top-level window rejected its
3631 For sophisticated session managers provided on Unix/X11, QSessionManager
3632 offers further possibilities to fine-tune an application's session
3633 management behavior: setRestartCommand(), setDiscardCommand(),
3634 setRestartHint(), setProperty(), requestPhase2(). See the respective
3635 function descriptions for further details.
3637 \sa QApplication, {Session Management}
3640 /*! \enum QSessionManager::RestartHint
3642 This enum type defines the circumstances under which this application wants
3643 to be restarted by the session manager. The current values are:
3645 \value RestartIfRunning If the application is still running when the
3646 session is shut down, it wants to be restarted
3647 at the start of the next session.
3649 \value RestartAnyway The application wants to be started at the
3650 start of the next session, no matter what.
3651 (This is useful for utilities that run just
3652 after startup and then quit.)
3654 \value RestartImmediately The application wants to be started immediately
3655 whenever it is not running.
3657 \value RestartNever The application does not want to be restarted
3660 The default hint is \c RestartIfRunning.
3665 \fn QString QSessionManager::sessionId() const
3667 Returns the identifier of the current session.
3669 If the application has been restored from an earlier session, this
3670 identifier is the same as it was in the earlier session.
3672 \sa sessionKey(), QApplication::sessionId()
3676 \fn QString QSessionManager::sessionKey() const
3678 Returns the session key in the current session.
3680 If the application has been restored from an earlier session, this key is
3681 the same as it was when the previous session ended.
3683 The session key changes with every call of commitData() or saveState().
3685 \sa sessionId(), QApplication::sessionKey()
3689 \fn void* QSessionManager::handle() const
3695 \fn bool QSessionManager::allowsInteraction()
3697 Asks the session manager for permission to interact with the user. Returns
3698 true if interaction is permitted; otherwise returns false.
3700 The rationale behind this mechanism is to make it possible to synchronize
3701 user interaction during a shutdown. Advanced session managers may ask all
3702 applications simultaneously to commit their data, resulting in a much
3705 When the interaction is completed we strongly recommend releasing the user
3706 interaction semaphore with a call to release(). This way, other
3707 applications may get the chance to interact with the user while your
3708 application is still busy saving data. (The semaphore is implicitly
3709 released when the application exits.)
3711 If the user decides to cancel the shutdown process during the interaction
3712 phase, you must tell the session manager that this has happened by calling
3715 Here's an example of how an application's QApplication::commitData() might
3718 \snippet code/src_gui_kernel_qapplication.cpp 8
3720 If an error occurred within the application while saving its data, you may
3721 want to try allowsErrorInteraction() instead.
3723 \sa QApplication::commitData(), release(), cancel()
3728 \fn bool QSessionManager::allowsErrorInteraction()
3730 Returns true if error interaction is permitted; otherwise returns false.
3732 This is similar to allowsInteraction(), but also enables the application to
3733 tell the user about any errors that occur. Session managers may give error
3734 interaction requests higher priority, which means that it is more likely
3735 that an error interaction is permitted. However, you are still not
3736 guaranteed that the session manager will allow interaction.
3738 \sa allowsInteraction(), release(), cancel()
3742 \fn void QSessionManager::release()
3744 Releases the session manager's interaction semaphore after an interaction
3747 \sa allowsInteraction(), allowsErrorInteraction()
3751 \fn void QSessionManager::cancel()
3753 Tells the session manager to cancel the shutdown process. Applications
3754 should not call this function without asking the user first.
3756 \sa allowsInteraction(), allowsErrorInteraction()
3760 \fn void QSessionManager::setRestartHint(RestartHint hint)
3762 Sets the application's restart hint to \a hint. On application startup, the
3763 hint is set to \c RestartIfRunning.
3765 \note These flags are only hints, a session manager may or may not respect
3768 We recommend setting the restart hint in QApplication::saveState() because
3769 most session managers perform a checkpoint shortly after an application's
3776 \fn QSessionManager::RestartHint QSessionManager::restartHint() const
3778 Returns the application's current restart hint. The default is
3779 \c RestartIfRunning.
3781 \sa setRestartHint()
3785 \fn void QSessionManager::setRestartCommand(const QStringList& command)
3787 If the session manager is capable of restoring sessions it will execute
3788 \a command in order to restore the application. The command defaults to
3790 \snippet code/src_gui_kernel_qapplication.cpp 9
3792 The \c -session option is mandatory; otherwise QApplication cannot tell
3793 whether it has been restored or what the current session identifier is.
3794 See QApplication::isSessionRestored() and QApplication::sessionId() for
3797 If your application is very simple, it may be possible to store the entire
3798 application state in additional command line options. This is usually a
3799 very bad idea because command lines are often limited to a few hundred
3800 bytes. Instead, use QSettings, temporary files, or a database for this
3801 purpose. By marking the data with the unique sessionId(), you will be able
3802 to restore the application in a future session.
3804 \sa restartCommand(), setDiscardCommand(), setRestartHint()
3808 \fn QStringList QSessionManager::restartCommand() const
3810 Returns the currently set restart command.
3812 To iterate over the list, you can use the \l foreach pseudo-keyword:
3814 \snippet code/src_gui_kernel_qapplication.cpp 10
3816 \sa setRestartCommand(), restartHint()
3820 \fn void QSessionManager::setDiscardCommand(const QStringList& list)
3822 Sets the discard command to the given \a list.
3824 \sa discardCommand(), setRestartCommand()
3829 \fn QStringList QSessionManager::discardCommand() const
3831 Returns the currently set discard command.
3833 To iterate over the list, you can use the \l foreach pseudo-keyword:
3835 \snippet code/src_gui_kernel_qapplication.cpp 11
3837 \sa setDiscardCommand(), restartCommand(), setRestartCommand()
3841 \fn void QSessionManager::setManagerProperty(const QString &name, const QString &value)
3844 Low-level write access to the application's identification and state
3845 records are kept in the session manager.
3847 The property called \a name has its value set to the string \a value.
3851 \fn void QSessionManager::setManagerProperty(const QString& name,
3852 const QStringList& value)
3854 Low-level write access to the application's identification and state record
3855 are kept in the session manager.
3857 The property called \a name has its value set to the string list \a value.
3861 \fn bool QSessionManager::isPhase2() const
3863 Returns true if the session manager is currently performing a second
3864 session management phase; otherwise returns false.
3870 \fn void QSessionManager::requestPhase2()
3872 Requests a second session management phase for the application. The
3873 application may then return immediately from the QApplication::commitData()
3874 or QApplication::saveState() function, and they will be called again once
3875 most or all other applications have finished their session management.
3877 The two phases are useful for applications such as the X11 window manager
3878 that need to store information about another application's windows and
3879 therefore have to wait until these applications have completed their
3880 respective session management tasks.
3882 \note If another application has requested a second phase it may get called
3883 before, simultaneously with, or after your application's second phase.
3889 \fn Qt::MacintoshVersion QApplication::macVersion()
3891 Use QSysInfo::MacintoshVersion instead.
3895 \fn QApplication::ColorMode QApplication::colorMode()
3897 Use colorSpec() instead, and use ColorSpec as the enum type.
3901 \fn void QApplication::setColorMode(ColorMode mode)
3903 Use setColorSpec() instead, and pass a ColorSpec value instead.
3907 \fn bool QApplication::hasGlobalMouseTracking()
3909 This feature does not exist anymore. This function always returns true
3914 \fn void QApplication::setGlobalMouseTracking(bool dummy)
3916 This function does nothing in Qt 4. The \a dummy parameter is ignored.
3920 \fn void QApplication::flushX()
3922 Use flush() instead.
3926 \fn void QApplication::setWinStyleHighlightColor(const QColor &c)
3928 Use the palette instead.
3931 app.setWinStyleHighlightColor(color);
3933 QPalette palette(QApplication::palette());
3934 palette.setColor(QPalette::Highlight, color);
3935 QApplication::setPalette(palette);
3940 \fn void QApplication::setPalette(const QPalette &pal, bool b, const char* className = 0)
3942 Use the two-argument overload instead.
3946 \fn void QApplication::setFont(const QFont &font, bool b, const char* className = 0)
3948 Use the two-argument overload instead.
3952 \fn const QColor &QApplication::winStyleHighlightColor()
3954 Use QApplication::palette().color(QPalette::Active, QPalette::Highlight) instead.
3958 \fn QWidget *QApplication::widgetAt(int x, int y, bool child)
3960 Use the two-argument widgetAt() overload to get the child widget. To get
3961 the top-level widget do this:
3963 \snippet code/src_gui_kernel_qapplication.cpp 12
3967 \fn QWidget *QApplication::widgetAt(const QPoint &point, bool child)
3969 Use the single-argument widgetAt() overload to get the child widget. To get
3970 the top-level widget do this:
3972 \snippet code/src_gui_kernel_qapplication.cpp 13
3975 bool QApplicationPrivate::inPopupMode() const
3977 return QApplicationPrivate::popupWidgets != 0;
3980 #ifdef QT_KEYPAD_NAVIGATION
3982 Sets the kind of focus navigation Qt should use to \a mode.
3984 This feature is available in Qt for Embedded Linux, and Windows CE
3987 \note On Windows CE this feature is disabled by default for touch device
3988 mkspecs. To enable keypad navigation, build Qt with
3989 QT_KEYPAD_NAVIGATION defined.
3993 \sa keypadNavigationEnabled()
3995 void QApplication::setNavigationMode(Qt::NavigationMode mode)
3997 QApplicationPrivate::navigationMode = mode;
4001 Returns what kind of focus navigation Qt is using.
4003 This feature is available in Qt for Embedded Linux, and Windows CE only.
4005 \note On Windows CE this feature is disabled by default for touch device
4006 mkspecs. To enable keypad navigation, build Qt with
4007 QT_KEYPAD_NAVIGATION defined.
4011 \sa keypadNavigationEnabled()
4013 Qt::NavigationMode QApplication::navigationMode()
4015 return QApplicationPrivate::navigationMode;
4019 Sets whether Qt should use focus navigation suitable for use with a
4022 This feature is available in Qt for Embedded Linux, and Windows CE only.
4024 \note On Windows CE this feature is disabled by default for touch device
4025 mkspecs. To enable keypad navigation, build Qt with
4026 QT_KEYPAD_NAVIGATION defined.
4030 \sa setNavigationMode()
4032 void QApplication::setKeypadNavigationEnabled(bool enable)
4035 QApplication::setNavigationMode(Qt::NavigationModeKeypadTabOrder);
4037 QApplication::setNavigationMode(Qt::NavigationModeNone);
4042 Returns true if Qt is set to use keypad navigation; otherwise returns
4043 false. The default value is false.
4045 This feature is available in Qt for Embedded Linux, and Windows CE only.
4047 \note On Windows CE this feature is disabled by default for touch device
4048 mkspecs. To enable keypad navigation, build Qt with
4049 QT_KEYPAD_NAVIGATION defined.
4053 \sa navigationMode()
4055 bool QApplication::keypadNavigationEnabled()
4057 return QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadTabOrder ||
4058 QApplicationPrivate::navigationMode == Qt::NavigationModeKeypadDirectional;
4063 \fn void QApplication::alert(QWidget *widget, int msec)
4066 Causes an alert to be shown for \a widget if the window is not the active
4067 window. The alert is shown for \a msec miliseconds. If \a msec is zero (the
4068 default), then the alert is shown indefinitely until the window becomes
4071 Currently this function does nothing on Qt for Embedded Linux.
4073 On Mac OS X, this works more at the application level and will cause the
4074 application icon to bounce in the dock.
4076 On Windows, this causes the window's taskbar entry to flash for a time. If
4077 \a msec is zero, the flashing will stop and the taskbar entry will turn a
4078 different color (currently orange).
4080 On X11, this will cause the window to be marked as "demands attention", the
4081 window must not be hidden (i.e. not have hide() called on it, but be
4082 visible in some sort of way) in order for this to work.
4086 \property QApplication::cursorFlashTime
4087 \brief the text cursor's flash (blink) time in milliseconds
4089 The flash time is the time required to display, invert and restore the
4090 caret display. Usually the text cursor is displayed for half the cursor
4091 flash time, then hidden for the same amount of time, but this may vary.
4093 The default value on X11 is 1000 milliseconds. On Windows, the
4094 \uicontrol{Control Panel} value is used and setting this property sets the cursor
4095 flash time for all applications.
4097 We recommend that widgets do not cache this value as it may change at any
4098 time if the user changes the global desktop settings.
4100 void QApplication::setCursorFlashTime(int msecs)
4105 int QApplication::cursorFlashTime()
4107 return qApp->styleHints()->cursorFlashTime();
4112 \property QApplication::doubleClickInterval
4113 \brief the time limit in milliseconds that distinguishes a double click
4114 from two consecutive mouse clicks
4116 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
4117 operating system's value is used.
4119 Setting the interval is not supported anymore in Qt 5.
4121 void QApplication::setDoubleClickInterval(int ms)
4126 int QApplication::doubleClickInterval()
4128 return qApp->styleHints()->mouseDoubleClickInterval();
4132 \property QApplication::keyboardInputInterval
4133 \brief the time limit in milliseconds that distinguishes a key press
4134 from two consecutive key presses
4137 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
4138 operating system's value is used.
4140 void QApplication::setKeyboardInputInterval(int ms)
4145 int QApplication::keyboardInputInterval()
4147 return qApp->styleHints()->keyboardInputInterval();
4151 \property QApplication::wheelScrollLines
4152 \brief the number of lines to scroll a widget, when the
4153 mouse wheel is rotated.
4155 If the value exceeds the widget's number of visible lines, the widget
4156 should interpret the scroll operation as a single \e{page up} or
4157 \e{page down}. If the widget is an \l{QAbstractItemView}{item view class},
4158 then the result of scrolling one \e line depends on the setting of the
4159 widget's \l{QAbstractItemView::verticalScrollMode()}{scroll mode}. Scroll
4160 one \e line can mean \l{QAbstractItemView::ScrollPerItem}{scroll one item}
4161 or \l{QAbstractItemView::ScrollPerPixel}{scroll one pixel}.
4163 By default, this property has a value of 3.
4167 \fn void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
4169 Enables the UI effect \a effect if \a enable is true, otherwise the effect
4172 \note All effects are disabled on screens running at less than 16-bit color
4175 \sa isEffectEnabled(), Qt::UIEffect, setDesktopSettingsAware()
4179 \fn bool QApplication::isEffectEnabled(Qt::UIEffect effect)
4181 Returns true if \a effect is enabled; otherwise returns false.
4183 By default, Qt will try to use the desktop settings. To prevent this, call
4184 setDesktopSettingsAware(false).
4186 \note All effects are disabled on screens running at less than 16-bit color
4189 \sa setEffectEnabled(), Qt::UIEffect
4193 \fn QWidget *QApplication::mainWidget()
4195 Returns the main application widget, or 0 if there is no main widget.
4199 \fn void QApplication::setMainWidget(QWidget *mainWidget)
4201 Sets the application's main widget to \a mainWidget.
4203 In most respects the main widget is like any other widget, except that if
4204 it is closed, the application exits. QApplication does \e not take
4205 ownership of the \a mainWidget, so if you create your main widget on the
4206 heap you must delete it yourself.
4208 You need not have a main widget; connecting lastWindowClosed() to quit()
4211 On X11, this function also resizes and moves the main widget according
4212 to the \e -geometry command-line option, so you should set the default
4213 geometry (using \l QWidget::setGeometry()) before calling setMainWidget().
4215 \sa mainWidget(), exec(), quit()
4219 \fn void QApplication::beep()
4221 Sounds the bell, using the default volume and sound. The function is \e not
4222 available in Qt for Embedded Linux.
4228 \relates QApplication
4230 A global pointer referring to the unique application object. It is
4231 equivalent to the pointer returned by the QCoreApplication::instance()
4232 function except that, in GUI applications, it is a pointer to a
4233 QApplication instance.
4235 Only one application object can be created.
4237 \sa QCoreApplication::instance()
4241 \fn QLocale QApplication::keyboardInputLocale()
4245 Returns the current keyboard input locale. Replaced with QInputMethod::locale()
4249 \fn Qt::LayoutDirection QApplication::keyboardInputDirection()*
4253 Returns the current keyboard input direction. Replaced with QInputMethod::inputDirection()
4256 bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
4258 return QGuiApplication::sendSpontaneousEvent(receiver, event);
4262 void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget,
4263 Qt::FocusPolicy focusPolicy,
4264 Qt::FocusReason focusReason)
4266 QWidget *focusWidget = widget;
4267 while (focusWidget) {
4268 if (focusWidget->isEnabled()
4269 && QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) {
4270 focusWidget->setFocus(focusReason);
4273 if (focusWidget->isWindow())
4275 focusWidget = focusWidget->parentWidget();
4279 bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy)
4282 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
4283 f = f->d_func()->extra->focus_proxy;
4285 if ((w->focusPolicy() & policy) != policy)
4287 if (w != f && (f->focusPolicy() & policy) != policy)
4292 /*! \fn void QApplication::winFocus(QWidget *widget, bool gotFocus)
4296 If \a gotFocus is true, \a widget will become the active window.
4297 Otherwise the active window is reset to 0.
4300 /*! \fn void QApplication::winMouseButtonUp()
4304 void QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent)
4306 for (int i = 0; i < touchEvent->touchPoints().count(); ++i) {
4307 QTouchEvent::TouchPoint &touchPoint = touchEvent->_touchPoints[i];
4309 // preserve the sub-pixel resolution
4310 QRectF rect = touchPoint.screenRect();
4311 const QPointF screenPos = rect.center();
4312 const QPointF delta = screenPos - screenPos.toPoint();
4314 rect.moveCenter(widget->mapFromGlobal(screenPos.toPoint()) + delta);
4315 touchPoint.d->rect = rect;
4316 touchPoint.d->startPos = widget->mapFromGlobal(touchPoint.startScreenPos().toPoint()) + delta;
4317 touchPoint.d->lastPos = widget->mapFromGlobal(touchPoint.lastScreenPos().toPoint()) + delta;
4321 void QApplicationPrivate::initializeMultitouch()
4323 initializeMultitouch_sys();
4326 void QApplicationPrivate::cleanupMultitouch()
4328 cleanupMultitouch_sys();
4331 QWidget *QApplicationPrivate::findClosestTouchPointTarget(QTouchDevice *device, const QPointF &screenPos)
4333 int closestTouchPointId = -1;
4334 QObject *closestTarget = 0;
4335 qreal closestDistance = qreal(0.);
4336 QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it = activeTouchPoints.constBegin(),
4337 ite = activeTouchPoints.constEnd();
4339 if (it.key().device == device) {
4340 const QTouchEvent::TouchPoint &touchPoint = it->touchPoint;
4341 qreal dx = screenPos.x() - touchPoint.screenPos().x();
4342 qreal dy = screenPos.y() - touchPoint.screenPos().y();
4343 qreal distance = dx * dx + dy * dy;
4344 if (closestTouchPointId == -1 || distance < closestDistance) {
4345 closestTouchPointId = touchPoint.id();
4346 closestDistance = distance;
4347 closestTarget = it.value().target.data();
4352 return static_cast<QWidget *>(closestTarget);
4355 void QApplicationPrivate::translateRawTouchEvent(QWidget *window,
4356 QTouchDevice *device,
4357 const QList<QTouchEvent::TouchPoint> &touchPoints,
4360 QApplicationPrivate *d = self;
4361 typedef QPair<Qt::TouchPointStates, QList<QTouchEvent::TouchPoint> > StatesAndTouchPoints;
4362 QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents;
4364 for (int i = 0; i < touchPoints.count(); ++i) {
4365 QTouchEvent::TouchPoint touchPoint = touchPoints.at(i);
4366 // explicitly detach from the original touch point that we got, so even
4367 // if the touchpoint structs are reused, we will make a copy that we'll
4368 // deliver to the user (which might want to store the struct for later use).
4369 touchPoint.d = touchPoint.d->detach();
4372 QWeakPointer<QObject> target;
4373 ActiveTouchPointsKey touchInfoKey(device, touchPoint.id());
4374 ActiveTouchPointsValue &touchInfo = d->activeTouchPoints[touchInfoKey];
4375 if (touchPoint.state() == Qt::TouchPointPressed) {
4376 if (device->type() == QTouchDevice::TouchPad) {
4377 // on touch-pads, send all touch points to the same widget
4378 target = d->activeTouchPoints.isEmpty()
4379 ? QWeakPointer<QObject>()
4380 : d->activeTouchPoints.constBegin().value().target;
4384 // determine which widget this event will go to
4386 window = QApplication::topLevelAt(touchPoint.screenPos().toPoint());
4389 target = window->childAt(window->mapFromGlobal(touchPoint.screenPos().toPoint()));
4394 if (device->type() == QTouchDevice::TouchScreen) {
4395 QWidget *closestWidget = d->findClosestTouchPointTarget(device, touchPoint.screenPos());
4396 QWidget *widget = static_cast<QWidget *>(target.data());
4398 && (widget->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget))) {
4399 target = closestWidget;
4403 touchInfo.target = target;
4405 target = touchInfo.target;
4409 Q_ASSERT(target.data() != 0);
4411 StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[static_cast<QWidget *>(target.data())];
4412 maskAndPoints.first |= touchPoint.state();
4413 maskAndPoints.second.append(touchPoint);
4416 if (widgetsNeedingEvents.isEmpty())
4419 QHash<QWidget *, StatesAndTouchPoints>::ConstIterator it = widgetsNeedingEvents.constBegin();
4420 const QHash<QWidget *, StatesAndTouchPoints>::ConstIterator end = widgetsNeedingEvents.constEnd();
4421 for (; it != end; ++it) {
4422 QWidget *widget = it.key();
4423 if (!QApplicationPrivate::tryModalHelper(widget, 0))
4426 QEvent::Type eventType;
4427 switch (it.value().first) {
4428 case Qt::TouchPointPressed:
4429 eventType = QEvent::TouchBegin;
4431 case Qt::TouchPointReleased:
4432 eventType = QEvent::TouchEnd;
4434 case Qt::TouchPointStationary:
4435 // don't send the event if nothing changed
4438 eventType = QEvent::TouchUpdate;
4442 QTouchEvent touchEvent(eventType,
4444 QApplication::keyboardModifiers(),
4447 updateTouchPointsForWidget(widget, &touchEvent);
4448 touchEvent.setTimestamp(timestamp);
4449 touchEvent.setWindow(window->windowHandle());
4450 touchEvent.setTarget(widget);
4452 switch (touchEvent.type()) {
4453 case QEvent::TouchBegin:
4455 // if the TouchBegin handler recurses, we assume that means the event
4456 // has been implicitly accepted and continue to send touch events
4457 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
4458 (void ) QApplication::sendSpontaneousEvent(widget, &touchEvent);
4462 if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent)) {
4463 if (touchEvent.type() == QEvent::TouchEnd)
4464 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, false);
4465 (void) QApplication::sendSpontaneousEvent(widget, &touchEvent);
4472 void QApplicationPrivate::translateTouchCancel(QTouchDevice *device, ulong timestamp)
4474 QTouchEvent touchEvent(QEvent::TouchCancel, device, QApplication::keyboardModifiers());
4475 touchEvent.setTimestamp(timestamp);
4476 QHash<ActiveTouchPointsKey, ActiveTouchPointsValue>::const_iterator it
4477 = self->activeTouchPoints.constBegin(), ite = self->activeTouchPoints.constEnd();
4478 QSet<QWidget *> widgetsNeedingCancel;
4480 QWidget *widget = static_cast<QWidget *>(it->target.data());
4482 widgetsNeedingCancel.insert(widget);
4485 for (QSet<QWidget *>::const_iterator widIt = widgetsNeedingCancel.constBegin(),
4486 widItEnd = widgetsNeedingCancel.constEnd(); widIt != widItEnd; ++widIt) {
4487 QWidget *widget = *widIt;
4488 touchEvent.setWindow(widget->windowHandle());
4489 touchEvent.setTarget(widget);
4490 QApplication::sendSpontaneousEvent(widget, &touchEvent);
4494 void QApplicationPrivate::notifyThemeChanged()
4496 QGuiApplicationPrivate::notifyThemeChanged();
4497 clearSystemPalette();
4498 initSystemPalette();
4501 #ifndef QT_NO_GESTURES
4502 QGestureManager* QGestureManager::instance()
4504 QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
4507 if (!qAppPriv->gestureManager)
4508 qAppPriv->gestureManager = new QGestureManager(qApp);
4509 return qAppPriv->gestureManager;
4511 #endif // QT_NO_GESTURES
4513 QPixmap QApplicationPrivate::applyQIconStyleHelper(QIcon::Mode mode, const QPixmap& base) const
4515 QStyleOption opt(0);
4516 opt.palette = QGuiApplication::palette();
4517 return QApplication::style()->generatedIconPixmap(mode, base, &opt);
4522 #include "moc_qapplication.cpp"