Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qapplication.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qplatformdefs.h"
7#include "qapplication.h"
8#include "qclipboard.h"
9#include "qcursor.h"
10#include "qdir.h"
11#include "qevent.h"
12#include "qfile.h"
13#include "qfileinfo.h"
14#if QT_CONFIG(graphicsview)
15#include "qgraphicsscene.h"
16#include <QtWidgets/qgraphicsproxywidget.h>
17#endif
18#include "qhash.h"
19#include "qset.h"
20#include "qlayout.h"
21#include "qpixmapcache.h"
22#include "qstyle.h"
23#include "qstyleoption.h"
24#include "qstylefactory.h"
25#if QT_CONFIG(tooltip)
26#include "qtooltip.h"
27#endif
28#include "qtranslator.h"
29#include "qvariant.h"
30#include "qwidget.h"
31#if QT_CONFIG(draganddrop)
32#include <private/qdnd_p.h>
33#endif
34#include "private/qguiapplication_p.h"
35#include "qdebug.h"
36#if QT_CONFIG(style_stylesheet)
37#include "private/qstylesheetstyle_p.h"
38#endif
39#include "private/qstyle_p.h"
40#if QT_CONFIG(messagebox)
41#include "qmessagebox.h"
42#endif
44#include <QtGui/qstylehints.h>
45#include <QtGui/qinputmethod.h>
46#include <QtGui/private/qwindow_p.h>
47#include <QtGui/qpointingdevice.h>
48#include <QtGui/private/qpointingdevice_p.h>
49#include <qpa/qplatformtheme.h>
50#if QT_CONFIG(whatsthis)
51#include <QtWidgets/QWhatsThis>
52#endif
53#if QT_CONFIG(accessibility)
54#include <QtGui/qaccessible_base.h>
55#include "private/qaccessiblewidgetfactory_p.h"
56#endif
57
58#include "private/qkeymapper_p.h"
59
60#include <qspan.h>
61#include <qthread.h>
62#include <private/qthread_p.h>
63
64#include <QtGui/private/qevent_p.h>
65#include <QtGui/private/qeventpoint_p.h>
66#include <private/qfont_p.h>
67#if QT_CONFIG(action)
68#include <private/qaction_p.h>
69#endif
70
71#include <stdlib.h>
72
73#include "qapplication_p.h"
74#include "qwidget_p.h"
75
76#include "qgesture.h"
77#include "private/qgesturemanager_p.h"
78#include <qpa/qplatformfontdatabase.h>
79
80#include "qdatetime.h"
81
82#include <qpa/qplatformwindow.h>
83#include <qpa/qplatformwindow_p.h>
84
85#include <qtwidgets_tracepoints_p.h>
86
87#ifdef Q_OS_MACOS
88#include <QtCore/private/qcore_mac_p.h>
89#endif
90
91#include <algorithm>
92#include <iterator>
93
94static void initResources()
95{
96 Q_INIT_RESOURCE(qstyle);
97
98#if QT_CONFIG(messagebox)
99 Q_INIT_RESOURCE(qmessagebox);
100#endif
101}
102
104
105Q_STATIC_LOGGING_CATEGORY(lcWidgetPopup, "qt.widgets.popup");
106
107using namespace Qt::StringLiterals;
108
110 "#include <qcoreevent.h>"
111);
112Q_TRACE_METADATA(qtwidgets, "ENUM { AUTO, RANGE User ... MaxUser } QEvent::Type;");
113Q_TRACE_POINT(qtwidgets, QApplication_notify_entry, QObject *receiver, QEvent *event, QEvent::Type type);
114Q_TRACE_POINT(qtwidgets, QApplication_notify_exit, bool consumed, bool filtered);
115
116// Helper macro for static functions to check on the existence of the application class.
117#define CHECK_QAPP_INSTANCE(...)
118 if (Q_LIKELY(QCoreApplication::instance())) {
119 } else {
120 qWarning("Must construct a QApplication first.");
121 return __VA_ARGS__;
122 }
123
124Q_CORE_EXPORT void qt_call_post_routines();
125Q_GUI_EXPORT bool qt_sendShortcutOverrideEvent(QObject *o, ulong timestamp, int k, Qt::KeyboardModifiers mods, const QString &text = QString(), bool autorep = false, ushort count = 1);
126
127QApplicationPrivate *QApplicationPrivate::self = nullptr;
128
129bool QApplicationPrivate::autoSipEnabled = true;
130
131bool QApplicationPrivate::replayMousePress = false;
132
133QApplicationPrivate::QApplicationPrivate(int &argc, char **argv)
134 : QGuiApplicationPrivate(argc, argv)
135{
136 application_type = QApplicationPrivate::Gui;
137
138#ifndef QT_NO_GESTURES
139 gestureManager = nullptr;
140 gestureWidget = nullptr;
141#endif // QT_NO_GESTURES
142
143 if (!self)
144 self = this;
145}
146
147QApplicationPrivate::~QApplicationPrivate()
148{
149 if (self == this)
150 self = nullptr;
151}
152
153void QApplicationPrivate::createEventDispatcher()
154{
155 QGuiApplicationPrivate::createEventDispatcher();
156}
157
158/*!
159 \class QApplication
160 \brief The QApplication class manages the GUI application's control
161 flow and main settings.
162
163 \inmodule QtWidgets
164
165 QApplication specializes QGuiApplication with some functionality needed
166 for QWidget-based applications. It handles widget specific initialization,
167 finalization.
168
169 For any GUI application using Qt, there is precisely \b one QApplication
170 object, no matter whether the application has 0, 1, 2 or more windows at
171 any given time. For non-QWidget based Qt applications, use QGuiApplication instead,
172 as it does not depend on the \l QtWidgets library.
173
174 Some GUI applications provide a special batch mode ie. provide command line
175 arguments for executing tasks without manual intervention. In such non-GUI
176 mode, it is often sufficient to instantiate a plain QCoreApplication to
177 avoid unnecessarily initializing resources needed for a graphical user
178 interface. The following example shows how to dynamically create an
179 appropriate type of application instance:
180
181 \snippet code/src_gui_kernel_qapplication.cpp 0
182
183 The QApplication object is accessible through the instance() function that
184 returns a pointer equivalent to the global qApp pointer.
185
186 QApplication's main areas of responsibility are:
187 \list
188 \li It initializes the application with the user's desktop settings
189 such as palette(), font() and doubleClickInterval(). It keeps
190 track of these properties in case the user changes the desktop
191 globally, for example through some kind of control panel.
192
193 \li It performs event handling, meaning that it receives events
194 from the underlying window system and dispatches them to the
195 relevant widgets. By using sendEvent() and postEvent() you can
196 send your own events to widgets.
197
198 \li It parses common command line arguments and sets its internal
199 state accordingly. See the \l{QApplication::QApplication()}
200 {constructor documentation} below for more details.
201
202 \li It defines the application's look and feel, which is
203 encapsulated in a QStyle object. This can be changed at runtime
204 with setStyle().
205
206 \li It provides localization of strings that are visible to the
207 user via translate().
208
209 \li It provides some magical objects like the clipboard().
210
211 \li It knows about the application's windows. You can ask which
212 widget is at a certain position using widgetAt(), get a list of
213 topLevelWidgets() and closeAllWindows(), etc.
214
215 \li It manages the application's mouse cursor handling, see
216 setOverrideCursor()
217 \endlist
218
219 Since the QApplication object does so much initialization, it \e{must} be
220 created before any other objects related to the user interface are created.
221 QApplication also deals with common command line arguments. Hence, it is
222 usually a good idea to create it \e before any interpretation or
223 modification of \c argv is done in the application itself.
224
225 \table
226 \header
227 \li{2,1} Groups of functions
228
229 \row
230 \li System settings
231 \li desktopSettingsAware(),
232 setDesktopSettingsAware(),
233 cursorFlashTime(),
234 setCursorFlashTime(),
235 doubleClickInterval(),
236 setDoubleClickInterval(),
237 setKeyboardInputInterval(),
238 wheelScrollLines(),
239 setWheelScrollLines(),
240 palette(),
241 setPalette(),
242 font(),
243 setFont().
244
245 \row
246 \li Event handling
247 \li exec(),
248 processEvents(),
249 exit(),
250 quit().
251 sendEvent(),
252 postEvent(),
253 sendPostedEvents(),
254 removePostedEvents(),
255 notify().
256
257 \row
258 \li GUI Styles
259 \li style(),
260 setStyle().
261
262 \row
263 \li Text handling
264 \li installTranslator(),
265 removeTranslator()
266 translate().
267
268 \row
269 \li Widgets
270 \li allWidgets(),
271 topLevelWidgets(),
272 activePopupWidget(),
273 activeModalWidget(),
274 clipboard(),
275 focusWidget(),
276 activeWindow(),
277 widgetAt().
278
279 \row
280 \li Advanced cursor handling
281 \li overrideCursor(),
282 setOverrideCursor(),
283 restoreOverrideCursor().
284
285 \row
286 \li Miscellaneous
287 \li closeAllWindows(),
288 startingUp(),
289 closingDown().
290 \endtable
291
292 \sa QCoreApplication, QAbstractEventDispatcher, QEventLoop, QSettings
293*/
294
295/*!
296 \fn QWidget *QApplication::topLevelAt(const QPoint &point)
297
298 Returns the top-level widget at the given \a point; returns \nullptr if
299 there is no such widget.
300*/
301QWidget *QApplication::topLevelAt(const QPoint &pos)
302{
303 if (const QWindow *window = QGuiApplication::topLevelAt(pos)) {
304 if (const QWidgetWindow *widgetWindow = qobject_cast<const QWidgetWindow *>(window))
305 return widgetWindow->widget();
306 }
307 return nullptr;
308}
309
310/*!
311 \fn QWidget *QApplication::topLevelAt(int x, int y)
312
313 \overload
314
315 Returns the top-level widget at the point (\a{x}, \a{y}); returns
316 0 if there is no such widget.
317*/
318
320
321QStyle *QApplicationPrivate::app_style = nullptr; // default application style
322#if QT_CONFIG(style_stylesheet)
323QString QApplicationPrivate::styleSheet; // default application stylesheet
324#endif
325QPointer<QWidget> QApplicationPrivate::leaveAfterRelease = nullptr;
326
327QFont *QApplicationPrivate::sys_font = nullptr; // default system font
328QFont *QApplicationPrivate::set_font = nullptr; // default font set by programmer
329
330QWidget *QApplicationPrivate::main_widget = nullptr; // main application widget
331QWidget *QApplicationPrivate::focus_widget = nullptr; // has keyboard input focus
332QWidget *QApplicationPrivate::hidden_focus_widget = nullptr; // will get keyboard input focus after show()
333QWidget *QApplicationPrivate::active_window = nullptr; // toplevel with keyboard focus
334#if QT_CONFIG(wheelevent)
335QPointer<QWidget> QApplicationPrivate::wheel_widget;
336#endif
339int QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
340bool QApplicationPrivate::widgetCount = false;
341
342inline bool QApplicationPrivate::isAlien(QWidget *widget)
343{
344 return widget && !widget->isWindow();
345}
346
347bool Q_WIDGETS_EXPORT qt_tab_all_widgets()
348{
349 return QGuiApplication::styleHints()->tabFocusBehavior() == Qt::TabFocusAllControls;
350}
351
352// ######## move to QApplicationPrivate
353// Default fonts (per widget type)
354Q_GLOBAL_STATIC(FontHash, app_fonts)
355// Exported accessor for use outside of this file
356FontHash *qt_app_fonts_hash() { return app_fonts(); }
357
358/*!
359 \internal
360*/
361void QApplicationPrivate::process_cmdline()
362{
363 if (styleOverride.isEmpty())
364 styleOverride = qEnvironmentVariable("QT_STYLE_OVERRIDE");
365
366 // process platform-indep command line
367 if (qt_is_tty_app || !argc)
368 return;
369
370 int i, j;
371
372 j = 1;
373 for (i=1; i<argc; i++) { // if you add anything here, modify QCoreApplication::arguments()
374 if (!argv[i])
375 continue;
376 if (*argv[i] != '-') {
377 argv[j++] = argv[i];
378 continue;
379 }
380 const char *arg = argv[i];
381 if (arg[1] == '-') // startsWith("--")
382 ++arg;
383 if (strcmp(arg, "-qdevel") == 0 || strcmp(arg, "-qdebug") == 0) {
384 // obsolete argument
385#if QT_CONFIG(style_stylesheet)
386 } else if (strcmp(arg, "-stylesheet") == 0 && i < argc -1) {
387 styleSheet = "file:///"_L1;
388 styleSheet.append(QString::fromLocal8Bit(argv[++i]));
389 } else if (strncmp(arg, "-stylesheet=", 12) == 0) {
390 styleSheet = "file:///"_L1;
391 styleSheet.append(QString::fromLocal8Bit(arg + 12));
392#endif
393 } else if (qstrcmp(arg, "-widgetcount") == 0) {
394 widgetCount = true;
395 } else {
396 argv[j++] = argv[i];
397 }
398 }
399
400 if (j < argc) {
401 argv[j] = nullptr;
402 argc = j;
403 }
404}
405
406/*!
407 Initializes the window system and constructs an application object with
408 \a argc command line arguments in \a argv.
409
410 \warning The data referred to by \a argc and \a argv must stay valid for
411 the entire lifetime of the QApplication object. In addition, \a argc must
412 be greater than zero and \a argv must contain at least one valid character
413 string.
414
415 The global \c qApp pointer refers to this application object. Only one
416 application object should be created.
417
418 This application object must be constructed before any \l{QPaintDevice}
419 {paint devices} (including widgets, pixmaps, bitmaps etc.).
420
421 \note \a argc and \a argv might be changed as Qt removes command line
422 arguments that it recognizes.
423
424 All Qt programs automatically support the following command line options:
425 \list
426 \li -style= \e style, sets the application GUI style. Possible values
427 depend on your system configuration. If you compiled Qt with
428 additional styles or have additional styles as plugins these will
429 be available to the \c -style command line option. You can also
430 set the style for all Qt applications by setting the
431 \c QT_STYLE_OVERRIDE environment variable.
432 \li -style \e style, is the same as listed above.
433 \li -stylesheet= \e stylesheet, sets the application \l styleSheet. The
434 value must be a path to a file that contains the Style Sheet.
435 \note Relative URLs in the Style Sheet file are relative to the
436 Style Sheet file's path.
437 \li -stylesheet \e stylesheet, is the same as listed above.
438 \li -widgetcount, prints debug message at the end about number of
439 widgets left undestroyed and maximum number of widgets existed at
440 the same time
441 \li -reverse, sets the application's layout direction to
442 Qt::RightToLeft
443 \li -qmljsdebugger=, activates the QML/JS debugger with a specified port.
444 The value must be of format port:1234[,block], where block is optional
445 and will make the application wait until a debugger connects to it.
446 \endlist
447
448 \sa QCoreApplication::arguments()
449*/
450
451#ifdef Q_QDOC
452QApplication::QApplication(int &argc, char **argv)
453#else
454QApplication::QApplication(int &argc, char **argv, int)
455#endif
456 : QGuiApplication(*new QApplicationPrivate(argc, argv))
457{
458 Q_D(QApplication);
459 d->init();
460}
461
462/*!
463 \internal
464*/
465void QApplicationPrivate::init()
466{
467#if defined(Q_OS_MACOS)
468 QMacAutoReleasePool pool;
469#endif
470
471 QGuiApplicationPrivate::init();
472
473 initResources();
474
475 qt_is_tty_app = (application_type == QApplicationPrivate::Tty);
476 process_cmdline();
477
478 // Must be called before initialize()
479 initializeWidgetPalettesFromTheme();
480 qt_init_tooltip_palette();
481 QApplicationPrivate::initializeWidgetFontHash();
482
483 initialize();
484 eventDispatcher->startingUp();
485
486#if QT_CONFIG(accessibility)
487 // factory for accessible interfaces for widgets shipped with Qt
488 QAccessible::installFactory(&qAccessibleFactory);
489#endif
490
491}
492
494{
495#if QT_CONFIG(tooltip)
496 if (const QPalette *toolTipPalette = QGuiApplicationPrivate::platformTheme()->palette(QPlatformTheme::ToolTipPalette))
497 QToolTip::setPalette(*toolTipPalette);
498#endif
499}
500
501extern void qRegisterWidgetsVariant();
502
503/*!
504 \class QApplicationPrivate
505 \inmodule QtWidgets
506 \internal
507*/
508
509/*!
510 Initializes the QApplication object, called from the constructors.
511*/
512void QApplicationPrivate::initialize()
513{
514 is_app_running = false; // Starting up.
515
516 QWidgetPrivate::mapper = new QWidgetMapper;
517 QWidgetPrivate::allWidgets = new QWidgetSet;
518
519 // needed for a static build.
520 qRegisterWidgetsVariant();
521
522 // needed for widgets in QML
523 QAbstractDeclarativeData::setWidgetParent = QWidgetPrivate::setWidgetParentHelper;
524
525 if (application_type != QApplicationPrivate::Tty) {
526 if (!styleOverride.isEmpty()) {
527 if (auto *style = QStyleFactory::create(styleOverride.toLower())) {
528 QApplication::setStyle(style);
529 } else {
530 qWarning("QApplication: invalid style override '%s' passed, ignoring it.\n"
531 "\tAvailable styles: %s", qPrintable(styleOverride),
532 qPrintable(QStyleFactory::keys().join(", "_L1)));
533 // Clear styleOverride so it is not picked by Qt Quick Controls (QTBUG-100563)
534 styleOverride.clear();
535 }
536 }
537
538 // Trigger default style if none was set already
539 Q_UNUSED(QApplication::style());
540 }
541
542 if (qEnvironmentVariableIntValue("QT_USE_NATIVE_WINDOWS") > 0)
543 QCoreApplication::setAttribute(Qt::AA_NativeWindows);
544
545 if (!qt_is_tty_app)
546 initializeMultitouch();
547
548 if (QGuiApplication::desktopSettingsAware())
549 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
550 QApplicationPrivate::enabledAnimations = theme->themeHint(QPlatformTheme::UiEffects).toInt();
551 }
552
553 is_app_running = true; // no longer starting up
554}
555
556void QApplicationPrivate::initializeWidgetFontHash()
557{
558 const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme();
559 if (!theme)
560 return;
561 FontHash *fontHash = app_fonts();
562 fontHash->clear();
563
564 if (const QFont *font = theme->font(QPlatformTheme::MenuFont))
565 fontHash->insert(QByteArrayLiteral("QMenu"), *font);
566 if (const QFont *font = theme->font(QPlatformTheme::MenuBarFont))
567 fontHash->insert(QByteArrayLiteral("QMenuBar"), *font);
568 if (const QFont *font = theme->font(QPlatformTheme::MenuItemFont))
569 fontHash->insert(QByteArrayLiteral("QMenuItem"), *font);
570 if (const QFont *font = theme->font(QPlatformTheme::MessageBoxFont))
571 fontHash->insert(QByteArrayLiteral("QMessageBox"), *font);
572 if (const QFont *font = theme->font(QPlatformTheme::LabelFont))
573 fontHash->insert(QByteArrayLiteral("QLabel"), *font);
574 if (const QFont *font = theme->font(QPlatformTheme::TipLabelFont))
575 fontHash->insert(QByteArrayLiteral("QTipLabel"), *font);
576 if (const QFont *font = theme->font(QPlatformTheme::TitleBarFont))
577 fontHash->insert(QByteArrayLiteral("QTitleBar"), *font);
578 if (const QFont *font = theme->font(QPlatformTheme::StatusBarFont))
579 fontHash->insert(QByteArrayLiteral("QStatusBar"), *font);
580 if (const QFont *font = theme->font(QPlatformTheme::MdiSubWindowTitleFont))
581 fontHash->insert(QByteArrayLiteral("QMdiSubWindowTitleBar"), *font);
582 if (const QFont *font = theme->font(QPlatformTheme::DockWidgetTitleFont))
583 fontHash->insert(QByteArrayLiteral("QDockWidgetTitle"), *font);
584 if (const QFont *font = theme->font(QPlatformTheme::PushButtonFont))
585 fontHash->insert(QByteArrayLiteral("QPushButton"), *font);
586 if (const QFont *font = theme->font(QPlatformTheme::CheckBoxFont))
587 fontHash->insert(QByteArrayLiteral("QCheckBox"), *font);
588 if (const QFont *font = theme->font(QPlatformTheme::RadioButtonFont))
589 fontHash->insert(QByteArrayLiteral("QRadioButton"), *font);
590 if (const QFont *font = theme->font(QPlatformTheme::ToolButtonFont))
591 fontHash->insert(QByteArrayLiteral("QToolButton"), *font);
592 if (const QFont *font = theme->font(QPlatformTheme::ItemViewFont))
593 fontHash->insert(QByteArrayLiteral("QAbstractItemView"), *font);
594 if (const QFont *font = theme->font(QPlatformTheme::ListViewFont))
595 fontHash->insert(QByteArrayLiteral("QListView"), *font);
596 if (const QFont *font = theme->font(QPlatformTheme::HeaderViewFont))
597 fontHash->insert(QByteArrayLiteral("QHeaderView"), *font);
598 if (const QFont *font = theme->font(QPlatformTheme::ListBoxFont))
599 fontHash->insert(QByteArrayLiteral("QListBox"), *font);
600 if (const QFont *font = theme->font(QPlatformTheme::ComboMenuItemFont))
601 fontHash->insert(QByteArrayLiteral("QComboMenuItem"), *font);
602 if (const QFont *font = theme->font(QPlatformTheme::ComboLineEditFont))
603 fontHash->insert(QByteArrayLiteral("QComboLineEdit"), *font);
604 if (const QFont *font = theme->font(QPlatformTheme::SmallFont))
605 fontHash->insert(QByteArrayLiteral("QSmallFont"), *font);
606 if (const QFont *font = theme->font(QPlatformTheme::MiniFont))
607 fontHash->insert(QByteArrayLiteral("QMiniFont"), *font);
608}
609
610/*****************************************************************************
611 Functions returning the active popup and modal widgets.
612 *****************************************************************************/
613
614/*!
615 Returns the active popup widget.
616
617 A popup widget is a special top-level widget that sets the \c
618 Qt::WType_Popup widget flag, e.g. the QMenu widget. When the application
619 opens a popup widget, all events are sent to the popup. Normal widgets and
620 modal widgets cannot be accessed before the popup widget is closed.
621
622 Only other popup widgets may be opened when a popup widget is shown. The
623 popup widgets are organized in a stack. This function returns the active
624 popup widget at the top of the stack.
625
626 \sa activeModalWidget(), topLevelWidgets()
627*/
628
629QWidget *QApplication::activePopupWidget()
630{
631 auto *win = qobject_cast<QWidgetWindow *>(QGuiApplicationPrivate::activePopupWindow());
632 return win ? win->widget() : nullptr;
633}
634
635
636/*!
637 Returns the active modal widget.
638
639 A modal widget is a special top-level widget which is a subclass of QDialog
640 that specifies the modal parameter of the constructor as true. A modal
641 widget must be closed before the user can continue with other parts of the
642 program.
643
644 Modal widgets are organized in a stack. This function returns the active
645 modal widget at the top of the stack.
646
647 \sa activePopupWidget(), topLevelWidgets()
648*/
649
650QWidget *QApplication::activeModalWidget()
651{
652 QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(modalWindow());
653 return widgetWindow ? widgetWindow->widget() : nullptr;
654}
655
656/*!
657 Cleans up any window system resources that were allocated by this
658 application. Sets the global variable \c qApp to \nullptr.
659*/
660
661QApplication::~QApplication()
662{
663 Q_D(QApplication);
664
665 //### this should probable be done even later
666 qt_call_post_routines();
667
668 // kill timers before closing down the dispatcher
669 d->toolTipWakeUp.stop();
670 d->toolTipFallAsleep.stop();
671
672 QApplicationPrivate::is_app_closing = true;
673 QApplicationPrivate::is_app_running = false;
674
675 delete QWidgetPrivate::mapper;
676 QWidgetPrivate::mapper = nullptr;
677
678 // delete all widgets
679 if (QWidgetPrivate::allWidgets) {
680 QWidgetSet *mySet = QWidgetPrivate::allWidgets;
681 QWidgetPrivate::allWidgets = nullptr;
682 for (QWidgetSet::ConstIterator it = mySet->constBegin(), cend = mySet->constEnd(); it != cend; ++it) {
683 QWidget *w = *it;
684 if (!w->parent()) // window
685 w->destroy(true, true);
686 }
687 delete mySet;
688 }
689
690 QApplicationPrivate::widgetPalettes.clear();
691
692 delete QApplicationPrivate::sys_font;
693 QApplicationPrivate::sys_font = nullptr;
694 delete QApplicationPrivate::set_font;
695 QApplicationPrivate::set_font = nullptr;
696 if (app_fonts.exists())
697 app_fonts()->clear();
698
699 delete QApplicationPrivate::app_style;
700 QApplicationPrivate::app_style = nullptr;
701
702#if QT_CONFIG(draganddrop)
703 if (!qt_is_tty_app)
704 delete QDragManager::self();
705#endif
706
707 d->cleanupMultitouch();
708
709 QPixmapCache::clear();
710
711 QApplicationPrivate::active_window = nullptr; //### this should not be necessary
712
713 if (QApplicationPrivate::widgetCount)
714 qDebug("Widgets left: %i Max widgets: %i \n", QWidgetPrivate::instanceCounter, QWidgetPrivate::maxInstances);
715
716 QApplicationPrivate::obey_desktop_settings = true;
717
718 QApplicationPrivate::enabledAnimations = QPlatformTheme::GeneralUiEffect;
719 QApplicationPrivate::widgetCount = false;
720}
721
722/*!
723 \fn QWidget *QApplication::widgetAt(const QPoint &point)
724
725 Returns the widget at global screen position \a point, or \nullptr
726 if there is no Qt widget there.
727
728 This function can be slow.
729
730 \sa QCursor::pos(), QWidget::grabMouse(), QWidget::grabKeyboard()
731*/
732QWidget *QApplication::widgetAt(const QPoint &p)
733{
734 QWidget *window = QApplication::topLevelAt(p);
735 if (!window)
736 return nullptr;
737
738 QWidget *child = nullptr;
739
740 if (!window->testAttribute(Qt::WA_TransparentForMouseEvents))
741 child = window->childAt(window->mapFromGlobal(p));
742
743 if (child)
744 return child;
745
746 if (window->testAttribute(Qt::WA_TransparentForMouseEvents)) {
747 //shoot a hole in the widget and try once again,
748 //suboptimal on Qt for Embedded Linux where we do
749 //know the stacking order of the toplevels.
750 int x = p.x();
751 int y = p.y();
752 QRegion oldmask = window->mask();
753 QPoint wpoint = window->mapFromGlobal(QPoint(x, y));
754 QRegion newmask = (oldmask.isEmpty() ? QRegion(window->rect()) : oldmask)
755 - QRegion(wpoint.x(), wpoint.y(), 1, 1);
756 window->setMask(newmask);
757 QWidget *recurse = nullptr;
758 if (QApplication::topLevelAt(p) != window) // verify recursion will terminate
759 recurse = widgetAt(x, y);
760 if (oldmask.isEmpty())
761 window->clearMask();
762 else
763 window->setMask(oldmask);
764 return recurse;
765 }
766 return window;
767}
768
769/*!
770 \fn QWidget *QApplication::widgetAt(int x, int y)
771
772 \overload
773
774 Returns the widget at global screen position (\a x, \a y), or
775 \nullptr if there is no Qt widget there.
776*/
777
778/*!
779 \internal
780*/
781#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
782bool QApplication::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
783{
784 return d_func()->compressEvent(event, receiver, postedEvents);
785}
786#endif
787
788bool QApplicationPrivate::compressEvent(QEvent *event, QObject *receiver, QPostEventList *postedEvents)
789{
790 // Only compress the following events:
791 const QEvent::Type type = event->type();
792 switch (type) {
793 case QEvent::UpdateRequest:
794 case QEvent::UpdateLater:
795 case QEvent::LayoutRequest:
796 case QEvent::Resize:
797 case QEvent::Move:
798 case QEvent::LanguageChange:
799 break;
800 default:
801 return QGuiApplicationPrivate::compressEvent(event, receiver, postedEvents);
802 }
803
804 // Events before startOffset have already been delivered by sendPostedEvents()
805 const auto pending = QSpan(std::as_const(*postedEvents)).subspan(postedEvents->startOffset);
806 for (const auto &postedEvent : pending) {
807
808 // Continue, unless a valid event of the same type exists for the same receiver
809 if (postedEvent.receiver != receiver
810 || !postedEvent.event
811 || postedEvent.event->type() != type) {
812 continue;
813 }
814
815 // Handle type specific compression
816 switch (type) {
817 case QEvent::Resize:
818 static_cast<QResizeEvent *>(postedEvent.event)->m_size =
819 static_cast<const QResizeEvent *>(event)->size();
820 break;
821 case QEvent::Move:
822 static_cast<QMoveEvent *>(postedEvent.event)->m_pos =
823 static_cast<const QMoveEvent *>(event)->pos();
824 break;
825 case QEvent::UpdateLater:
826 static_cast<QUpdateLaterEvent *>(postedEvent.event)->m_region +=
827 static_cast<const QUpdateLaterEvent *>(event)->region();
828 break;
829 case QEvent::UpdateRequest:
830 case QEvent::LanguageChange:
831 case QEvent::LayoutRequest:
832 break;
833 default:
834 continue;
835 }
836 delete event;
837 return true;
838 }
839 return false;
840}
841
842/*!
843 \property QApplication::styleSheet
844 \brief the application style sheet
845 \since 4.2
846
847 The application style sheet applies to all widgets in the application, in
848 addition to any style sheet set on individual widgets. See
849 \l{Qt Style Sheets} for the cascading rules.
850
851 Setting this property replaces the application style with a style sheet
852 style that wraps the current \l{style()}{style}, and every later change
853 repolishes all widgets in the application. Set the style sheet once,
854 before the first window is shown, and do not use it to switch themes at
855 runtime. For when to use style sheets at all, see
856 \l{Styling Approaches for Qt Widgets}.
857
858 If the value is a \c{file:///} URL, Qt loads the style sheet from the named
859 file and resolves relative URLs inside it, such as image references, against
860 that file's directory. Only the application style sheet accepts a
861 \c{file:///} URL; \l QWidget::styleSheet does not.
862
863 By default, this property is an empty string unless the user specifies the
864 \c{-stylesheet} option on the command line when running the application;
865 that option sets this property to a \c{file:///} URL for the given file.
866
867 \sa QWidget::styleSheet, setStyle(), {Qt Style Sheets},
868 {Styling Approaches for Qt Widgets}
869*/
870
871/*!
872 \property QApplication::autoSipEnabled
873 \since 4.5
874 \brief toggles automatic SIP (software input panel) visibility
875
876 Set this property to \c true to automatically display the SIP when entering
877 widgets that accept keyboard input. This property only affects widgets with
878 the WA_InputMethodEnabled attribute set, and is typically used to launch
879 a virtual keyboard on devices which have very few or no keys.
880
881 \b{ The property only has an effect on platforms that use software input
882 panels.}
883
884 The default is platform dependent.
885*/
886void QApplication::setAutoSipEnabled(const bool enabled)
887{
888 QApplicationPrivate::autoSipEnabled = enabled;
889}
890
891bool QApplication::autoSipEnabled() const
892{
893 return QApplicationPrivate::autoSipEnabled;
894}
895
896#if QT_CONFIG(style_stylesheet)
897
898QString QApplication::styleSheet() const
899{
900 return QApplicationPrivate::styleSheet;
901}
902
903void QApplication::setStyleSheet(const QString& styleSheet)
904{
905 QApplicationPrivate::styleSheet = styleSheet;
906 QStyleSheetStyle *styleSheetStyle = qt_styleSheet(QApplicationPrivate::app_style);
907 if (styleSheet.isEmpty()) { // application style sheet removed
908 if (!styleSheetStyle)
909 return; // there was no stylesheet before
910 setStyle(styleSheetStyle->base);
911 } else if (styleSheetStyle) { // style sheet update, just repolish
912 styleSheetStyle->repolish(qApp);
913 } else { // stylesheet set the first time
914 QStyleSheetStyle *newStyleSheetStyle = new QStyleSheetStyle(QApplicationPrivate::app_style);
915 QApplicationPrivate::app_style->setParent(newStyleSheetStyle);
916 setStyle(newStyleSheetStyle);
917 }
918}
919
920#endif // QT_NO_STYLE_STYLESHEET
921
922/*!
923 Returns the application's style object.
924
925 \sa setStyle(), QStyle
926*/
927QStyle *QApplication::style()
928{
929 if (!QApplicationPrivate::app_style) {
930 // Create default style
931 if (!qobject_cast<QApplication *>(QCoreApplication::instance())) {
932 Q_ASSERT(!"No style available without QApplication!");
933 return nullptr;
934 }
935
936 auto &defaultStyle = QApplicationPrivate::app_style;
937
938 defaultStyle = QStyleFactory::create(QApplicationPrivate::desktopStyleKey());
939 if (!defaultStyle) {
940 const QStringList styles = QStyleFactory::keys();
941 for (const auto &style : styles) {
942 if ((defaultStyle = QStyleFactory::create(style)))
943 break;
944 }
945 }
946 if (!defaultStyle) {
947 Q_ASSERT(!"No styles available!");
948 return nullptr;
949 }
950
951 // Take ownership of the style
952 defaultStyle->setParent(qApp);
953
954 QGuiApplicationPrivate::updatePalette();
955
956#if QT_CONFIG(style_stylesheet)
957 if (!QApplicationPrivate::styleSheet.isEmpty()) {
958 qApp->setStyleSheet(QApplicationPrivate::styleSheet);
959 } else
960#endif
961 {
962 defaultStyle->polish(qApp);
963 }
964 }
965
966 return QApplicationPrivate::app_style;
967}
968
969/*!
970 Sets the application's GUI style to \a style. Ownership of the style object
971 is transferred to QApplication, so QApplication will delete the style
972 object on application exit or when a new style is set and the old style is
973 still the parent of the application object.
974
975 Example usage:
976 \snippet code/src_gui_kernel_qapplication.cpp 1
977
978 When switching application styles, the color palette is set back to the
979 initial colors or the system defaults. This is necessary since certain
980 styles have to adapt the color palette to be fully style-guide compliant.
981
982 Setting the style before a palette has been set, i.e., before creating
983 QApplication, will cause the application to use QStyle::standardPalette()
984 for the palette.
985
986 \sa style(), QStyle, setPalette(), desktopSettingsAware()
987*/
988void QApplication::setStyle(QStyle *style)
989{
990 if (!style || style == QApplicationPrivate::app_style)
991 return;
992
993 QWidgetList all = allWidgets();
994
995 // clean up the old style
996 if (QApplicationPrivate::app_style) {
997 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
998 for (QWidgetList::ConstIterator it = all.constBegin(), cend = all.constEnd(); it != cend; ++it) {
999 QWidget *w = *it;
1000 if (w->testAttribute(Qt::WA_WState_Polished)) // has been polished
1001 QApplicationPrivate::app_style->unpolish(w);
1002 }
1003 }
1004 QApplicationPrivate::app_style->unpolish(qApp);
1005 }
1006
1007 QStyle *old = QApplicationPrivate::app_style; // save
1008
1009#if QT_CONFIG(style_stylesheet)
1010 if (!QApplicationPrivate::styleSheet.isEmpty() && !qt_styleSheet(style)) {
1011 // we have a stylesheet already and a new style is being set
1012 QStyleSheetStyle *newStyleSheetStyle = new QStyleSheetStyle(style);
1013 style->setParent(newStyleSheetStyle);
1014 QApplicationPrivate::app_style = newStyleSheetStyle;
1015 } else
1016#endif // QT_NO_STYLE_STYLESHEET
1017 QApplicationPrivate::app_style = style;
1018 QApplicationPrivate::app_style->setParent(qApp); // take ownership
1019
1020 // Take care of possible palette requirements of certain
1021 // styles. Do it before polishing the application since the
1022 // style might call QApplication::setPalette() itself.
1023 QGuiApplicationPrivate::updatePalette();
1024
1025 // The default widget font hash is based on the platform theme,
1026 // not the style, but the widget fonts could in theory have been
1027 // affected by polish of the previous style, without a proper
1028 // cleanup in unpolish, so reset it now before polishing the
1029 // new style.
1030 QApplicationPrivate::initializeWidgetFontHash();
1031
1032 // initialize the application with the new style
1033 QApplicationPrivate::app_style->polish(qApp);
1034
1035 // re-polish existing widgets if necessary
1036 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1037 for (QWidgetList::ConstIterator it = all.constBegin(), cend = all.constEnd(); it != cend; ++it) {
1038 QWidget *w = *it;
1039 if (w->testAttribute(Qt::WA_WState_Polished)) {
1040 if (w->style() == QApplicationPrivate::app_style)
1041 QApplicationPrivate::app_style->polish(w); // repolish
1042#if QT_CONFIG(style_stylesheet)
1043 else
1044 w->setStyleSheet(w->styleSheet()); // touch
1045#endif
1046 }
1047 }
1048
1049 for (QWidgetList::ConstIterator it = all.constBegin(), cend = all.constEnd(); it != cend; ++it) {
1050 QWidget *w = *it;
1051 if (!w->testAttribute(Qt::WA_SetStyle)) {
1052 QEvent e(QEvent::StyleChange);
1053 QCoreApplication::sendEvent(w, &e);
1054 w->update();
1055 }
1056 }
1057 }
1058
1059#if QT_CONFIG(style_stylesheet)
1060 if (QStyleSheetStyle *oldStyleSheetStyle = qt_styleSheet(old)) {
1061 oldStyleSheetStyle->deref();
1062 } else
1063#endif
1064 if (old && old->parent() == qApp) {
1065 delete old;
1066 }
1067
1068 if (QApplicationPrivate::focus_widget) {
1069 QFocusEvent in(QEvent::FocusIn, Qt::OtherFocusReason);
1070 QCoreApplication::sendEvent(QApplicationPrivate::focus_widget->style(), &in);
1071 QApplicationPrivate::focus_widget->update();
1072 }
1073}
1074
1075/*!
1076 \overload
1077
1078 Requests a QStyle object for \a style from the QStyleFactory.
1079
1080 The string must be one of the QStyleFactory::keys(), typically one of
1081 "windows", "windowsvista", "fusion", or "macos". Style
1082 names are case insensitive.
1083
1084 Returns \nullptr if an unknown \a style is passed, otherwise the QStyle object
1085 returned is set as the application's GUI style.
1086
1087 \warning To ensure that the application's style is set correctly, it is
1088 best to call this function before the QApplication constructor, if
1089 possible.
1090*/
1091QStyle* QApplication::setStyle(const QString& style)
1092{
1093 QStyle *s = QStyleFactory::create(style);
1094 if (!s)
1095 return nullptr;
1096
1097 setStyle(s);
1098 return s;
1099}
1100
1101// Widget specific palettes
1102QApplicationPrivate::PaletteHash QApplicationPrivate::widgetPalettes;
1103
1104QPalette QApplicationPrivate::basePalette() const
1105{
1106 // Start out with a palette based on the style, in case there's no theme
1107 // available, or so that we can fill in missing roles in the theme.
1108 QPalette palette = app_style ? app_style->standardPalette() : Qt::gray;
1109
1110 // Prefer theme palette if available, but fill in missing roles from style
1111 // for compatibility. Note that the style's standard palette is not prioritized
1112 // over the theme palette, as the documented way of applying the style's palette
1113 // is to set it explicitly using QApplication::setPalette().
1114 if (const QPalette *themePalette = platformTheme() ? platformTheme()->palette() : nullptr)
1115 palette = themePalette->resolve(palette);
1116
1117 // This palette now is Qt-generated, so reset the resolve mask. This allows
1118 // QStyle::polish implementations to respect palettes that are user provided,
1119 // by checking if the palette has a brush set for a color that the style might
1120 // otherwise overwrite.
1121 palette.setResolveMask(0);
1122
1123 // Finish off by letting the application style polish the palette. This will
1124 // not result in the polished palette becoming a user-set palette, as the
1125 // resulting base palette is only used as a fallback, with the resolve mask
1126 // set to 0.
1127 if (app_style)
1128 app_style->polish(palette);
1129
1130 return palette;
1131}
1132
1133/*!
1134 \fn QPalette QApplication::palette(const QWidget* widget)
1135
1136 If a \a widget is passed, the default palette for the widget's class is
1137 returned. This may or may not be the application palette. In most cases
1138 there is no special palette for certain types of widgets, but one notable
1139 exception is the popup menu under Windows, if the user has defined a
1140 special background color for menus in the display settings.
1141
1142 \sa setPalette(), QWidget::palette()
1143*/
1144QPalette QApplication::palette(const QWidget* w)
1145{
1146 auto &widgetPalettes = QApplicationPrivate::widgetPalettes;
1147 if (w && !widgetPalettes.isEmpty()) {
1148 for (const auto *metaObject = w->metaObject(); metaObject != nullptr; metaObject = metaObject->superClass()) {
1149 auto it = widgetPalettes.constFind(metaObject->className());
1150 if (it != widgetPalettes.constEnd())
1151 return *it;
1152 }
1153 }
1154 return palette();
1155}
1156
1157/*!
1158 \overload
1159
1160 Returns the palette for widgets of the given \a className.
1161
1162 \sa setPalette(), QWidget::palette()
1163*/
1164QPalette QApplication::palette(const char *className)
1165{
1166 auto &widgetPalettes = QApplicationPrivate::widgetPalettes;
1167 if (className && !widgetPalettes.isEmpty()) {
1168 auto it = widgetPalettes.constFind(className);
1169 if (it != widgetPalettes.constEnd())
1170 return *it;
1171 }
1172
1173 return QGuiApplication::palette();
1174}
1175
1176/*!
1177 Changes the application palette to \a palette.
1178
1179 If \a className is passed, the change applies only to widgets that inherit
1180 \a className (as reported by QObject::inherits()). If \a className is left
1181 0, the change affects all widgets, thus overriding any previously set class
1182 specific palettes.
1183
1184 The palette may be changed according to the current GUI style in
1185 QStyle::polish().
1186
1187 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1188 When using style sheets, the palette of a widget can be customized using
1189 the "color", "background-color", "selection-color",
1190 "selection-background-color" and "alternate-background-color".
1191
1192 \note Some styles do not use the palette for all drawing, for instance, if
1193 they make use of native theme engines. This is the case for the
1194 Windows Vista and \macos styles.
1195
1196 \sa QWidget::setPalette(), palette(), QStyle::polish()
1197*/
1198void QApplication::setPalette(const QPalette &palette, const char* className)
1199{
1200 if (className) {
1201 QPalette polishedPalette = palette;
1202 if (QApplicationPrivate::app_style) {
1203 auto originalResolveMask = palette.resolveMask();
1204 QApplicationPrivate::app_style->polish(polishedPalette);
1205 polishedPalette.setResolveMask(originalResolveMask);
1206 }
1207
1208 QApplicationPrivate::widgetPalettes.insert(className, polishedPalette);
1209 if (qApp)
1210 qApp->d_func()->handlePaletteChanged(className);
1211 } else {
1212 QGuiApplication::setPalette(palette);
1213 }
1214}
1215
1216void QApplicationPrivate::handlePaletteChanged(const char *className)
1217{
1218 if (!is_app_running || is_app_closing)
1219 return;
1220
1221 // Setting the global application palette is documented to
1222 // reset any previously set class specific widget palettes.
1223 if (!className && !widgetPalettes.isEmpty())
1224 widgetPalettes.clear();
1225
1226 QGuiApplicationPrivate::handlePaletteChanged(className);
1227
1228 QEvent event(QEvent::ApplicationPaletteChange);
1229 const QWidgetList widgets = QApplication::allWidgets();
1230 for (auto widget : widgets) {
1231 if (!widget->isWindow() && widget->inherits(className))
1232 QCoreApplication::sendEvent(widget, &event);
1233 }
1234
1235#if QT_CONFIG(graphicsview)
1236 for (auto scene : std::as_const(scene_list))
1237 QCoreApplication::sendEvent(scene, &event);
1238#endif
1239
1240 // Palette has been reset back to the default application palette,
1241 // so we need to reinitialize the widget palettes from the theme.
1242 if (!className && !testAttribute(Qt::AA_SetPalette))
1243 initializeWidgetPalettesFromTheme();
1244}
1245
1246void QApplicationPrivate::initializeWidgetPalettesFromTheme()
1247{
1248 QPlatformTheme *platformTheme = QGuiApplicationPrivate::platformTheme();
1249 if (!platformTheme)
1250 return;
1251
1252 widgetPalettes.clear();
1253
1254 struct ThemedWidget { const char *className; QPlatformTheme::Palette palette; };
1255
1256 static const ThemedWidget themedWidgets[] = {
1257 { "QToolButton", QPlatformTheme::ToolButtonPalette },
1258 { "QAbstractButton", QPlatformTheme::ButtonPalette },
1259 { "QCheckBox", QPlatformTheme::CheckBoxPalette },
1260 { "QRadioButton", QPlatformTheme::RadioButtonPalette },
1261 { "QHeaderView", QPlatformTheme::HeaderPalette },
1262 { "QAbstractItemView", QPlatformTheme::ItemViewPalette },
1263 { "QMessageBoxLabel", QPlatformTheme::MessageBoxLabelPalette },
1264 { "QTabBar", QPlatformTheme::TabBarPalette },
1265 { "QLabel", QPlatformTheme::LabelPalette },
1266 { "QGroupBox", QPlatformTheme::GroupBoxPalette },
1267 { "QMenu", QPlatformTheme::MenuPalette },
1268 { "QMenuBar", QPlatformTheme::MenuBarPalette },
1269 { "QTextEdit", QPlatformTheme::TextEditPalette },
1270 { "QTextControl", QPlatformTheme::TextEditPalette },
1271 { "QLineEdit", QPlatformTheme::TextLineEditPalette },
1272 { "QComboBox", QPlatformTheme::ComboBoxPalette },
1273 };
1274
1275 for (const auto themedWidget : themedWidgets) {
1276 if (auto *palette = platformTheme->palette(themedWidget.palette))
1277 QApplication::setPalette(*palette, themedWidget.className);
1278 }
1279}
1280
1281/*!
1282 Returns the default application font.
1283
1284 \sa fontMetrics(), QWidget::font()
1285*/
1286QFont QApplication::font()
1287{
1288 return QGuiApplication::font();
1289}
1290
1291/*!
1292 \overload
1293
1294 Returns the default font for the \a widget. If a default font was not
1295 registered for the \a{widget}'s class, it returns the default font of
1296 its nearest registered superclass.
1297
1298 \sa fontMetrics(), setFont(), QWidget::setFont()
1299*/
1300
1301QFont QApplication::font(const QWidget *widget)
1302{
1303 typedef FontHash::const_iterator FontHashConstIt;
1304
1305 FontHash *hash = app_fonts();
1306
1307 if (widget && hash && hash->size()) {
1308#ifdef Q_OS_MACOS
1309 // short circuit for small and mini controls
1310 if (widget->testAttribute(Qt::WA_MacSmallSize)) {
1311 return hash->value(QByteArrayLiteral("QSmallFont"));
1312 } else if (widget->testAttribute(Qt::WA_MacMiniSize)) {
1313 return hash->value(QByteArrayLiteral("QMiniFont"));
1314 }
1315#endif
1316 // Return the font for the nearest registered superclass
1317 const QMetaObject *metaObj = widget->metaObject();
1318 FontHashConstIt it = hash->constFind(metaObj->className());
1319 const FontHashConstIt cend = hash->constEnd();
1320 while (it == cend && metaObj != &QWidget::staticMetaObject) {
1321 metaObj = metaObj->superClass();
1322 it = hash->constFind(metaObj->className());
1323 }
1324 if (it != cend)
1325 return it.value();
1326 }
1327 return font();
1328}
1329
1330/*!
1331 \overload
1332
1333 Returns the font for widgets of the given \a className.
1334
1335 \sa setFont(), QWidget::font()
1336*/
1337QFont QApplication::font(const char *className)
1338{
1339 FontHash *hash = app_fonts();
1340 if (className && hash && hash->size()) {
1341 QHash<QByteArray, QFont>::ConstIterator it = hash->constFind(className);
1342 if (it != hash->constEnd())
1343 return *it;
1344 }
1345 return font();
1346}
1347
1348
1349/*!
1350 Changes the default application font to \a font. If \a className is passed,
1351 the change applies only to classes that inherit \a className (as reported
1352 by QObject::inherits()).
1353
1354 On application start-up, the default font depends on the window system. It
1355 can vary depending on both the window system version and the locale. This
1356 function lets you override the default font; but overriding may be a bad
1357 idea because, for example, some locales need extra large fonts to support
1358 their special characters.
1359
1360 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
1361 The font of an application can be customized using the "font" style sheet
1362 property. To set a bold font for all QPushButtons, set the application
1363 styleSheet() as "QPushButton { font: bold }"
1364
1365 \sa font(), fontMetrics(), QWidget::setFont()
1366*/
1367
1368void QApplication::setFont(const QFont &font, const char *className)
1369{
1370 FontHash *hash = app_fonts();
1371 if (!className) {
1372 QGuiApplication::setFont(font);
1373 if (hash && hash->size())
1374 hash->clear();
1375 } else if (hash) {
1376 hash->insert(className, font);
1377 }
1378 if (QApplicationPrivate::is_app_running && !QApplicationPrivate::is_app_closing) {
1379 QEvent e(QEvent::ApplicationFontChange);
1380 QWidgetList wids = QApplication::allWidgets();
1381 for (QWidgetList::ConstIterator it = wids.constBegin(), cend = wids.constEnd(); it != cend; ++it) {
1382 QWidget *w = *it;
1383 if (!w->isWindow() && w->inherits(className)) // matching class
1384 sendEvent(w, &e);
1385 }
1386
1387#if QT_CONFIG(graphicsview)
1388 // Send to all scenes as well.
1389 QList<QGraphicsScene *> &scenes = qApp->d_func()->scene_list;
1390 for (QList<QGraphicsScene *>::ConstIterator it = scenes.constBegin();
1391 it != scenes.constEnd(); ++it) {
1392 QCoreApplication::sendEvent(*it, &e);
1393 }
1394#endif // QT_CONFIG(graphicsview)
1395 }
1396 if (!className && (!QApplicationPrivate::sys_font || !font.isCopyOf(*QApplicationPrivate::sys_font))) {
1397 if (!QApplicationPrivate::set_font)
1398 QApplicationPrivate::set_font = new QFont(font);
1399 else
1400 *QApplicationPrivate::set_font = font;
1401 }
1402}
1403
1404/*! \internal
1405*/
1406void QApplicationPrivate::setSystemFont(const QFont &font)
1407{
1408 if (!sys_font)
1409 sys_font = new QFont(font);
1410 else
1411 *sys_font = font;
1412
1413 if (!QApplicationPrivate::set_font)
1414 QApplication::setFont(*sys_font);
1415}
1416
1417/*! \internal
1418*/
1419QString QApplicationPrivate::desktopStyleKey()
1420{
1421#if defined(QT_BUILD_INTERNAL)
1422 // Allow auto-tests to override the desktop style
1423 if (QString env = qEnvironmentVariable("QT_DESKTOP_STYLE_KEY"); !env.isNull())
1424 return env;
1425#endif
1426
1427 // The platform theme might return a style that is not available, find
1428 // first valid one.
1429 if (const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme()) {
1430 const QStringList availableKeys = QStyleFactory::keys();
1431 const auto styles = theme->themeHint(QPlatformTheme::StyleNames).toStringList();
1432 for (const QString &style : styles) {
1433 if (availableKeys.contains(style, Qt::CaseInsensitive))
1434 return style;
1435 }
1436 }
1437 return QString();
1438}
1439
1440void QApplicationPrivate::notifyWindowIconChanged()
1441{
1442 QEvent ev(QEvent::ApplicationWindowIconChange);
1443 const QWidgetList list = QApplication::topLevelWidgets();
1444 QWindowList windowList = QGuiApplication::topLevelWindows();
1445
1446 // send to all top-level QWidgets
1447 for (auto *w : list) {
1448 windowList.removeOne(w->windowHandle());
1449 QCoreApplication::sendEvent(w, &ev);
1450 }
1451
1452 // in case there are any plain QWindows in this QApplication-using
1453 // application, also send the notification to them
1454 for (QWindow *w : std::as_const(windowList))
1455 QCoreApplication::sendEvent(w, &ev);
1456}
1457
1458/*!
1459 Returns a list of the top-level widgets (windows) in the application.
1460
1461 \note Some of the top-level widgets may be hidden, for example a tooltip if
1462 no tooltip is currently shown.
1463
1464 Example:
1465
1466 \snippet code/src_gui_kernel_qapplication.cpp 4
1467
1468 \sa allWidgets(), QWidget::isWindow(), QWidget::isHidden()
1469*/
1470QWidgetList QApplication::topLevelWidgets()
1471{
1472 QWidgetList list;
1473 if (QWidgetPrivate::allWidgets != nullptr) {
1474 const auto isTopLevelWidget = [] (const QWidget *w) {
1475 return w->isWindow();
1476 };
1477 std::copy_if(QWidgetPrivate::allWidgets->cbegin(), QWidgetPrivate::allWidgets->cend(),
1478 std::back_inserter(list), isTopLevelWidget);
1479 }
1480 return list;
1481}
1482
1483/*!
1484 Returns a list of all the widgets in the application.
1485
1486 The list is empty (QList::isEmpty()) if there are no widgets.
1487
1488 \note Some of the widgets may be hidden.
1489
1490 Example:
1491 \snippet code/src_gui_kernel_qapplication.cpp 5
1492
1493 \sa topLevelWidgets(), QWidget::isVisible()
1494*/
1495
1496QWidgetList QApplication::allWidgets()
1497{
1498 if (QWidgetPrivate::allWidgets)
1499 return QWidgetPrivate::allWidgets->values();
1500 return QWidgetList();
1501}
1502
1503/*!
1504 Returns the application widget that has the keyboard input focus,
1505 or \nullptr if no widget in this application has the focus.
1506
1507 \sa QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), focusChanged()
1508*/
1509
1510QWidget *QApplication::focusWidget()
1511{
1512 return QApplicationPrivate::focus_widget;
1513}
1514
1515void QApplicationPrivate::setFocusWidget(QWidget *focus, Qt::FocusReason reason)
1516{
1517#if QT_CONFIG(graphicsview)
1518 if (focus && focus->window()->graphicsProxyWidget())
1519 return;
1520#endif
1521
1522 hidden_focus_widget = nullptr;
1523
1524 if (focus != focus_widget) {
1525 if (focus && focus->isHidden()) {
1526 hidden_focus_widget = focus;
1527 return;
1528 }
1529
1530 if (focus) {
1531 if ((reason == Qt::BacktabFocusReason || reason == Qt::TabFocusReason)
1532 && qt_in_tab_key_event)
1533 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1534 else if (reason == Qt::ShortcutFocusReason) {
1535 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange);
1536 } else if (reason != Qt::ActiveWindowFocusReason) {
1537 focus->window()->setAttribute(Qt::WA_KeyboardFocusChange, false);
1538 }
1539 }
1540 QWidget *prev = focus_widget;
1541 focus_widget = focus;
1542
1543 if (focus_widget)
1544 focus_widget->d_func()->setFocus_sys();
1545
1546 if (reason != Qt::NoFocusReason) {
1547
1548 //send events
1549 if (prev) {
1550 QFocusEvent out(QEvent::FocusOut, reason);
1551 QPointer<QWidget> that = prev;
1552 QCoreApplication::sendEvent(prev, &out);
1553 if (that)
1554 QCoreApplication::sendEvent(that->style(), &out);
1555 }
1556 if (focus && QApplicationPrivate::focus_widget == focus) {
1557 QFocusEvent in(QEvent::FocusIn, reason);
1558 QPointer<QWidget> that = focus;
1559 QCoreApplication::sendEvent(focus, &in);
1560 if (that)
1561 QCoreApplication::sendEvent(that->style(), &in);
1562 }
1563 emit qApp->focusChanged(prev, focus_widget);
1564 }
1565 }
1566}
1567
1568
1569/*!
1570 Returns the application top-level window that has the keyboard input focus,
1571 or \nullptr if no application window has the focus. There might be an
1572 activeWindow() even if there is no focusWidget(), for example if no widget
1573 in that window accepts key events.
1574
1575 \sa QWidget::setFocus(), QWidget::hasFocus(), focusWidget()
1576*/
1577
1578QWidget *QApplication::activeWindow()
1579{
1580 return QApplicationPrivate::active_window;
1581}
1582
1583/*!
1584 \fn QFontMetrics QApplication::fontMetrics()
1585 \deprecated [6.0] Use QFontMetricsF(qApp->font()) instead.
1586
1587 Returns display (screen) font metrics for the application font. For more
1588 information about the difference between \l QFontMetrics and \l QFontMetricsF,
1589 see the detailed description of \l QFontMetrics.
1590
1591 \sa font(), setFont(), QWidget::fontMetrics(), QPainter::fontMetrics()
1592*/
1593
1594#if QT_DEPRECATED_SINCE(6,0)
1595QFontMetrics QApplication::fontMetrics()
1596{
1597 return QFontMetrics(qApp->font());
1598}
1599#endif
1600
1601bool QApplicationPrivate::tryCloseAllWidgetWindows(QWindowList *processedWindows)
1602{
1603 Q_ASSERT(processedWindows);
1604 while (QWidget *w = QApplication::activeModalWidget()) {
1605 if (!w->isVisible() || w->data->is_closing)
1606 break;
1607 QWindow *window = w->windowHandle();
1608 if (!window->close()) // Qt::WA_DeleteOnClose may cause deletion.
1609 return false;
1610 if (window)
1611 processedWindows->append(window);
1612 }
1613
1614retry:
1615 const QWidgetList list = QApplication::topLevelWidgets();
1616 for (auto *w : list) {
1617 if (w->isVisible() && !w->testAttribute(Qt::WA_DontShowOnScreen) && !w->data->is_closing) {
1618 QWindow *window = w->windowHandle();
1619 if (!window->close()) // Qt::WA_DeleteOnClose may cause deletion.
1620 return false;
1621 if (window)
1622 processedWindows->append(window);
1623 goto retry;
1624 }
1625 }
1626 return true;
1627}
1628
1629/*!
1630 Closes all top-level windows.
1631
1632 This function is particularly useful for applications with many top-level
1633 windows.
1634
1635 The windows are closed in random order, until one window does not accept
1636 the close event. The application quits when the last window was successfully
1637 closed, unless \l quitOnLastWindowClosed is set to false. To trigger application
1638 termination from e.g. a menu, use QCoreApplication::quit() instead of this
1639 function.
1640
1641 \sa quitOnLastWindowClosed, lastWindowClosed(), QWidget::close(),
1642 QWidget::closeEvent(), QCoreApplication::quit(),
1643 topLevelWidgets(), QWidget::isWindow()
1644*/
1645void QApplication::closeAllWindows()
1646{
1647 QWindowList processedWindows;
1648 QApplicationPrivate::tryCloseAllWidgetWindows(&processedWindows);
1649}
1650
1651/*!
1652 Displays a simple message box about Qt. The message includes the version
1653 number of Qt being used by the application.
1654
1655 This is useful for inclusion in the \uicontrol Help menu of an application, as
1656 shown in the \l{mainwindows/menus}{Menus} example.
1657
1658 This function is a convenience slot for QMessageBox::aboutQt().
1659*/
1660void QApplication::aboutQt()
1661{
1662#if QT_CONFIG(messagebox)
1663 QMessageBox::aboutQt(activeWindow());
1664#endif // QT_CONFIG(messagebox)
1665}
1666
1667/*!
1668 \since 4.1
1669 \fn void QApplication::focusChanged(QWidget *old, QWidget *now)
1670
1671 This signal is emitted when the widget that has keyboard focus changed from
1672 \a old to \a now, i.e., because the user pressed the tab-key, clicked into
1673 a widget or changed the active window. Both \a old and \a now can be \nullptr.
1674
1675
1676 The signal is emitted after both widget have been notified about the change
1677 through QFocusEvent.
1678
1679 \sa QWidget::setFocus(), QWidget::clearFocus(), Qt::FocusReason
1680*/
1681
1682bool QApplicationPrivate::handleQuitEvent()
1683{
1684 // FIXME: This logic first tries to close all windows, and then
1685 // checks whether it was successful, but the conditions used in
1686 // closeAllWindows() differ from the verification logic below.
1687 // We should build on the logic in tryCloseAllWidgetWindows().
1688 QApplication::closeAllWindows();
1689 for (auto *w : QApplication::topLevelWidgets()) {
1690 if (w->data->is_closing)
1691 continue;
1692 if (w->isVisible() && !(w->windowType() == Qt::Popup) &&
1693 (!(w->windowType() == Qt::Dialog) || !w->parentWidget()) && !w->testAttribute(Qt::WA_DontShowOnScreen))
1694 return false;
1695 }
1696 // Explicitly call QCoreApplicationPrivate instead of QGuiApplicationPrivate so that
1697 // we don't let QGuiApplication close any windows we skipped earlier in
1698 // closeAllWindows(). FIXME: Unify all this close magic through closeAllWindows.
1699 return QCoreApplicationPrivate::handleQuitEvent();
1700}
1701
1702/*!\reimp
1703
1704*/
1705bool QApplication::event(QEvent *e)
1706{
1707 Q_D(QApplication);
1708 switch (e->type()) {
1709#ifndef Q_OS_WIN
1710 case QEvent::LocaleChange: {
1711 // on Windows the event propagation is taken care by the
1712 // WM_SETTINGCHANGE event handler.
1713 const QWidgetList list = topLevelWidgets();
1714 for (auto *w : list) {
1715 if (!w->testAttribute(Qt::WA_SetLocale))
1716 w->d_func()->setLocale_helper(QLocale(), true);
1717 }
1718 break;
1719 }
1720#endif
1721 case QEvent::Timer: {
1722 QTimerEvent *te = static_cast<QTimerEvent*>(e);
1723 Q_ASSERT(te != nullptr);
1724 if (te->timerId() == d->toolTipWakeUp.timerId()) {
1725 d->toolTipWakeUp.stop();
1726 if (d->toolTipWidget) {
1727 QWidget *w = d->toolTipWidget->window();
1728 // show tooltip if WA_AlwaysShowToolTips is set, or if
1729 // any ancestor of d->toolTipWidget is the active
1730 // window
1731 bool showToolTip = w->testAttribute(Qt::WA_AlwaysShowToolTips);
1732 while (w && !showToolTip) {
1733 showToolTip = w->isActiveWindow();
1734 w = w->parentWidget();
1735 w = w ? w->window() : nullptr;
1736 }
1737 if (showToolTip) {
1738 QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
1739 QCoreApplication::sendEvent(d->toolTipWidget, &e);
1740 if (e.isAccepted() && d->toolTipWidget) {
1741 QStyle *s = d->toolTipWidget->style();
1742 int sleepDelay = s->styleHint(QStyle::SH_ToolTip_FallAsleepDelay, nullptr, d->toolTipWidget, nullptr);
1743 d->toolTipFallAsleep.start(sleepDelay, this);
1744 }
1745 }
1746 }
1747 } else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
1748 d->toolTipFallAsleep.stop();
1749 }
1750 break;
1751 }
1752#if QT_CONFIG(whatsthis)
1753 case QEvent::EnterWhatsThisMode:
1754 QWhatsThis::enterWhatsThisMode();
1755 return true;
1756#endif
1757 case QEvent::LanguageChange:
1758 case QEvent::ApplicationFontChange:
1759 case QEvent::ApplicationPaletteChange: {
1760 // QGuiApplication::event does not account for the cases where
1761 // there is a top level widget without a window handle. So they
1762 // need to have the event posted here
1763 const QWidgetList list = topLevelWidgets();
1764 for (auto *w : list) {
1765 if (!w->windowHandle())
1766 postEvent(w, new QEvent(e->type()));
1767 }
1768 break;
1769 }
1770 default:
1771 break;
1772 }
1773
1774 return QGuiApplication::event(e);
1775}
1776
1777// ### FIXME: topLevelWindows does not contain QWidgets without a parent
1778// until QWidgetPrivate::create is called. So we have to override the
1779// QGuiApplication::notifyLayoutDirectionChange
1780// to do the right thing.
1781void QApplicationPrivate::notifyLayoutDirectionChange()
1782{
1783 const QWidgetList list = QApplication::topLevelWidgets();
1784 QWindowList windowList = QGuiApplication::topLevelWindows();
1785
1786 // send to all top-level QWidgets
1787 for (auto *w : list) {
1788 windowList.removeAll(w->windowHandle());
1789 QEvent ev(QEvent::ApplicationLayoutDirectionChange);
1790 QCoreApplication::sendEvent(w, &ev);
1791 }
1792
1793 // in case there are any plain QWindows in this QApplication-using
1794 // application, also send the notification to them
1795 for (QWindow *w: std::as_const(windowList)) {
1796 QEvent ev(QEvent::ApplicationLayoutDirectionChange);
1797 QCoreApplication::sendEvent(w, &ev);
1798 }
1799}
1800
1801/*!
1802 \fn void QApplication::setActiveWindow(QWidget* active)
1803 \deprecated [6.5] Use QWidget::activateWindow() instead.
1804
1805 Sets the active window to the \a active widget in response to a system
1806 event. The function is called from the platform specific event handlers.
1807
1808 \warning This function does \e not set the keyboard focus to the active
1809 widget. Call QWidget::activateWindow() instead.
1810
1811 It sets the activeWindow() and focusWidget() attributes and sends proper
1812 \l{QEvent::WindowActivate}{WindowActivate}/\l{QEvent::WindowDeactivate}
1813 {WindowDeactivate} and \l{QEvent::FocusIn}{FocusIn}/\l{QEvent::FocusOut}
1814 {FocusOut} events to all appropriate widgets. The window will then be
1815 painted in active state (e.g. cursors in line edits will blink), and it
1816 will have tool tips enabled.
1817
1818 \sa activeWindow(), QWidget::activateWindow()
1819*/
1820#if QT_DEPRECATED_SINCE(6,5)
1821void QApplication::setActiveWindow(QWidget* act)
1822{
1823 QApplicationPrivate::setActiveWindow(act);
1824}
1825#endif
1826
1827void QApplicationPrivate::setActiveWindow(QWidget* act)
1828{
1829 QWidget* window = act?act->window():nullptr;
1830
1831 if (QApplicationPrivate::active_window == window)
1832 return;
1833
1834#if QT_CONFIG(graphicsview)
1835 if (window && window->graphicsProxyWidget()) {
1836 // Activate the proxy's view->viewport() ?
1837 return;
1838 }
1839#endif
1840
1841 QWidgetList toBeActivated;
1842 QWidgetList toBeDeactivated;
1843
1844 if (QApplicationPrivate::active_window) {
1845 if (QApplication::style()->styleHint(QStyle::SH_Widget_ShareActivation, nullptr, QApplicationPrivate::active_window)) {
1846 const QWidgetList list = QApplication::topLevelWidgets();
1847 for (auto *w : list) {
1848 if (w->isVisible() && w->isActiveWindow())
1849 toBeDeactivated.append(w);
1850 }
1851 } else {
1852 toBeDeactivated.append(QApplicationPrivate::active_window);
1853 }
1854 }
1855
1856 if (QApplicationPrivate::focus_widget) {
1857 if (QApplicationPrivate::focus_widget->testAttribute(Qt::WA_InputMethodEnabled))
1858 QGuiApplication::inputMethod()->commit();
1859
1860 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, Qt::ActiveWindowFocusReason);
1861 QCoreApplication::sendEvent(QApplicationPrivate::focus_widget, &focusAboutToChange);
1862 }
1863
1864 QApplicationPrivate::active_window = window;
1865
1866 if (QApplicationPrivate::active_window) {
1867 if (QApplication::style()->styleHint(QStyle::SH_Widget_ShareActivation, nullptr, QApplicationPrivate::active_window)) {
1868 const QWidgetList list = QApplication::topLevelWidgets();
1869 for (auto *w : list) {
1870 if (w->isVisible() && w->isActiveWindow())
1871 toBeActivated.append(w);
1872 }
1873 } else {
1874 toBeActivated.append(QApplicationPrivate::active_window);
1875 }
1876
1877 }
1878
1879 // first the activation/deactivation events
1880 QEvent activationChange(QEvent::ActivationChange);
1881 QEvent windowActivate(QEvent::WindowActivate);
1882 QEvent windowDeactivate(QEvent::WindowDeactivate);
1883
1884 for (QWidget *w : std::as_const(toBeActivated)) {
1885 QApplication::sendSpontaneousEvent(w, &windowActivate);
1886 QApplication::sendSpontaneousEvent(w, &activationChange);
1887 }
1888
1889 for (QWidget *w : std::as_const(toBeDeactivated)) {
1890 QApplication::sendSpontaneousEvent(w, &windowDeactivate);
1891 QApplication::sendSpontaneousEvent(w, &activationChange);
1892 }
1893
1894 if (!inPopupMode()) {
1895 // then focus events
1896 if (!QApplicationPrivate::active_window && QApplicationPrivate::focus_widget) {
1897 QApplicationPrivate::setFocusWidget(nullptr, Qt::ActiveWindowFocusReason);
1898 } else if (QApplicationPrivate::active_window) {
1899 QWidget *w = QApplicationPrivate::active_window->focusWidget();
1900 if (w && w->isVisible() /*&& w->focusPolicy() != QWidget::NoFocus*/)
1901 w->setFocus(Qt::ActiveWindowFocusReason);
1902 else {
1903 w = QApplicationPrivate::focusNextPrevChild_helper(QApplicationPrivate::active_window, true);
1904 if (w) {
1905 w->setFocus(Qt::ActiveWindowFocusReason);
1906 } else {
1907 w = QApplicationPrivate::focus_widget;
1908 if (!w && QApplicationPrivate::active_window->focusPolicy() != Qt::NoFocus) {
1909 QApplicationPrivate::active_window->setFocus(Qt::ActiveWindowFocusReason);
1910 } else if (!QApplicationPrivate::active_window->isAncestorOf(w)) {
1911 // If the focus widget is not in the activate_window, clear the focus
1912 QApplicationPrivate::setFocusWidget(nullptr, Qt::ActiveWindowFocusReason);
1913 }
1914 }
1915 }
1916 }
1917 }
1918}
1919
1921{
1922 // QTBUG-32177, wnd might be a QQuickView embedded via window container.
1923 while (wnd && !wnd->isTopLevel()) {
1924 QWindow *parent = wnd->parent();
1925 if (!parent)
1926 break;
1927
1928 // Don't end up in windows not belonging to this application
1929 if (parent->handle() && parent->handle()->isForeignWindow())
1930 break;
1931
1932 wnd = wnd->parent();
1933 }
1934 if (wnd) {
1935 const auto tlws = QApplication::topLevelWidgets();
1936 for (QWidget *tlw : tlws) {
1937 if (tlw->windowHandle() == wnd)
1938 return tlw;
1939 }
1940 }
1941 return nullptr;
1942}
1943
1944void QApplicationPrivate::notifyActiveWindowChange(QWindow *previous)
1945{
1946#ifndef Q_OS_MACOS
1947 // Some delayed focus event to ignore, unless we are on cocoa where
1948 // popups can be opened via right-click on inactive applications
1949 if (inPopupMode())
1950 return;
1951#endif
1952 QWindow *focusWindow = QGuiApplicationPrivate::focus_window;
1953 QWidget *focusWidget = qt_tlw_for_window(focusWindow);
1954 QApplicationPrivate::setActiveWindow(focusWidget);
1955 // QTBUG-37126, Active X controls may set the focus on native child widgets.
1956 if (focusWindow && focusWidget && focusWindow != focusWidget->windowHandle()) {
1957 if (QWidgetWindow *widgetWindow = qobject_cast<QWidgetWindow *>(focusWindow))
1958 if (QWidget *widget = widgetWindow->widget())
1959 if (widget->inherits("QAxHostWidget"))
1960 widget->setFocus(Qt::ActiveWindowFocusReason);
1961 }
1962
1963 // QApplication::setActiveWindow() will deliver window activation events for
1964 // QWidgetWindows. But for other subclasses of QWindow (like QQuickWindow), we
1965 // need to send them explicitly, like we do from the base class implementation.
1966 if (previous && !qobject_cast<QWidgetWindow *>(previous)) {
1967 QEvent de(QEvent::WindowDeactivate);
1968 QCoreApplication::sendEvent(previous, &de);
1969 }
1970
1971 if (focusWindow && !qobject_cast<QWidgetWindow *>(focusWindow)) {
1972 QEvent ae(QEvent::WindowActivate);
1973 QCoreApplication::sendEvent(focusWindow, &ae);
1974 }
1975
1976 // don't call base class to avoid double delivery of WindowActivate/Deactivate events
1977}
1978
1979/*!internal
1980 * Helper function that returns the new focus widget, but does not set the focus reason.
1981 * Returns \nullptr if a new focus widget could not be found.
1982 * Shared with QGraphicsProxyWidgetPrivate::findFocusChild()
1983*/
1984QWidget *QApplicationPrivate::focusNextPrevChild_helper(QWidget *toplevel, bool next,
1985 bool *wrappingOccurred)
1986{
1987 uint focus_flag = qt_tab_all_widgets() ? Qt::TabFocus : Qt::StrongFocus;
1988
1989 QWidget *f = toplevel->focusWidget();
1990 if (!f)
1991 f = toplevel;
1992
1993 QWidget *w = f;
1994 QWidget *test = f->nextInFocusChain();
1995 bool seenWindow = false;
1996 bool focusWidgetAfterWindow = false;
1997 while (test && test != f) {
1998 if (test->isWindow())
1999 seenWindow = true;
2000
2001 // If the next focus widget has a focus proxy, we need to check to ensure
2002 // that the proxy is in the correct parent-child direction (according to
2003 // \a next). This is to ensure that we can tab in and out of compound widgets
2004 // without getting stuck in a tab-loop between parent and child.
2005 QWidget *focusProxy = test->d_func()->deepestFocusProxy();
2006 auto effectiveFocusPolicy = [](QWidget *widget) {
2007 return widget->isEnabled() ? widget->focusPolicy() : Qt::NoFocus;
2008 };
2009 const bool canTakeFocus = (effectiveFocusPolicy(focusProxy ? focusProxy : test)
2010 & focus_flag) == focus_flag;
2011 const bool composites = focusProxy ? (next ? focusProxy->isAncestorOf(test)
2012 : test->isAncestorOf(focusProxy))
2013 : false;
2014 if (canTakeFocus && !composites
2015 && test->isVisibleTo(toplevel) && test->isEnabled()
2016 && !(w->windowType() == Qt::SubWindow && !w->isAncestorOf(test))
2017 && (toplevel->windowType() != Qt::SubWindow || toplevel->isAncestorOf(test))
2018 && f != focusProxy) {
2019 w = test;
2020 if (seenWindow)
2021 focusWidgetAfterWindow = true;
2022 if (next)
2023 break;
2024 }
2025 test = test->nextInFocusChain();
2026 }
2027
2028 if (wrappingOccurred != nullptr)
2029 *wrappingOccurred = next ? focusWidgetAfterWindow : !focusWidgetAfterWindow;
2030
2031 if (w == f) {
2032 if (qt_in_tab_key_event) {
2033 w->window()->setAttribute(Qt::WA_KeyboardFocusChange);
2034 w->update();
2035 }
2036 return nullptr;
2037 }
2038 return w;
2039}
2040
2041/*!
2042 \fn void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, const QPointF &globalPosF)
2043 \internal
2044
2045 Creates the proper Enter/Leave event when widget \a enter is entered and
2046 widget \a leave is left.
2047 */
2048void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave, const QPointF &globalPosF)
2049{
2050 if ((!enter && !leave) || (enter == leave))
2051 return;
2052
2053 QWidgetList leaveList;
2054 QWidgetList enterList;
2055
2056 bool sameWindow = leave && enter && leave->window() == enter->window();
2057 if (leave && !sameWindow) {
2058 auto *w = leave;
2059 do {
2060 leaveList.append(w);
2061 } while (!w->isWindow() && (w = w->parentWidget()));
2062 }
2063 if (enter && !sameWindow) {
2064 auto *w = enter;
2065 do {
2066 enterList.append(w);
2067 } while (!w->isWindow() && (w = w->parentWidget()));
2068 }
2069 if (sameWindow) {
2070 int enterDepth = 0;
2071 int leaveDepth = 0;
2072 auto *e = enter;
2073 while (!e->isWindow() && (e = e->parentWidget()))
2074 enterDepth++;
2075 auto *l = leave;
2076 while (!l->isWindow() && (l = l->parentWidget()))
2077 leaveDepth++;
2078 QWidget* wenter = enter;
2079 QWidget* wleave = leave;
2080 while (enterDepth > leaveDepth) {
2081 wenter = wenter->parentWidget();
2082 enterDepth--;
2083 }
2084 while (leaveDepth > enterDepth) {
2085 wleave = wleave->parentWidget();
2086 leaveDepth--;
2087 }
2088 while (!wenter->isWindow() && wenter != wleave) {
2089 wenter = wenter->parentWidget();
2090 wleave = wleave->parentWidget();
2091 }
2092
2093 for (auto *w = leave; w != wleave; w = w->parentWidget())
2094 leaveList.append(w);
2095
2096 for (auto *w = enter; w != wenter; w = w->parentWidget())
2097 enterList.append(w);
2098 }
2099
2100 QEvent leaveEvent(QEvent::Leave);
2101 for (QWidget *w : std::as_const(leaveList)) {
2102 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, nullptr)) {
2103 QCoreApplication::sendEvent(w, &leaveEvent);
2104 if (w->testAttribute(Qt::WA_Hover) &&
2105 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2106 Q_ASSERT(instance());
2107 QHoverEvent he(QEvent::HoverLeave, QPointF(-1, -1), globalPosF, w->mapFromGlobal(globalPosF),
2108 QGuiApplication::keyboardModifiers());
2109 qApp->d_func()->notify_helper(w, &he);
2110 }
2111 }
2112 }
2113 if (!enterList.isEmpty()) {
2114 // Guard against QGuiApplicationPrivate::lastCursorPosition initialized to qInf(), qInf().
2115 const QPointF globalPos = qIsInf(globalPosF.x())
2117 : globalPosF;
2118 const QPointF windowPos = std::as_const(enterList).back()->window()->mapFromGlobal(globalPos);
2119 for (auto it = enterList.crbegin(), end = enterList.crend(); it != end; ++it) {
2120 auto *w = *it;
2121 if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, nullptr)) {
2122 const QPointF localPos = w->mapFromGlobal(globalPos);
2123 QEnterEvent enterEvent(localPos, windowPos, globalPos);
2124 QCoreApplication::sendEvent(w, &enterEvent);
2125 if (w->testAttribute(Qt::WA_Hover) &&
2126 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2127 QHoverEvent he(QEvent::HoverEnter, windowPos, QPointF(-1, -1), globalPos,
2128 QGuiApplication::keyboardModifiers());
2129 QMutableEventPoint::setPosition(he.point(0), localPos);
2130 qApp->d_func()->notify_helper(w, &he);
2131 }
2132 }
2133 }
2134 }
2135
2136#ifndef QT_NO_CURSOR
2137 // Update cursor for alien/graphics widgets.
2138
2139 const bool enterOnAlien = (enter && (isAlien(enter) || enter->testAttribute(Qt::WA_DontShowOnScreen)));
2140 // Whenever we leave an alien widget on X11/QPA, we need to reset its nativeParentWidget()'s cursor.
2141 // This is not required on Windows as the cursor is reset on every single mouse move.
2142 QWidget *parentOfLeavingCursor = nullptr;
2143 for (QWidget *w : std::as_const(leaveList)) {
2144 if (!isAlien(w))
2145 break;
2146 if (w->testAttribute(Qt::WA_SetCursor)) {
2147 QWidget *parent = w->parentWidget();
2148 while (parent && parent->d_func()->data.in_destructor)
2149 parent = parent->parentWidget();
2150 parentOfLeavingCursor = parent;
2151 //continue looping, we need to find the downest alien widget with a cursor.
2152 // (downest on the screen)
2153 }
2154 }
2155 //check that we will not call qt_x11_enforce_cursor twice with the same native widget
2156 if (parentOfLeavingCursor && (!enterOnAlien
2157 || parentOfLeavingCursor->effectiveWinId() != enter->effectiveWinId())) {
2158#if QT_CONFIG(graphicsview)
2159 if (!parentOfLeavingCursor->window()->graphicsProxyWidget())
2160#endif
2161 {
2162 qt_qpa_set_cursor(parentOfLeavingCursor, true);
2163 }
2164 }
2165 if (enterOnAlien) {
2166 QWidget *cursorWidget = enter;
2167 while (!cursorWidget->isWindow() && !cursorWidget->isEnabled())
2168 cursorWidget = cursorWidget->parentWidget();
2169
2170 if (!cursorWidget)
2171 return;
2172
2173#if QT_CONFIG(graphicsview)
2174 if (cursorWidget->window()->graphicsProxyWidget()) {
2175 QWidgetPrivate::nearestGraphicsProxyWidget(cursorWidget)->setCursor(cursorWidget->cursor());
2176 } else
2177#endif
2178 {
2179 qt_qpa_set_cursor(cursorWidget, true);
2180 }
2181 }
2182#endif
2183}
2184
2185/* exported for the benefit of testing tools */
2186Q_WIDGETS_EXPORT bool qt_tryModalHelper(QWidget *widget, QWidget **rettop)
2187{
2188 return QApplicationPrivate::tryModalHelper(widget, rettop);
2189}
2190
2191/*! \internal
2192 Returns \c true if \a widget is blocked by a modal window.
2193 */
2194bool QApplicationPrivate::isBlockedByModal(QWidget *widget)
2195{
2196 widget = widget->window();
2197 QWindow *window = widget->windowHandle();
2198 return window && self->isWindowBlocked(window);
2199}
2200
2201Qt::WindowModality QApplicationPrivate::defaultModality() const
2202{
2203 return Qt::ApplicationModal;
2204}
2205
2206bool QApplicationPrivate::windowNeverBlocked(QWindow *window) const
2207{
2208 QWidget *popupWidget = QApplication::activePopupWidget();
2209 QWindow *popupWindow = popupWidget ? popupWidget->windowHandle() : nullptr;
2210 return popupWindow == window || (!popupWindow && QWindowPrivate::get(window)->isPopup());
2211}
2212
2213/*!\internal
2214
2215 Called from qapplication_\e{platform}.cpp, returns \c true
2216 if the widget should accept the event.
2217 */
2218bool QApplicationPrivate::tryModalHelper(QWidget *widget, QWidget **rettop)
2219{
2220 QWidget *top = QApplication::activeModalWidget();
2221 if (rettop)
2222 *rettop = top;
2223
2224 // the active popup widget always gets the input event
2225 if (QApplication::activePopupWidget())
2226 return true;
2227
2228 return !isBlockedByModal(widget->window());
2229}
2230
2231bool qt_try_modal(QWidget *widget, QEvent::Type type)
2232{
2233 QWidget * top = nullptr;
2234
2235 if (QApplicationPrivate::tryModalHelper(widget, &top))
2236 return true;
2237
2238 bool block_event = false;
2239
2240 switch (type) {
2241 case QEvent::MouseButtonPress: // disallow mouse/key events
2242 case QEvent::MouseButtonRelease:
2243 case QEvent::MouseMove:
2244 case QEvent::KeyPress:
2245 case QEvent::KeyRelease:
2246 block_event = true;
2247 break;
2248 default:
2249 break;
2250 }
2251
2252 if (block_event && top && top->parentWidget() == nullptr)
2253 top->raise();
2254
2255 return !block_event;
2256}
2257
2258bool QApplicationPrivate::modalState()
2259{
2260 return !self->modalWindowList.isEmpty();
2261}
2262
2263/*
2264 \internal
2265*/
2266QWidget *QApplicationPrivate::pickMouseReceiver(QWidget *candidate, const QPointF &windowPos,
2267 QPointF *pos, QEvent::Type type,
2268 Qt::MouseButtons buttons, QWidget *buttonDown,
2269 QWidget *alienWidget)
2270{
2271 Q_ASSERT(candidate);
2272
2273 QWidget *mouseGrabber = QWidget::mouseGrabber();
2274 if (((type == QEvent::MouseMove && buttons) || (type == QEvent::MouseButtonRelease))
2275 && !buttonDown && !mouseGrabber) {
2276 return nullptr;
2277 }
2278
2279 if (alienWidget && alienWidget->internalWinId())
2280 alienWidget = nullptr;
2281
2282 QWidget *receiver = candidate;
2283
2284 if (!mouseGrabber)
2285 mouseGrabber = (buttonDown && !isBlockedByModal(buttonDown)) ? buttonDown : alienWidget;
2286
2287 if (mouseGrabber && mouseGrabber != candidate) {
2288 receiver = mouseGrabber;
2289 *pos = receiver->mapFromGlobal(candidate->mapToGlobal(windowPos));
2290 }
2291
2292 return receiver;
2293
2294}
2295
2296/*
2297 \internal
2298*/
2299bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event,
2300 QWidget *alienWidget, QWidget *nativeWidget,
2301 QWidget **buttonDown, QPointer<QWidget> &lastMouseReceiver,
2302 bool spontaneous, bool onlyDispatchEnterLeave)
2303{
2304 Q_ASSERT(receiver);
2305 Q_ASSERT(event);
2306 Q_ASSERT(nativeWidget);
2307 Q_ASSERT(buttonDown);
2308
2309 if (alienWidget && !isAlien(alienWidget))
2310 alienWidget = nullptr;
2311
2312 QPointer<QWidget> receiverGuard = receiver;
2313 QPointer<QWidget> nativeGuard = nativeWidget;
2314 QPointer<QWidget> alienGuard = alienWidget;
2315 QPointer<QWidget> activePopupWidget = QApplication::activePopupWidget();
2316
2317 const bool graphicsWidget = nativeWidget->testAttribute(Qt::WA_DontShowOnScreen);
2318
2319 bool widgetUnderMouse = QRectF(receiver->rect()).contains(event->position());
2320
2321 // Clear the obsolete leaveAfterRelease value, if mouse button has been released but
2322 // leaveAfterRelease has not been updated.
2323 // This happens e.g. when modal dialog or popup is shown as a response to button click.
2324 if (leaveAfterRelease && !*buttonDown && !event->buttons())
2325 leaveAfterRelease = nullptr;
2326
2327 if (*buttonDown) {
2328 if (!graphicsWidget) {
2329 // Register the widget that shall receive a leave event
2330 // after the last button is released.
2331 if ((alienWidget || !receiver->internalWinId()) && !leaveAfterRelease && !QWidget::mouseGrabber())
2332 leaveAfterRelease = *buttonDown;
2333 if (event->type() == QEvent::MouseButtonRelease && !event->buttons())
2334 *buttonDown = nullptr;
2335 }
2336 } else if (lastMouseReceiver && widgetUnderMouse) {
2337 // Dispatch enter/leave if we move:
2338 // 1) from an alien widget to another alien widget or
2339 // from a native widget to an alien widget (first OR case)
2340 // 2) from an alien widget to a native widget (second OR case)
2341 if ((alienWidget && alienWidget != lastMouseReceiver)
2342 || (isAlien(lastMouseReceiver) && !alienWidget)) {
2343 if (activePopupWidget) {
2344 if (!QWidget::mouseGrabber())
2345 dispatchEnterLeave(alienWidget ? alienWidget : nativeWidget, lastMouseReceiver, event->globalPosition());
2346 } else {
2347 dispatchEnterLeave(receiver, lastMouseReceiver, event->globalPosition());
2348 }
2349
2350 }
2351 }
2352
2353 // We need this quard in case someone opens a modal dialog / popup. If that's the case
2354 // leaveAfterRelease is set to null, but we shall not update lastMouseReceiver.
2355 const bool wasLeaveAfterRelease = leaveAfterRelease != nullptr;
2356 bool result = true;
2357 // This code is used for sending the synthetic enter/leave events for cases where it is needed
2358 // due to other events causing the widget under the mouse to change. However in those cases
2359 // we do not want to send the mouse event associated with this call, so this enables us to
2360 // not send the unneeded mouse event
2361 if (!onlyDispatchEnterLeave) {
2362 if (spontaneous)
2363 result = QApplication::sendSpontaneousEvent(receiver, event);
2364 else
2365 result = QCoreApplication::sendEvent(receiver, event);
2366 }
2367
2368 if (!graphicsWidget && leaveAfterRelease && event->type() == QEvent::MouseButtonRelease
2369 && !event->buttons() && QWidget::mouseGrabber() != leaveAfterRelease) {
2370 // Dispatch enter/leave if:
2371 // 1) the mouse grabber is an alien widget
2372 // 2) the button is released on an alien widget
2373 QWidget *enter = nullptr;
2374 if (nativeGuard)
2375 enter = alienGuard ? alienWidget : nativeWidget;
2376 else // The receiver is typically deleted on mouse release with drag'n'drop.
2377 enter = QApplication::widgetAt(event->globalPosition().toPoint());
2378 dispatchEnterLeave(enter, leaveAfterRelease, event->globalPosition());
2379 leaveAfterRelease = nullptr;
2380 lastMouseReceiver = enter;
2381 } else if (!wasLeaveAfterRelease) {
2382 if (activePopupWidget) {
2383 if (!QWidget::mouseGrabber())
2384 lastMouseReceiver = alienGuard ? alienWidget : (nativeGuard ? nativeWidget : nullptr);
2385 } else {
2386 lastMouseReceiver = receiverGuard ? receiver : QApplication::widgetAt(event->globalPosition().toPoint());
2387 }
2388 }
2389
2390 return result;
2391}
2392
2393/*
2394 This function should only be called when the widget changes visibility, i.e.
2395 when the \a widget is shown, hidden or deleted. This function does nothing
2396 if the widget is a top-level or native, i.e. not an alien widget. In that
2397 case enter/leave events are generated by the underlying windowing system.
2398*/
2400extern Q_WIDGETS_EXPORT QWidget *qt_button_down;
2401void QApplicationPrivate::sendSyntheticEnterLeave(QWidget *widget)
2402{
2403#ifndef QT_NO_CURSOR
2404 if (!widget || widget->isWindow())
2405 return;
2406 const bool widgetInShow = widget->isVisible() && !widget->data->in_destructor;
2407 if (!widgetInShow && widget != qt_last_mouse_receiver)
2408 return; // Widget was not under the cursor when it was hidden/deleted.
2409
2410 if (widgetInShow && widget->parentWidget()->data->in_show)
2411 return; // Ignore recursive show.
2412
2413 QWidget *mouseGrabber = QWidget::mouseGrabber();
2414 if (mouseGrabber && mouseGrabber != widget)
2415 return; // Someone else has the grab; enter/leave should not occur.
2416
2417 QWidget *tlw = widget->window();
2418 if (tlw->data->in_destructor || tlw->data->is_closing)
2419 return; // Closing down the business.
2420
2421 if (widgetInShow && (!qt_last_mouse_receiver || qt_last_mouse_receiver->window() != tlw))
2422 return; // Mouse cursor not inside the widget's top-level.
2423
2424 const QPoint globalPos(QCursor::pos());
2425 QPoint windowPos = tlw->mapFromGlobal(globalPos);
2426
2427 // Find the current widget under the mouse. If this function was called from
2428 // the widget's destructor, we have to make sure childAt() doesn't take into
2429 // account widgets that are about to be destructed.
2430 QWidget *widgetUnderCursor = tlw->d_func()->childAt_helper(windowPos, widget->data->in_destructor);
2431 if (!widgetUnderCursor)
2432 widgetUnderCursor = tlw;
2433 QPoint pos = widgetUnderCursor->mapFrom(tlw, windowPos);
2434
2435 if (widgetInShow && widgetUnderCursor != widget && !widget->isAncestorOf(widgetUnderCursor))
2436 return; // Mouse cursor not inside the widget or any of its children.
2437
2438 if (widget->data->in_destructor && qt_button_down == widget)
2439 qt_button_down = nullptr;
2440
2441 // A mouse move is not actually sent, but we utilize the sendMouseEvent() call to send the
2442 // enter/leave events as appropriate
2443 QMouseEvent e(QEvent::MouseMove, pos, windowPos, globalPos, Qt::NoButton, Qt::NoButton, Qt::NoModifier);
2444 sendMouseEvent(widgetUnderCursor, &e, widgetUnderCursor, tlw, &qt_button_down, qt_last_mouse_receiver, true, true);
2445#else // !QT_NO_CURSOR
2446 Q_UNUSED(widget);
2447#endif // QT_NO_CURSOR
2448}
2449
2450/*
2451 Sets the time after which a drag should start to \a ms ms.
2452
2453 \sa startDragTime()
2454*/
2455
2456void QApplication::setStartDragTime(int ms)
2457{
2458 QGuiApplication::styleHints()->setStartDragTime(ms);
2459}
2460
2461/*!
2462 \property QApplication::startDragTime
2463 \brief the time in milliseconds that a mouse button must be held down
2464 before a drag and drop operation will begin
2465
2466 If you support drag and drop in your application, and want to start a drag
2467 and drop operation after the user has held down a mouse button for a
2468 certain amount of time, you should use this property's value as the delay.
2469
2470 Qt also uses this delay internally, e.g. in QTextEdit and QLineEdit, for
2471 starting a drag.
2472
2473 The default value is 500 ms.
2474
2475 \sa startDragDistance(), {Drag and Drop in Qt}{Drag and Drop}
2476*/
2477
2478int QApplication::startDragTime()
2479{
2480 return QGuiApplication::styleHints()->startDragTime();
2481}
2482
2483/*
2484 Sets the distance after which a drag should start to \a l pixels.
2485
2486 \sa startDragDistance()
2487*/
2488
2489void QApplication::setStartDragDistance(int l)
2490{
2491 QGuiApplication::styleHints()->setStartDragDistance(l);
2492}
2493
2494/*!
2495 \property QApplication::startDragDistance
2496 \brief the minimum distance required for a drag and drop operation to start.
2497
2498 If you support drag and drop in your application, and want to start a drag
2499 and drop operation after the user has moved the cursor a certain distance
2500 with a button held down, you should use this property's value as the
2501 minimum distance required.
2502
2503 For example, if the mouse position of the click is stored in \c startPos
2504 and the current position (e.g. in the mouse move event) is \c currentPos,
2505 you can find out if a drag should be started with code like this:
2506
2507 \snippet code/src_gui_kernel_qapplication.cpp 7
2508
2509 Qt uses this value internally, e.g. in QFileDialog.
2510
2511 The default value (if the platform doesn't provide a different default)
2512 is 10 pixels.
2513
2514 \sa startDragTime(), QPoint::manhattanLength(), {Drag and Drop in Qt}{Drag and Drop}
2515*/
2516
2517int QApplication::startDragDistance()
2518{
2519 return QGuiApplication::styleHints()->startDragDistance();
2520}
2521
2522/*!
2523 Enters the main event loop and waits until exit() is called, then returns
2524 the value that was set to exit() (which is 0 if exit() is called via
2525 quit()).
2526
2527 It is necessary to call this function to start event handling. The main
2528 event loop receives events from the window system and dispatches these to
2529 the application widgets.
2530
2531 Generally, no user interaction can take place before calling exec(). As a
2532 special case, modal widgets like QMessageBox can be used before calling
2533 exec(), because modal widgets call exec() to start a local event loop.
2534
2535 To make your application perform idle processing, i.e., executing a special
2536 function whenever there are no pending events, use a QChronoTimer with 0ns
2537 timeout. More advanced idle processing schemes can be achieved using
2538 processEvents().
2539
2540 We recommend that you connect clean-up code to the
2541 \l{QCoreApplication::}{aboutToQuit()} signal, instead of putting it in your
2542 application's \c{main()} function. This is because, on some platforms the
2543 QApplication::exec() call may not return. For example, on the Windows
2544 platform, when the user logs off, the system terminates the process after Qt
2545 closes all top-level windows. Hence, there is \e{no guarantee} that the
2546 application will have time to exit its event loop and execute code at the
2547 end of the \c{main()} function, after the QApplication::exec() call.
2548
2549 \sa quitOnLastWindowClosed, QCoreApplication::quit(), QCoreApplication::exit(),
2550 QCoreApplication::processEvents(), QCoreApplication::exec()
2551*/
2552int QApplication::exec()
2553{
2554 return QGuiApplication::exec();
2555}
2556
2557/*! \reimp
2558 */
2559bool QApplication::notify(QObject *receiver, QEvent *e)
2560{
2561 Q_D(QApplication);
2562 // no events are delivered after ~QCoreApplication() has started
2563 if (QApplicationPrivate::is_app_closing)
2564 return true;
2565
2566 if (Q_UNLIKELY(!receiver)) { // serious error
2567 qWarning("QApplication::notify: Unexpected null receiver");
2568 return true;
2569 }
2570
2571 QCoreApplicationPrivate::checkReceiverThread(receiver, "QApplication::notify");
2572
2573 const bool isWindowType = receiver->isWindowType();
2574 const bool isWidgetType = receiver->isWidgetType();
2575 if (isWindowType
2576 && QGuiApplicationPrivate::sendQWindowEventToQPlatformWindow(static_cast<QWindow *>(receiver), e)) {
2577 return true; // Platform plugin ate the event
2578 }
2579
2580 QGuiApplicationPrivate::captureGlobalModifierState(e);
2581
2582#ifndef QT_NO_GESTURES
2583 // walk through parents and check for gestures
2584 if (d->gestureManager) {
2585 switch (e->type()) {
2586 case QEvent::Paint:
2587 case QEvent::MetaCall:
2588 case QEvent::DeferredDelete:
2589 case QEvent::DragEnter: case QEvent::DragMove: case QEvent::DragLeave:
2590 case QEvent::Drop: case QEvent::DragResponse:
2591 case QEvent::ChildAdded: case QEvent::ChildPolished:
2592 case QEvent::ChildRemoved:
2593 case QEvent::UpdateRequest:
2594 case QEvent::UpdateLater:
2595 case QEvent::LocaleChange:
2596 case QEvent::Style:
2597 case QEvent::IconDrag:
2598 case QEvent::StyleChange:
2599 case QEvent::GraphicsSceneDragEnter:
2600 case QEvent::GraphicsSceneDragMove:
2601 case QEvent::GraphicsSceneDragLeave:
2602 case QEvent::GraphicsSceneDrop:
2603 case QEvent::DynamicPropertyChange:
2604 case QEvent::NetworkReplyUpdated:
2605 break;
2606 default:
2607 if (d->gestureManager->thread() == QThread::currentThread()) {
2608 if (isWidgetType) {
2609 if (d->gestureManager->filterEvent(static_cast<QWidget *>(receiver), e))
2610 return true;
2611 } else {
2612 // a special case for events that go to QGesture objects.
2613 // We pass the object to the gesture manager and it'll figure
2614 // out if it's QGesture or not.
2615 if (d->gestureManager->filterEvent(receiver, e))
2616 return true;
2617 }
2618 }
2619 break;
2620 }
2621 }
2622#endif // QT_NO_GESTURES
2623
2624 switch (e->type()) {
2625 case QEvent::ApplicationDeactivate:
2626 case QEvent::OrientationChange:
2627 // Close all popups (triggers when switching applications
2628 // by pressing ALT-TAB on Windows, which is not receive as key event.
2629 // triggers when the screen rotates.)
2630 d->closeAllPopups();
2631 break;
2632 case QEvent::Wheel: // User input and window activation makes tooltips sleep
2633 case QEvent::ActivationChange:
2634 case QEvent::KeyPress:
2635 case QEvent::KeyRelease:
2636 case QEvent::FocusOut:
2637 case QEvent::FocusIn:
2638 case QEvent::MouseButtonPress:
2639 case QEvent::MouseButtonRelease:
2640 case QEvent::MouseButtonDblClick:
2641 d->toolTipFallAsleep.stop();
2642 Q_FALLTHROUGH();
2643 case QEvent::Leave:
2644 d->toolTipWakeUp.stop();
2645 break;
2646 default:
2647 break;
2648 }
2649
2650 switch (e->type()) {
2651 case QEvent::KeyPress: {
2652 QKeyEvent* keyEvent = static_cast<QKeyEvent*>(e);
2653 const int key = keyEvent->key();
2654 // When a key press is received which is not spontaneous then it needs to
2655 // be manually sent as a shortcut override event to ensure that any
2656 // matching shortcut is triggered first. This enables emulation/playback
2657 // of recorded events to still have the same effect.
2658 if (!e->spontaneous() && isWidgetType
2659 && qt_sendShortcutOverrideEvent(static_cast<QWidget *>(receiver), keyEvent->timestamp(),
2660 key, keyEvent->modifiers(), keyEvent->text(),
2661 keyEvent->isAutoRepeat(), keyEvent->count())) {
2662 return true;
2663 }
2664 qt_in_tab_key_event = (key == Qt::Key_Backtab
2665 || key == Qt::Key_Tab
2666 || key == Qt::Key_Left
2667 || key == Qt::Key_Up
2668 || key == Qt::Key_Right
2669 || key == Qt::Key_Down);
2670 break;
2671 }
2672 default:
2673 break;
2674 }
2675
2676 bool res = false;
2677 if (isWidgetType) {
2678 QWidget * w = static_cast<QWidget *>(receiver);
2679 switch (e->type()) {
2680 case QEvent::ShortcutOverride:
2681 case QEvent::KeyPress:
2682 case QEvent::KeyRelease: {
2683 QKeyEvent* key = static_cast<QKeyEvent*>(e);
2684 bool def = key->isAccepted();
2685 /*
2686 QLineEdit will emit a signal on Key_Return, but
2687 ignore the event, and sometimes the connected
2688 slot deletes the QLineEdit (common in itemview
2689 delegates), so we have to check if the widget
2690 was destroyed even if the event was ignored (to
2691 prevent a crash)
2692
2693 Note that we don't have to reset pr while
2694 propagating (because the original receiver will
2695 be destroyed if one of its ancestors is)
2696 */
2697 QPointer<QObject> pr = receiver;
2698 while (w) {
2699 if (def)
2700 key->accept();
2701 else
2702 key->ignore();
2703 res = d->notify_helper(w, e);
2704
2705 if (res && key->isAccepted())
2706 break;
2707 if (!pr || w->isWindow())
2708 break;
2709
2710 w = w->parentWidget();
2711 }
2712 qt_in_tab_key_event = false;
2713 break;
2714 }
2715 case QEvent::MouseButtonPress:
2716 case QEvent::MouseButtonRelease:
2717 case QEvent::MouseButtonDblClick:
2718 case QEvent::MouseMove: {
2719 QMouseEvent* mouse = static_cast<QMouseEvent*>(e);
2720 QPoint relpos = mouse->position().toPoint();
2721
2722 if (e->spontaneous()) {
2723 if (e->type() != QEvent::MouseMove)
2724 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos);
2725
2726 // ### Qt 7 These dynamic tool tips should be an OPT-IN feature. Some platforms
2727 // like macOS (probably others too), can optimize their views by not
2728 // dispatching mouse move events. We have attributes to control hover,
2729 // and mouse tracking, but as long as we are deciding to implement this
2730 // feature without choice of opting-in or out, you ALWAYS have to have
2731 // tracking enabled. Therefore, the other properties give a false sense of
2732 // performance enhancement.
2733 if (e->type() == QEvent::MouseMove && mouse->buttons() == 0
2734 && w->rect().contains(relpos)) { // Outside due to mouse grab?
2735 d->toolTipWidget = w;
2736 d->toolTipPos = relpos;
2737 d->toolTipGlobalPos = mouse->globalPosition().toPoint();
2738 QStyle *s = d->toolTipWidget->style();
2739 int wakeDelay = s->styleHint(QStyle::SH_ToolTip_WakeUpDelay, nullptr, d->toolTipWidget, nullptr);
2740 d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive() ? 20 : wakeDelay, this);
2741 }
2742 }
2743
2744 bool eventAccepted = mouse->isAccepted();
2745
2746 QPointer<QWidget> pw = w;
2747 while (w) {
2748 QMouseEvent me(mouse->type(), relpos, mouse->scenePosition(), mouse->globalPosition(),
2749 mouse->button(), mouse->buttons(), mouse->modifiers(), mouse->source(),
2750 mouse->pointingDevice());
2751 me.m_spont = mouse->spontaneous();
2752 me.setTimestamp(mouse->timestamp());
2753 QMutableSinglePointEvent::setDoubleClick(&me, QMutableSinglePointEvent::isDoubleClick(mouse));
2754 // throw away any mouse-tracking-only mouse events
2755 if (!w->hasMouseTracking()
2756 && mouse->type() == QEvent::MouseMove && mouse->buttons() == 0) {
2757 // but still send them through all application event filters (normally done by notify_helper)
2758 d->sendThroughApplicationEventFilters(w, w == receiver ? mouse : &me);
2759 res = true;
2760 } else {
2761 w->setAttribute(Qt::WA_NoMouseReplay, false);
2762 res = d->notify_helper(w, w == receiver ? mouse : &me);
2763 e->m_spont = false;
2764 }
2765 eventAccepted = (w == receiver ? mouse : &me)->isAccepted();
2766 if (res && eventAccepted)
2767 break;
2768 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
2769 break;
2770 relpos += w->pos();
2771 w = w->parentWidget();
2772 }
2773
2774 mouse->setAccepted(eventAccepted);
2775
2776 if (e->type() == QEvent::MouseMove) {
2777 if (!pw)
2778 break;
2779
2780 w = static_cast<QWidget *>(receiver);
2781 relpos = mouse->position().toPoint();
2782 QPoint diff = relpos - w->mapFromGlobal(mouse->globalPosition()).toPoint();
2783 while (w) {
2784 if (w->testAttribute(Qt::WA_Hover) &&
2785 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) {
2786 QHoverEvent he(QEvent::HoverMove, mouse->scenePosition(), mouse->globalPosition(), relpos - diff, mouse->modifiers());
2787 QMutableEventPoint::setPosition(he.point(0), relpos);
2788 d->notify_helper(w, &he);
2789 }
2790 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
2791 break;
2792 relpos += w->pos();
2793 w = w->parentWidget();
2794 }
2795 }
2796 break;
2797 }
2798#if QT_CONFIG(wheelevent)
2799 case QEvent::Wheel: {
2800 // QTBUG-40656, QTBUG-42731: ignore wheel events when a popup (QComboBox) is open.
2801 if (const QWidget *popup = QApplication::activePopupWidget()) {
2802 if (w->window() != popup)
2803 return true;
2804 }
2805
2806 QWheelEvent* wheel = static_cast<QWheelEvent*>(e);
2807 if (!wheel->spontaneous()) {
2808 /*
2809 Synthesized events shouldn't propagate, e.g. QScrollArea passes events from the
2810 viewport on to the scrollbars, which might ignore the event if there is no more
2811 space to scroll. If we would propagate, the event would come back to the viewport.
2812 */
2813 res = d->notify_helper(w, wheel);
2814 break;
2815 }
2816
2817 const Qt::ScrollPhase phase = wheel->phase();
2818 QPointF relpos = wheel->position();
2819
2820 // Ideally, we should lock on a widget when it starts receiving wheel
2821 // events. This avoids other widgets to start receiving those events
2822 // as the mouse cursor hovers them. However, given the way common
2823 // wheeled mice work, there's no certain way of connecting different
2824 // wheel events as a stream. This results in the NoScrollPhase case,
2825 // where we just send the event from the original receiver and up its
2826 // hierarchy until the event gets accepted.
2827 //
2828 // In the case of more evolved input devices, like Apple's trackpad or
2829 // Magic Mouse, we receive the scroll phase information. This helps us
2830 // connect wheel events as a stream and therefore makes it easier to
2831 // lock on the widget onto which the scrolling was initiated.
2832 //
2833 // We assume that, when supported, the phase cycle follows the pattern:
2834 //
2835 // ScrollBegin (ScrollUpdate* ScrollMomentum* ScrollEnd)+
2836 //
2837 // This means that we can have scrolling sequences (starting with ScrollBegin)
2838 // or partial sequences (after a ScrollEnd and starting with ScrollUpdate).
2839
2840 // a widget has already grabbed the wheel for a sequence
2841 if (QApplicationPrivate::wheel_widget) {
2842 Q_ASSERT(phase != Qt::NoScrollPhase);
2843 w = QApplicationPrivate::wheel_widget;
2844 relpos = w->mapFromGlobal(wheel->globalPosition());
2845 }
2846 /*
2847 Start or finish a scrolling sequence by grabbing/releasing the wheel via
2848 wheel_widget. The sequence might be partial (ie. not start with ScrollBegin),
2849 e.g. if the previous wheel_widget was destroyed mid-sequence.
2850 */
2851 switch (phase) {
2852 case Qt::ScrollEnd:
2853 QApplicationPrivate::wheel_widget = nullptr;
2854 break;
2855 case Qt::ScrollBegin:
2856 QApplicationPrivate::wheel_widget = w;
2857 Q_FALLTHROUGH();
2858 case Qt::ScrollUpdate:
2859 case Qt::ScrollMomentum:
2860 if (!QApplicationPrivate::wheel_widget)
2861 QApplicationPrivate::wheel_widget = w;
2862 Q_FALLTHROUGH();
2863 case Qt::NoScrollPhase:
2864 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos.toPoint());
2865 break;
2866 // no default: - we want warnings if we don't handle all phases explicitly
2867 }
2868
2869 QWheelEvent we(relpos, wheel->globalPosition(), wheel->pixelDelta(), wheel->angleDelta(), wheel->buttons(),
2870 wheel->modifiers(), phase, wheel->inverted(), wheel->source(), wheel->pointingDevice());
2871
2872 we.setTimestamp(wheel->timestamp());
2873 bool eventAccepted;
2874 do {
2875 // events are delivered as accepted and ignored by the default event handler
2876 // since we always send the same QWheelEvent object, we need to reset the accepted state
2877 we.setAccepted(true);
2878 we.m_spont = wheel->spontaneous() && w == receiver;
2879 res = d->notify_helper(w, &we);
2880 eventAccepted = we.isAccepted();
2881 if (res && eventAccepted)
2882 break;
2883 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
2884 break;
2885
2886 QMutableEventPoint::setPosition(we.point(0), we.position() + w->pos());
2887 w = w->parentWidget();
2888 } while (w);
2889 wheel->setAccepted(eventAccepted);
2890 break;
2891 }
2892#endif
2893#ifndef QT_NO_CONTEXTMENU
2894 case QEvent::ContextMenu: {
2895 QContextMenuEvent *context = static_cast<QContextMenuEvent*>(e);
2896 QPoint relpos = context->pos();
2897 bool eventAccepted = context->isAccepted();
2898 while (w) {
2899 QContextMenuEvent ce(relpos, context->globalPos(), context->modifiers(),
2900 context->device());
2901 ce.m_spont = e->spontaneous();
2902 res = d->notify_helper(w, w == receiver ? context : &ce);
2903 eventAccepted = ((w == receiver) ? context : &ce)->isAccepted();
2904 e->m_spont = false;
2905
2906 if (res && eventAccepted)
2907 break;
2908 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
2909 break;
2910
2911 relpos += w->pos();
2912 w = w->parentWidget();
2913 }
2914 context->setAccepted(eventAccepted);
2915 break;
2916 }
2917#endif // QT_NO_CONTEXTMENU
2918#if QT_CONFIG(tabletevent)
2919 case QEvent::TabletMove:
2920 case QEvent::TabletPress:
2921 case QEvent::TabletRelease: {
2922 QTabletEvent *tablet = static_cast<QTabletEvent*>(e);
2923 QPointF relpos = tablet->position();
2924 bool eventAccepted = tablet->isAccepted();
2925 while (w) {
2926 QTabletEvent te(tablet->type(), tablet->pointingDevice(), relpos, tablet->globalPosition(),
2927 tablet->pressure(), tablet->xTilt(), tablet->yTilt(),
2928 tablet->tangentialPressure(), tablet->rotation(), tablet->z(),
2929 tablet->modifiers(), tablet->button(), tablet->buttons());
2930 te.m_spont = e->spontaneous();
2931 te.setTimestamp(tablet->timestamp());
2932 te.setAccepted(false);
2933 res = d->notify_helper(w, w == receiver ? tablet : &te);
2934 eventAccepted = ((w == receiver) ? tablet : &te)->isAccepted();
2935 e->m_spont = false;
2936 if (res && eventAccepted)
2937 break;
2938 if (w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
2939 break;
2940
2941 relpos += w->pos();
2942 w = w->parentWidget();
2943 }
2944 tablet->setAccepted(eventAccepted);
2945 break;
2946 }
2947#endif // QT_CONFIG(tabletevent)
2948
2949#if QT_CONFIG(tooltip) || QT_CONFIG(whatsthis)
2950 case QEvent::ToolTip:
2951 case QEvent::WhatsThis:
2952 case QEvent::QueryWhatsThis: {
2953 QHelpEvent *help = static_cast<QHelpEvent*>(e);
2954 QPoint relpos = help->pos();
2955 bool eventAccepted = help->isAccepted();
2956 while (w) {
2957 QHelpEvent he(help->type(), relpos, help->globalPos());
2958 he.m_spont = e->spontaneous();
2959 res = d->notify_helper(w, w == receiver ? help : &he);
2960 e->m_spont = false;
2961 eventAccepted = (w == receiver ? help : &he)->isAccepted();
2962 if (res && eventAccepted)
2963 break;
2964 if (w->isWindow())
2965 break;
2966
2967 relpos += w->pos();
2968 w = w->parentWidget();
2969 }
2970 help->setAccepted(eventAccepted);
2971 break;
2972 }
2973#endif
2974#if QT_CONFIG(statustip) || QT_CONFIG(whatsthis)
2975 case QEvent::StatusTip:
2976 case QEvent::WhatsThisClicked:
2977 while (w) {
2978 res = d->notify_helper(w, e);
2979 if (res && e->isAccepted())
2980 break;
2981 if (w->isWindow())
2982 break;
2983 w = w->parentWidget();
2984 }
2985 break;
2986#endif
2987
2988#if QT_CONFIG(draganddrop)
2989 case QEvent::DragEnter: {
2990 QDragEnterEvent *dragEvent = static_cast<QDragEnterEvent *>(e);
2991#if QT_CONFIG(graphicsview)
2992 // QGraphicsProxyWidget handles its own propagation,
2993 // and we must not change QDragManagers currentTarget.
2994 const auto &extra = w->window()->d_func()->extra;
2995 if (extra && extra->proxyWidget) {
2996 res = d->notify_helper(w, dragEvent);
2997 break;
2998 }
2999#endif
3000 while (w) {
3001 if (w->isEnabled() && w->acceptDrops()) {
3002 res = d->notify_helper(w, dragEvent);
3003 if (res && dragEvent->isAccepted()) {
3004 QDragManager::self()->setCurrentTarget(w);
3005 break;
3006 }
3007 }
3008 if (w->isWindow())
3009 break;
3010 dragEvent->m_pos = w->mapToParent(dragEvent->m_pos);
3011 w = w->parentWidget();
3012 }
3013 break;
3014 }
3015 case QEvent::DragMove:
3016 case QEvent::Drop:
3017 case QEvent::DragLeave: {
3018#if QT_CONFIG(graphicsview)
3019 // QGraphicsProxyWidget handles its own propagation,
3020 // and we must not change QDragManagers currentTarget.
3021 const auto &extra = w->window()->d_func()->extra;
3022 bool isProxyWidget = extra && extra->proxyWidget;
3023 if (!isProxyWidget)
3024#endif
3025 w = qobject_cast<QWidget *>(QDragManager::self()->currentTarget());
3026
3027 if (!w) {
3028 // The widget that received DragEnter didn't accept the event, so we have no
3029 // current drag target in the QDragManager. But DragLeave still needs to be
3030 // dispatched so that enter/leave events are in balance (and so that UnderMouse
3031 // gets cleared).
3032 if (e->type() == QEvent::DragLeave)
3033 w = static_cast<QWidget *>(receiver);
3034 else
3035 break;
3036 }
3037 if (e->type() == QEvent::DragMove || e->type() == QEvent::Drop) {
3038 QDropEvent *dragEvent = static_cast<QDropEvent *>(e);
3039 QWidget *origReceiver = static_cast<QWidget *>(receiver);
3040 while (origReceiver && w != origReceiver) {
3041 dragEvent->m_pos = origReceiver->mapToParent(dragEvent->m_pos);
3042 origReceiver = origReceiver->parentWidget();
3043 }
3044 }
3045 res = d->notify_helper(w, e);
3046 if (e->type() != QEvent::DragMove
3047#if QT_CONFIG(graphicsview)
3048 && !isProxyWidget
3049#endif
3050 )
3051 QDragManager::self()->setCurrentTarget(nullptr, e->type() == QEvent::Drop);
3052 break;
3053 }
3054#endif // QT_CONFIG(draganddrop)
3055 case QEvent::TouchBegin: {
3056 // Note: TouchUpdate and TouchEnd events are never propagated
3057 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
3058 bool eventAccepted = touchEvent->isAccepted();
3059 bool acceptTouchEvents = w->testAttribute(Qt::WA_AcceptTouchEvents);
3060
3061 if (acceptTouchEvents && e->spontaneous()
3062 && touchEvent->device()->type() != QInputDevice::DeviceType::TouchPad) {
3063 const QPoint localPos = touchEvent->points()[0].position().toPoint();
3064 QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, localPos);
3065 }
3066
3067#ifndef QT_NO_GESTURES
3068 QPointer<QWidget> gesturePendingWidget;
3069#endif
3070
3071 while (w) {
3072 // first, try to deliver the touch event
3073 acceptTouchEvents = w->testAttribute(Qt::WA_AcceptTouchEvents);
3074 QMutableTouchEvent::setTarget(touchEvent, w);
3075 touchEvent->setAccepted(acceptTouchEvents);
3076 QPointer<QWidget> p = w;
3077 res = acceptTouchEvents && d->notify_helper(w, touchEvent);
3078 eventAccepted = touchEvent->isAccepted();
3079 if (p.isNull()) {
3080 // widget was deleted
3081 w = nullptr;
3082 } else {
3083 w->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, res && eventAccepted);
3084 }
3085 touchEvent->m_spont = false;
3086 if (res && eventAccepted) {
3087 // the first widget to accept the TouchBegin gets an implicit grab.
3088 d->activateImplicitTouchGrab(w, touchEvent);
3089 break;
3090 }
3091#ifndef QT_NO_GESTURES
3092 if (gesturePendingWidget.isNull() && w && QGestureManager::gesturePending(w))
3093 gesturePendingWidget = w;
3094#endif
3095 if (!w || w->isWindow() || w->testAttribute(Qt::WA_NoMousePropagation))
3096 break;
3097
3098 const QPoint offset = w->pos();
3099 w = w->parentWidget();
3100 QMutableTouchEvent::setTarget(touchEvent, w);
3101 for (qsizetype cnt = touchEvent->pointCount(), i = 0; i < cnt; ++i) {
3102 auto &pt = touchEvent->point(i);
3103 QMutableEventPoint::setPosition(pt, pt.position() + offset);
3104 }
3105 }
3106
3107#ifndef QT_NO_GESTURES
3108 if (!eventAccepted && !gesturePendingWidget.isNull()) {
3109 // the first widget subscribed to a gesture gets an implicit grab for all
3110 // points, also for events and event points that have not been accepted.
3111 d->activateImplicitTouchGrab(gesturePendingWidget, touchEvent, QApplicationPrivate::GrabAllPoints);
3112 }
3113#endif
3114
3115 touchEvent->setAccepted(eventAccepted);
3116 break;
3117 }
3118 case QEvent::TouchUpdate:
3119 case QEvent::TouchEnd:
3120 // We may get here if the widget is subscribed to a gesture,
3121 // but has not accepted TouchBegin. Propagate touch events
3122 // only if TouchBegin has been accepted.
3123 if (w->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent))
3124 res = d->notify_helper(w, e);
3125 break;
3126 case QEvent::RequestSoftwareInputPanel:
3127 inputMethod()->show();
3128 break;
3129 case QEvent::CloseSoftwareInputPanel:
3130 inputMethod()->hide();
3131 break;
3132
3133#ifndef QT_NO_GESTURES
3134 case QEvent::NativeGesture:
3135 while (w) {
3136 e->ignore();
3137 res = d->notify_helper(w, e);
3138 if (res && e->isAccepted())
3139 break;
3140 if (w->isWindow())
3141 break;
3142 w = w->parentWidget();
3143 }
3144 break;
3145 case QEvent::Gesture:
3146 case QEvent::GestureOverride: {
3147 QGestureEvent *gestureEvent = static_cast<QGestureEvent *>(e);
3148 QList<QGesture *> allGestures = gestureEvent->gestures();
3149
3150 bool eventAccepted = gestureEvent->isAccepted();
3151 bool wasAccepted = eventAccepted;
3152 while (w) {
3153 // send only gestures the widget expects
3154 QList<QGesture *> gestures;
3155 QWidgetPrivate *wd = w->d_func();
3156 for (int i = 0; i < allGestures.size();) {
3157 QGesture *g = allGestures.at(i);
3158 Qt::GestureType type = g->gestureType();
3159 QMap<Qt::GestureType, Qt::GestureFlags>::iterator contextit =
3160 wd->gestureContext.find(type);
3161 bool deliver = contextit != wd->gestureContext.end() &&
3162 (g->state() == Qt::GestureStarted || w == receiver ||
3163 (contextit.value() & Qt::ReceivePartialGestures));
3164 if (deliver) {
3165 allGestures.removeAt(i);
3166 gestures.append(g);
3167 } else {
3168 ++i;
3169 }
3170 }
3171 if (!gestures.isEmpty()) { // we have gestures for this w
3172 QGestureEvent ge(gestures);
3173 ge.t = gestureEvent->t;
3174 ge.m_spont = gestureEvent->spontaneous();
3175 ge.m_accept = wasAccepted;
3176 ge.m_accepted = gestureEvent->m_accepted;
3177 res = d->notify_helper(w, &ge);
3178 gestureEvent->m_spont = false;
3179 eventAccepted = ge.isAccepted();
3180 for (QGesture *g : std::as_const(gestures)) {
3181 // Ignore res [event return value] because handling of multiple gestures
3182 // packed into a single QEvent depends on not consuming the event
3183 if (eventAccepted || ge.isAccepted(g)) {
3184 // if the gesture was accepted, mark the target widget for it
3185 gestureEvent->m_targetWidgets[g->gestureType()] = w;
3186 gestureEvent->setAccepted(g, true);
3187 } else {
3188 // if the gesture was explicitly ignored by the application,
3189 // put it back so a parent can get it
3190 allGestures.append(g);
3191 }
3192 }
3193 }
3194 if (allGestures.isEmpty()) // everything delivered
3195 break;
3196 if (w->isWindow())
3197 break;
3198 w = w->parentWidget();
3199 }
3200 for (QGesture *g : std::as_const(allGestures))
3201 gestureEvent->setAccepted(g, false);
3202 gestureEvent->m_accept = false; // to make sure we check individual gestures
3203 break;
3204 }
3205#endif // QT_NO_GESTURES
3206#ifdef Q_OS_MACOS
3207 // Enable touch events on enter, disable on leave.
3208 case QEvent::Enter:
3209 case QEvent::Leave:
3210 if (w->testAttribute(Qt::WA_AcceptTouchEvents)) {
3211 if (QWindow *window = w->window()->windowHandle()) {
3212 if (auto *cocoaWindow = window->nativeInterface<QNativeInterface::Private::QCocoaWindow>())
3213 cocoaWindow->enableTrackpadTouchDelivery(e->type() == QEvent::Enter);
3214 }
3215 }
3216 res = d->notify_helper(receiver, e);
3217 break;
3218#endif
3219 default:
3220 res = d->notify_helper(receiver, e);
3221 break;
3222 }
3223 } else {
3224 res = d->notify_helper(receiver, e);
3225 }
3226
3227 return res;
3228}
3229
3230bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e)
3231{
3232 // These tracepoints (and the whole function, actually) are very similar
3233 // to the ones in QCoreApplicationPrivate::notify_helper; the reason for their
3234 // duplication is because tracepoint symbols are not exported by QtCore.
3235 // If you adjust the tracepoints here, consider adjusting QCoreApplicationPrivate too.
3236 Q_TRACE(QApplication_notify_entry, receiver, e, e->type());
3237 bool consumed = false;
3238 bool filtered = false;
3239 Q_TRACE_EXIT(QApplication_notify_exit, consumed, filtered);
3240
3241 // send to all application event filters
3242 QThreadData *threadData = receiver->d_func()->threadData.loadRelaxed();
3243 if (threadData->requiresCoreApplication
3244 && threadData->thread.loadAcquire() == mainThread()
3245 && sendThroughApplicationEventFilters(receiver, e)) {
3246 filtered = true;
3247 return filtered;
3248 }
3249
3250 if (receiver->isWidgetType()) {
3251 QWidget *widget = static_cast<QWidget *>(receiver);
3252
3253#if !defined(QT_NO_CURSOR)
3254 // toggle HasMouse widget state on enter and leave
3255 if ((e->type() == QEvent::Enter || e->type() == QEvent::DragEnter) &&
3256 (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == widget->window()))
3257 widget->setAttribute(Qt::WA_UnderMouse, true);
3258 else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave)
3259 widget->setAttribute(Qt::WA_UnderMouse, false);
3260#endif
3261
3262 if (QLayout *layout=widget->d_func()->layout) {
3263 layout->widgetEvent(e);
3264 }
3265 }
3266
3267 // send to all receiver event filters
3268 if (sendThroughObjectEventFilters(receiver, e)) {
3269 filtered = true;
3270 return filtered;
3271 }
3272
3273 // deliver the event
3274 consumed = receiver->event(e);
3275
3276 QCoreApplicationPrivate::setEventSpontaneous(e, false);
3277 return consumed;
3278}
3279
3280bool QApplicationPrivate::inPopupMode()
3281{
3282 return QGuiApplicationPrivate::activePopupWindow() != nullptr;
3283}
3284
3285static void ungrabKeyboardForPopup(QWidget *popup)
3286{
3287 qCDebug(lcWidgetPopup) << "ungrab keyboard for" << popup;
3288 if (QWidget::keyboardGrabber())
3289 qt_widget_private(QWidget::keyboardGrabber())->stealKeyboardGrab(true);
3290 else
3291 qt_widget_private(popup)->stealKeyboardGrab(false);
3292}
3293
3294static void ungrabMouseForPopup(QWidget *popup)
3295{
3296 qCDebug(lcWidgetPopup) << "ungrab mouse for" << popup;
3297 if (QWidget::mouseGrabber())
3298 qt_widget_private(QWidget::mouseGrabber())->stealMouseGrab(true);
3299 else
3300 qt_widget_private(popup)->stealMouseGrab(false);
3301}
3302
3303static bool popupGrabOk;
3304
3305static void grabForPopup(QWidget *popup)
3306{
3307 Q_ASSERT(popup->testAttribute(Qt::WA_WState_Created));
3308 popupGrabOk = qt_widget_private(popup)->stealKeyboardGrab(true);
3309 if (popupGrabOk) {
3310 popupGrabOk = qt_widget_private(popup)->stealMouseGrab(true);
3311 if (!popupGrabOk) {
3312 // transfer grab back to the keyboard grabber if any
3313 ungrabKeyboardForPopup(popup);
3314 }
3315 }
3316 qCDebug(lcWidgetPopup) << "grabbed mouse and keyboard?" << popupGrabOk << "for popup" << popup;
3317}
3318
3319void QApplicationPrivate::closePopup(QWidget *popup)
3320{
3321 QWindow *win = popup->windowHandle();
3322 if (!win)
3323 return;
3324 if (!QGuiApplicationPrivate::closePopup(win))
3325 return;
3326
3327 const QWindow *nextRemainingPopup = QGuiApplicationPrivate::activePopupWindow();
3328 if (!nextRemainingPopup) { // this was the last popup
3329
3330 if (popupGrabOk) {
3331 popupGrabOk = false;
3332
3333 if (active_window && active_window->windowHandle()
3334 && !popup->geometry().contains(QGuiApplicationPrivate::lastCursorPosition.toPoint())
3335 && !popup->testAttribute(Qt::WA_NoMouseReplay)) {
3336 QApplicationPrivate::replayMousePress = true;
3337 }
3338
3339 // transfer grab back to mouse grabber if any, otherwise release the grab
3340 ungrabMouseForPopup(popup);
3341
3342 // transfer grab back to keyboard grabber if any, otherwise release the grab
3343 ungrabKeyboardForPopup(popup);
3344 }
3345
3346 if (active_window) {
3347 if (QWidget *fw = active_window->focusWidget()) {
3348 if (fw != QApplication::focusWidget()) {
3349 fw->setFocus(Qt::PopupFocusReason);
3350 } else {
3351 QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason);
3352 QCoreApplication::sendEvent(fw, &e);
3353 }
3354 }
3355 }
3356
3357 } else if (const auto *popupWin = qobject_cast<const QWidgetWindow *>(nextRemainingPopup)) {
3358 // A popup was closed, so the previous popup gets the focus.
3359 if (QWidget *fw = popupWin->widget()->focusWidget())
3360 fw->setFocus(Qt::PopupFocusReason);
3361
3362 // can become nullptr due to setFocus() above
3363 if (QGuiApplicationPrivate::popupCount() == 1) // grab mouse/keyboard
3364 grabForPopup(popupWin->widget());
3365 }
3366
3367}
3368
3369void QApplicationPrivate::openPopup(QWidget *popup)
3370{
3371 QGuiApplicationPrivate::activatePopup(popup->windowHandle());
3372
3373 if (QGuiApplicationPrivate::popupCount() == 1) // grab mouse/keyboard
3374 grabForPopup(popup);
3375
3376 // popups are not focus-handled by the window system (the first
3377 // popup grabbed the keyboard), so we have to do that manually: A
3378 // new popup gets the focus
3379 if (popup->focusWidget()) {
3380 popup->focusWidget()->setFocus(Qt::PopupFocusReason);
3381 } else if (QGuiApplicationPrivate::popupCount() == 1) { // this was the first popup
3382 if (QWidget *fw = QApplication::focusWidget()) {
3383 QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason);
3384 QCoreApplication::sendEvent(fw, &e);
3385 }
3386 }
3387}
3388
3389/*!
3390 \fn void QApplication::alert(QWidget *widget, int msec)
3391 \since 4.3
3392
3393 Causes an alert to be shown for \a widget if the window is not the active
3394 window. The alert is shown for \a msec milliseconds. If \a msec is zero (the
3395 default), then the alert is shown indefinitely until the window becomes
3396 active again.
3397
3398 Currently this function does nothing on Qt for Embedded Linux.
3399
3400 On \macos, this works more at the application level and will cause the
3401 application icon to bounce in the dock.
3402
3403 On Windows, this causes the window's taskbar entry to flash for a time. If
3404 \a msec is zero, the flashing will stop and the taskbar entry will turn a
3405 different color (currently orange).
3406
3407 On X11, this will cause the window to be marked as "demands attention", the
3408 window must not be hidden (i.e. not have hide() called on it, but be
3409 visible in some sort of way) in order for this to work.
3410*/
3411void QApplication::alert(QWidget *widget, int duration)
3412{
3413 if (widget) {
3414 if (widget->window()->isActiveWindow() && !(widget->window()->windowState() & Qt::WindowMinimized))
3415 return;
3416 if (QWindow *window= QApplicationPrivate::windowForWidget(widget))
3417 window->alert(duration);
3418 } else {
3419 const auto topLevels = topLevelWidgets();
3420 for (QWidget *topLevel : topLevels)
3421 QApplication::alert(topLevel, duration);
3422 }
3423}
3424
3425/*!
3426 \property QApplication::cursorFlashTime
3427 \brief the text cursor's flash (blink) time in milliseconds
3428
3429 The flash time is the time required to display, invert and restore the
3430 caret display. Usually the text cursor is displayed for half the cursor
3431 flash time, then hidden for the same amount of time, but this may vary.
3432
3433 The default value on X11 is 1000 milliseconds. On Windows, the
3434 \uicontrol{Control Panel} value is used and setting this property sets the cursor
3435 flash time for all applications.
3436
3437 We recommend that widgets do not cache this value as it may change at any
3438 time if the user changes the global desktop settings.
3439
3440 \note This property may hold a negative value, for instance if cursor
3441 blinking is disabled.
3442*/
3443void QApplication::setCursorFlashTime(int msecs)
3444{
3445 QGuiApplication::styleHints()->setCursorFlashTime(msecs);
3446}
3447
3448int QApplication::cursorFlashTime()
3449{
3450 return QGuiApplication::styleHints()->cursorFlashTime();
3451}
3452
3453/*!
3454 \property QApplication::doubleClickInterval
3455 \brief the time limit in milliseconds that distinguishes a double click
3456 from two consecutive mouse clicks
3457
3458 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
3459 operating system's value is used.
3460*/
3461void QApplication::setDoubleClickInterval(int ms)
3462{
3463 QGuiApplication::styleHints()->setMouseDoubleClickInterval(ms);
3464}
3465
3466int QApplication::doubleClickInterval()
3467{
3468 return QGuiApplication::styleHints()->mouseDoubleClickInterval();
3469}
3470
3471/*!
3472 \property QApplication::keyboardInputInterval
3473 \brief the time limit in milliseconds that distinguishes a key press
3474 from two consecutive key presses
3475 \since 4.2
3476
3477 The default value on X11 is 400 milliseconds. On Windows and Mac OS, the
3478 operating system's value is used.
3479*/
3480void QApplication::setKeyboardInputInterval(int ms)
3481{
3482 QGuiApplication::styleHints()->setKeyboardInputInterval(ms);
3483}
3484
3485int QApplication::keyboardInputInterval()
3486{
3487 return QGuiApplication::styleHints()->keyboardInputInterval();
3488}
3489
3490/*!
3491 \property QApplication::wheelScrollLines
3492 \brief the number of lines to scroll a widget, when the
3493 mouse wheel is rotated.
3494
3495 If the value exceeds the widget's number of visible lines, the widget
3496 should interpret the scroll operation as a single \e{page up} or
3497 \e{page down}. If the widget is an \l{QAbstractItemView}{item view class},
3498 then the result of scrolling one \e line depends on the setting of the
3499 widget's \l{QAbstractItemView::verticalScrollMode()}{scroll mode}. Scroll
3500 one \e line can mean \l{QAbstractItemView::ScrollPerItem}{scroll one item}
3501 or \l{QAbstractItemView::ScrollPerPixel}{scroll one pixel}.
3502
3503 By default, this property has a value of 3.
3504
3505 \sa QStyleHints::wheelScrollLines()
3506*/
3507#if QT_CONFIG(wheelevent)
3508int QApplication::wheelScrollLines()
3509{
3510 return styleHints()->wheelScrollLines();
3511}
3512
3513void QApplication::setWheelScrollLines(int lines)
3514{
3515 styleHints()->setWheelScrollLines(lines);
3516}
3517#endif
3518
3519static inline int uiEffectToFlag(Qt::UIEffect effect)
3520{
3521 switch (effect) {
3522 case Qt::UI_General:
3523 return QPlatformTheme::GeneralUiEffect;
3524 case Qt::UI_AnimateMenu:
3525 return QPlatformTheme::AnimateMenuUiEffect;
3526 case Qt::UI_FadeMenu:
3527 return QPlatformTheme::FadeMenuUiEffect;
3528 case Qt::UI_AnimateCombo:
3529 return QPlatformTheme::AnimateComboUiEffect;
3530 case Qt::UI_AnimateTooltip:
3531 return QPlatformTheme::AnimateTooltipUiEffect;
3532 case Qt::UI_FadeTooltip:
3533 return QPlatformTheme::FadeTooltipUiEffect;
3534 case Qt::UI_AnimateToolBox:
3535 return QPlatformTheme::AnimateToolBoxUiEffect;
3536 }
3537 return 0;
3538}
3539
3540/*!
3541 \fn void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
3542
3543 Enables the UI effect \a effect if \a enable is true, otherwise the effect
3544 will not be used.
3545
3546 \note All effects are disabled on screens running at less than 16-bit color
3547 depth.
3548
3549 \sa isEffectEnabled(), Qt::UIEffect, setDesktopSettingsAware()
3550*/
3551void QApplication::setEffectEnabled(Qt::UIEffect effect, bool enable)
3552{
3553 int effectFlags = uiEffectToFlag(effect);
3554 if (enable) {
3555 if (effectFlags & QPlatformTheme::FadeMenuUiEffect)
3556 effectFlags |= QPlatformTheme::AnimateMenuUiEffect;
3557 if (effectFlags & QPlatformTheme::FadeTooltipUiEffect)
3558 effectFlags |= QPlatformTheme::AnimateTooltipUiEffect;
3559 QApplicationPrivate::enabledAnimations |= effectFlags;
3560 } else {
3561 QApplicationPrivate::enabledAnimations &= ~effectFlags;
3562 }
3563}
3564
3565/*!
3566 \fn bool QApplication::isEffectEnabled(Qt::UIEffect effect)
3567
3568 Returns \c true if \a effect is enabled; otherwise returns \c false.
3569
3570 By default, Qt will try to use the desktop settings. To prevent this, call
3571 setDesktopSettingsAware(false).
3572
3573 \note All effects are disabled on screens running at less than 16-bit color
3574 depth.
3575
3576 \sa setEffectEnabled(), Qt::UIEffect
3577*/
3578bool QApplication::isEffectEnabled(Qt::UIEffect effect)
3579{
3580 CHECK_QAPP_INSTANCE(false)
3581 const auto primaryScreenDepth = QGuiApplication::primaryScreen() ?
3582 QGuiApplication::primaryScreen()->depth() : 24;
3583 return primaryScreenDepth >= 16
3584 && (QApplicationPrivate::enabledAnimations & QPlatformTheme::GeneralUiEffect)
3585 && (QApplicationPrivate::enabledAnimations & uiEffectToFlag(effect));
3586}
3587
3588/*!
3589 \fn void QApplication::beep()
3590
3591 Sounds the bell, using the default volume and sound. The function is \e not
3592 available in Qt for Embedded Linux.
3593*/
3594void QApplication::beep()
3595{
3596 QGuiApplicationPrivate::platformIntegration()->beep();
3597}
3598
3599/*!
3600 \macro qApp
3601 \relates QApplication
3602
3603 A global pointer referring to the unique application object. It is
3604 equivalent to QCoreApplication::instance(), but cast as a QApplication pointer,
3605 so only valid when the unique application object is a QApplication.
3606
3607 \sa QCoreApplication::instance(), qGuiApp
3608*/
3609
3610bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
3611{
3612 return QGuiApplication::sendSpontaneousEvent(receiver, event);
3613}
3614
3615void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget, QEvent *event, QPoint localPos)
3616{
3617 const bool setFocusOnRelease = QGuiApplication::styleHints()->setFocusOnTouchRelease();
3618 Qt::FocusPolicy focusPolicy = Qt::ClickFocus;
3619 static QPointer<QWidget> focusedWidgetOnTouchBegin = nullptr;
3620
3621 switch (event->type()) {
3622 case QEvent::MouseButtonPress:
3623 case QEvent::MouseButtonDblClick:
3624 case QEvent::TouchBegin:
3625 focusedWidgetOnTouchBegin = QApplication::focusWidget();
3626 if (setFocusOnRelease)
3627 return;
3628 break;
3629 case QEvent::MouseButtonRelease:
3630 case QEvent::TouchEnd:
3631 if (!setFocusOnRelease)
3632 return;
3633 if (focusedWidgetOnTouchBegin != QApplication::focusWidget()) {
3634 // Focus widget was changed while delivering press/move events.
3635 // To not interfere with application logic, we leave focus as-is
3636 return;
3637 }
3638 break;
3639 case QEvent::Wheel:
3640 focusPolicy = Qt::WheelFocus;
3641 break;
3642 default:
3643 return;
3644 }
3645
3646 QWidget *focusWidget = widget;
3647 while (focusWidget) {
3648 if (focusWidget->isEnabled()
3649 && focusWidget->rect().contains(localPos)
3650 && QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) {
3651 focusWidget->setFocus(Qt::MouseFocusReason);
3652 break;
3653 }
3654 if (focusWidget->isWindow())
3655 break;
3656
3657 // find out whether this widget (or its proxy) already has focus
3658 QWidget *f = focusWidget;
3659 if (focusWidget->d_func()->extra && focusWidget->d_func()->extra->focus_proxy)
3660 f = focusWidget->d_func()->extra->focus_proxy;
3661 // if it has, stop here.
3662 // otherwise a click on the focused widget would remove its focus if ClickFocus isn't set
3663 if (f->hasFocus())
3664 break;
3665
3666 localPos += focusWidget->pos();
3667 focusWidget = focusWidget->parentWidget();
3668 }
3669}
3670
3671bool QApplicationPrivate::shouldSetFocus(QWidget *w, Qt::FocusPolicy policy)
3672{
3673 QWidget *f = w;
3674 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
3675 f = f->d_func()->extra->focus_proxy;
3676
3677 if ((w->focusPolicy() & policy) != policy)
3678 return false;
3679 if (w != f && (f->focusPolicy() & policy) != policy)
3680 return false;
3681 return true;
3682}
3683
3684bool QApplicationPrivate::updateTouchPointsForWidget(QWidget *widget, QTouchEvent *touchEvent)
3685{
3686 bool containsPress = false;
3687
3688 for (qsizetype cnt = touchEvent->pointCount(), i = 0; i < cnt; ++i) {
3689 auto &pt = touchEvent->point(i);
3690 QMutableEventPoint::setPosition(pt, widget->mapFromGlobal(pt.globalPosition()));
3691
3692 if (pt.state() == QEventPoint::State::Pressed)
3693 containsPress = true;
3694 }
3695 return containsPress;
3696}
3697
3698void QApplicationPrivate::initializeMultitouch()
3699{
3700 initializeMultitouch_sys();
3701}
3702
3703void QApplicationPrivate::initializeMultitouch_sys()
3704{
3705}
3706
3707void QApplicationPrivate::cleanupMultitouch()
3708{
3709 cleanupMultitouch_sys();
3710}
3711
3712void QApplicationPrivate::cleanupMultitouch_sys()
3713{
3714}
3715
3716/*! \internal
3717 Check the target widgets of the active touchpoints of the given \a device,
3718 and choose the widget that is closest to any of the points. This widget
3719 will then get all the touchpoints, even if it would not otherwise be the
3720 target for some of them.
3721
3722 \sa translateRawTouchEvent()
3723*/
3724QWidget *QApplicationPrivate::findClosestTouchPointTarget(const QPointingDevice *device, const QEventPoint &touchPoint)
3725{
3726 const QPointF globalPos = touchPoint.globalPosition();
3727 int closestTouchPointId = -1;
3728 QObject *closestTarget = nullptr;
3729 qreal closestDistance = 0;
3730 const QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(device);
3731 for (auto &epd : devPriv->activePoints.values()) {
3732 const auto &pt = epd.eventPoint;
3733 if (pt.id() != touchPoint.id() && QMutableEventPoint::target(pt)) {
3734 qreal dx = globalPos.x() - pt.globalPosition().x();
3735 qreal dy = globalPos.y() - pt.globalPosition().y();
3736 qreal distance = dx * dx + dy * dy;
3737 // closestTouchPointId is -1 at the beginning.
3738 // closestTouchPointId may be 0 if
3739 // a synth-mouse eventPoint was found in activePoints: that's not relevant here.
3740 if (closestTouchPointId <= 0 || distance < closestDistance) {
3741 closestTouchPointId = pt.id();
3742 closestDistance = distance;
3743 closestTarget = QMutableEventPoint::target(pt);
3744 }
3745 }
3746 }
3747 return static_cast<QWidget *>(closestTarget);
3748}
3749
3750void QApplicationPrivate::activateImplicitTouchGrab(QWidget *widget, QTouchEvent *touchEvent,
3751 ImplicitTouchGrabMode grabMode)
3752{
3753 if (touchEvent->type() != QEvent::TouchBegin)
3754 return;
3755
3756 // If the widget dispatched the event further (see QGraphicsProxyWidget), then
3757 // there might already be an implicit grabber. Don't override that. A widget that
3758 // has partially recognized a gesture needs to grab all points.
3759 for (qsizetype cnt = touchEvent->pointCount(), i = 0; i < cnt; ++i) {
3760 auto &ep = touchEvent->point(i);
3761 if (!QMutableEventPoint::target(ep) && (ep.isAccepted() || grabMode == GrabAllPoints))
3762 QMutableEventPoint::setTarget(ep, widget);
3763 }
3764 // TODO setExclusiveGrabber() to be consistent with Qt Quick?
3765}
3766
3767bool QApplicationPrivate::translateRawTouchEvent(QWidget *window, const QTouchEvent *te)
3768{
3769 QApplicationPrivate *d = self;
3770 // TODO get rid of this std::pair
3771 typedef std::pair<QEventPoint::State, QList<QEventPoint> > StatesAndTouchPoints;
3772 QHash<QWidget *, StatesAndTouchPoints> widgetsNeedingEvents;
3773
3774 const auto *device = te->pointingDevice();
3775 auto touchPoints = te->points(); // touch points will be mutated
3776 for (auto &touchPoint : touchPoints) {
3777 // update state
3778 QPointer<QObject> target;
3779 if (touchPoint.state() == QEventPoint::State::Pressed) {
3780 if (device->type() == QInputDevice::DeviceType::TouchPad) {
3781 // on touchpads, send all touch points to the same widget:
3782 // pick the first non-null target if possible
3783 target = QPointingDevicePrivate::get(device)->firstActiveTarget();
3784 }
3785
3786 if (target.isNull()) {
3787 // determine which widget this event will go to
3788 if (!window)
3789 window = QApplication::topLevelAt(touchPoint.globalPosition().toPoint());
3790 if (!window)
3791 continue;
3792 target = window->childAt(window->mapFromGlobal(touchPoint.globalPosition()));
3793 if (!target)
3794 target = window;
3795 }
3796
3797 bool usingClosestWidget = false;
3798 if (device->type() == QInputDevice::DeviceType::TouchScreen) {
3799 QWidget *closestWidget = d->findClosestTouchPointTarget(device, touchPoint);
3800 QWidget *widget = static_cast<QWidget *>(target.data());
3801 if (closestWidget
3802 && (widget->isAncestorOf(closestWidget) || closestWidget->isAncestorOf(widget))) {
3803 target = closestWidget;
3804 usingClosestWidget = true;
3805 }
3806 }
3807
3808 // on touch pads, implicitly grab all touch points
3809 // on touch screens, grab touch points that are redirected to the closest widget
3810 if (device->type() == QInputDevice::DeviceType::TouchPad || usingClosestWidget)
3811 QMutableEventPoint::setTarget(touchPoint, target);
3812 } else {
3813 target = QMutableEventPoint::target(touchPoint);
3814 if (!target)
3815 continue;
3816 }
3817 Q_ASSERT(!target.isNull());
3818
3819 QWidget *targetWidget = static_cast<QWidget *>(target.data());
3820
3821#ifdef Q_OS_MACOS
3822 // On macOS single-touch events are not sent unless WA_TouchPadAcceptSingleTouchEvents is set.
3823 // We also have similar logic in the Cocoa platform plugin for non-widget windows, with slight
3824 // behavior difference in how we deal with the last remaining point (we release it prematurely).
3825 // It's unclear why this code is macOS only. FIXME: Unify behavior for macOS, and across platforms.
3826 if (touchPoints.count() == 1
3827 && device->type() == QInputDevice::DeviceType::TouchPad
3828 && !targetWidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents)
3829 && !targetWidget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent))
3830 continue;
3831#endif
3832
3833 StatesAndTouchPoints &maskAndPoints = widgetsNeedingEvents[targetWidget];
3834 maskAndPoints.first = QEventPoint::State(maskAndPoints.first | touchPoint.state());
3835 maskAndPoints.second.append(touchPoint);
3836 }
3837
3838 if (widgetsNeedingEvents.isEmpty())
3839 return false;
3840
3841 bool accepted = false;
3842 QHash<QWidget *, StatesAndTouchPoints>::ConstIterator it = widgetsNeedingEvents.constBegin();
3843 const QHash<QWidget *, StatesAndTouchPoints>::ConstIterator end = widgetsNeedingEvents.constEnd();
3844 for (; it != end; ++it) {
3845 const QPointer<QWidget> widget = it.key();
3846 if (!QApplicationPrivate::tryModalHelper(widget, nullptr))
3847 continue;
3848
3849 QEvent::Type eventType;
3850 switch (it.value().first) {
3851 case QEventPoint::State::Pressed:
3852 eventType = QEvent::TouchBegin;
3853 break;
3854 case QEventPoint::State::Released:
3855 eventType = QEvent::TouchEnd;
3856 break;
3857 case QEventPoint::State::Stationary:
3858 // don't send the event if nothing changed
3859 continue;
3860 default:
3861 eventType = QEvent::TouchUpdate;
3862 break;
3863 }
3864
3865 QMutableTouchEvent touchEvent(eventType, device, QGuiApplication::keyboardModifiers(),
3866 it.value().second);
3867 bool containsPress = updateTouchPointsForWidget(widget, &touchEvent);
3868 touchEvent.setTimestamp(te->timestamp());
3869 touchEvent.setTarget(widget);
3870
3871 if (containsPress)
3872 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
3873
3874 switch (touchEvent.type()) {
3875 case QEvent::TouchBegin:
3876 {
3877 // if the TouchBegin handler recurses, we assume that means the event
3878 // has been implicitly accepted and continue to send touch events
3879 bool res = te->spontaneous() ? QApplication::sendSpontaneousEvent(widget, &touchEvent)
3880 : QApplication::sendEvent(widget, &touchEvent);
3881 if (res && touchEvent.isAccepted()) {
3882 accepted = true;
3883 if (!widget.isNull())
3884 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent);
3885 }
3886 break;
3887 }
3888 default:
3889 if (widget->testAttribute(Qt::WA_WState_AcceptedTouchBeginEvent)
3890#ifndef QT_NO_GESTURES
3891 || QGestureManager::gesturePending(widget)
3892#endif
3893 ) {
3894 bool res = te->spontaneous() ? QApplication::sendSpontaneousEvent(widget, &touchEvent)
3895 : QApplication::sendEvent(widget, &touchEvent);
3896 if (res && touchEvent.isAccepted())
3897 accepted = true;
3898 // widget can be deleted on TouchEnd
3899 if (touchEvent.type() == QEvent::TouchEnd && !widget.isNull())
3900 widget->setAttribute(Qt::WA_WState_AcceptedTouchBeginEvent, false);
3901 }
3902 break;
3903 }
3904 }
3905 return accepted;
3906}
3907
3908void QApplicationPrivate::translateTouchCancel(const QPointingDevice *device, ulong timestamp)
3909{
3910 QMutableTouchEvent touchEvent(QEvent::TouchCancel, device, QGuiApplication::keyboardModifiers());
3911 touchEvent.setTimestamp(timestamp);
3912
3913 QSet<QWidget *> widgetsNeedingCancel;
3914 const QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(device);
3915 for (auto &epd : devPriv->activePoints.values()) {
3916 const auto &pt = epd.eventPoint;
3917 QObject *target = QMutableEventPoint::target(pt);
3918 if (target && target->isWidgetType())
3919 widgetsNeedingCancel.insert(static_cast<QWidget *>(target));
3920 }
3921 for (QSet<QWidget *>::const_iterator widIt = widgetsNeedingCancel.constBegin(),
3922 widItEnd = widgetsNeedingCancel.constEnd(); widIt != widItEnd; ++widIt) {
3923 QWidget *widget = *widIt;
3924 touchEvent.setTarget(widget);
3925 QApplication::sendSpontaneousEvent(widget, &touchEvent);
3926 }
3927}
3928
3929void QApplicationPrivate::handleThemeChanged()
3930{
3931 QGuiApplicationPrivate::handleThemeChanged();
3932
3933 qt_init_tooltip_palette();
3934}
3935
3936#if QT_CONFIG(draganddrop)
3937void QApplicationPrivate::notifyDragStarted(const QDrag *drag)
3938{
3939 QGuiApplicationPrivate::notifyDragStarted(drag);
3940 // QTBUG-26145
3941 // Prevent pickMouseReceiver() from using the widget where the drag was started after a drag operation...
3942 // QTBUG-56713
3943 // ...only if qt_button_down is not a QQuickWidget
3944 if (qt_button_down && !qt_button_down->inherits("QQuickWidget"))
3945 qt_button_down = nullptr;
3946}
3947#endif // QT_CONFIG(draganddrop)
3948
3949#ifndef QT_NO_GESTURES
3950QGestureManager* QGestureManager::instance(InstanceCreation ic)
3951{
3952 QApplicationPrivate *qAppPriv = QApplicationPrivate::instance();
3953 if (!qAppPriv)
3954 return nullptr;
3955 if (!qAppPriv->gestureManager && ic == ForceCreation)
3956 qAppPriv->gestureManager = new QGestureManager(qApp);
3957 return qAppPriv->gestureManager;
3958}
3959#endif // QT_NO_GESTURES
3960
3961QPixmap QApplicationPrivate::applyQIconStyleHelper(QIcon::Mode mode, const QPixmap& base) const
3962{
3963 QStyleOption opt(0);
3964 opt.palette = QGuiApplication::palette();
3965 return QApplication::style()->generatedIconPixmap(mode, base, &opt);
3966}
3967
3968void *QApplication::resolveInterface(const char *name, int revision) const
3969{
3970 return QGuiApplication::resolveInterface(name, revision);
3971}
3972
3973QT_END_NAMESPACE
3974
3975#include "moc_qapplication.cpp"
friend class QWidget
Definition qpainter.h:432
The QWidget class is the base class of all user interface objects.
Definition qwidget.h:99
Q_GLOBAL_STATIC(DefaultRoleNames, qDefaultRoleNames, { { Qt::DisplayRole, "display" }, { Qt::DecorationRole, "decoration" }, { Qt::EditRole, "edit" }, { Qt::ToolTipRole, "toolTip" }, { Qt::StatusTipRole, "statusTip" }, { Qt::WhatsThisRole, "whatsThis" }, }) const QHash< int
static int uiEffectToFlag(Qt::UIEffect effect)
static void initResources()
void qt_init_tooltip_palette()
static void ungrabMouseForPopup(QWidget *popup)
static void ungrabKeyboardForPopup(QWidget *popup)
Q_TRACE_POINT(qtwidgets, QApplication_notify_entry, QObject *receiver, QEvent *event, QEvent::Type type)
Q_WIDGETS_EXPORT bool qt_tryModalHelper(QWidget *widget, QWidget **rettop)
int qt_antialiasing_threshold
bool qt_in_tab_key_event
static bool popupGrabOk
void qRegisterWidgetsVariant()
static void grabForPopup(QWidget *popup)
QPointer< QWidget > qt_last_mouse_receiver
QWidget * qt_tlw_for_window(QWindow *wnd)
Q_GUI_EXPORT bool qt_sendShortcutOverrideEvent(QObject *o, ulong timestamp, int k, Qt::KeyboardModifiers mods, const QString &text=QString(), bool autorep=false, ushort count=1)
bool qt_try_modal(QWidget *widget, QEvent::Type type)
Q_TRACE_POINT(qtcore, QCoreApplication_notify_exit, bool consumed, bool filtered)
Q_TRACE_METADATA(qtcore, "ENUM { AUTO, RANGE User ... MaxUser } QEvent::Type;")
Q_TRACE_PREFIX(qtcore, "#include <qcoreevent.h>")
#define qApp
Q_CORE_EXPORT void qt_call_post_routines()
#define CHECK_QAPP_INSTANCE(...)
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
bool qt_sendSpontaneousEvent(QObject *, QEvent *)
#define QWIDGETSIZE_MAX
Definition qwidget.h:919