Update spec to build Qt 5.0
[profile/ivi/qtbase.git] / src / widgets / kernel / qwidget.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia.  For licensing terms and
14 ** conditions see http://qt.digia.com/licensing.  For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file.  Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights.  These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file.  Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qapplication.h"
43 #include "qapplication_p.h"
44 #include "qbrush.h"
45 #include "qcursor.h"
46 #include "qdesktopwidget.h"
47 #include "qevent.h"
48 #include "qhash.h"
49 #include "qlayout.h"
50 #include "qmenu.h"
51 #include "qmetaobject.h"
52 #include "qpixmap.h"
53 #include "qpointer.h"
54 #include "qstack.h"
55 #include "qstyle.h"
56 #include "qstylefactory.h"
57 #include "qvariant.h"
58 #include "qwidget.h"
59 #include "qstyleoption.h"
60 #include "qstylehints.h"
61 #ifndef QT_NO_ACCESSIBILITY
62 # include "qaccessible.h"
63 #endif
64 #ifdef Q_WS_MAC
65 # include "qt_mac_p.h"
66 # include "qt_cocoa_helpers_mac_p.h"
67 # include "qmainwindow.h"
68 # include "qtoolbar.h"
69 # include <private/qmainwindowlayout_p.h>
70 #endif
71 #include <qpa/qplatformwindow.h>
72 #include "private/qwidgetwindow_qpa_p.h"
73 #include "qpainter.h"
74 #include "qtooltip.h"
75 #include "qwhatsthis.h"
76 #include "qdebug.h"
77 #include "private/qstylesheetstyle_p.h"
78 #include "private/qstyle_p.h"
79 #include "qfileinfo.h"
80 #include <QtGui/qinputmethod.h>
81
82 #include <private/qgraphicseffect_p.h>
83 #include <qbackingstore.h>
84 #include <private/qwidgetbackingstore_p.h>
85 #ifdef Q_WS_MAC
86 # include <private/qpaintengine_mac_p.h>
87 #endif
88 #include <private/qpaintengine_raster_p.h>
89
90 #include "qwidget_p.h"
91 #include <QtGui/private/qwindow_p.h>
92 #include "qaction_p.h"
93 #include "qlayout_p.h"
94 #include "QtWidgets/qgraphicsproxywidget.h"
95 #include "QtWidgets/qgraphicsscene.h"
96 #include "private/qgraphicsproxywidget_p.h"
97 #include "QtWidgets/qabstractscrollarea.h"
98 #include "private/qabstractscrollarea_p.h"
99 #include "private/qevent_p.h"
100
101 #include "private/qgesturemanager_p.h"
102
103 #ifdef QT_KEYPAD_NAVIGATION
104 #include "qtabwidget.h" // Needed in inTabWidget()
105 #endif // QT_KEYPAD_NAVIGATION
106
107
108 // widget/widget data creation count
109 //#define QWIDGET_EXTRA_DEBUG
110 //#define ALIEN_DEBUG
111
112 QT_BEGIN_NAMESPACE
113
114 static bool qt_enable_backingstore = true;
115 #ifdef Q_WS_X11
116 // for compatibility with Qt 4.0
117 Q_WIDGETS_EXPORT void qt_x11_set_global_double_buffer(bool enable)
118 {
119     qt_enable_backingstore = enable;
120 }
121 #endif
122
123 #ifdef Q_WS_MAC
124 bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
125 #endif
126
127 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
128 {
129     return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
130             qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
131 }
132
133 static inline bool hasBackingStoreSupport()
134 {
135     return true;
136 }
137
138 #ifdef Q_WS_MAC
139 #  define QT_NO_PAINT_DEBUG
140 #endif
141
142 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
143 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
144
145 /*!
146     \internal
147     \class QWidgetBackingStoreTracker
148     \brief Class which allows tracking of which widgets are using a given backing store
149
150     QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
151     which maintains a list of the QWidgets which are currently using the backing
152     store.  This list is modified via the registerWidget and unregisterWidget functions.
153  */
154
155 QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
156     :   m_ptr(0)
157 {
158
159 }
160
161 QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
162 {
163     delete m_ptr;
164 }
165
166 /*!
167     \internal
168     Destroy the contained QWidgetBackingStore, if not null, and clear the list of
169     widgets using the backing store, then create a new QWidgetBackingStore, providing
170     the QWidget.
171  */
172 void QWidgetBackingStoreTracker::create(QWidget *widget)
173 {
174     destroy();
175     m_ptr = new QWidgetBackingStore(widget);
176 }
177
178 /*!
179     \internal
180     Destroy the contained QWidgetBackingStore, if not null, and clear the list of
181     widgets using the backing store.
182  */
183 void QWidgetBackingStoreTracker::destroy()
184 {
185     delete m_ptr;
186     m_ptr = 0;
187     m_widgets.clear();
188 }
189
190 /*!
191     \internal
192     Add the widget to the list of widgets currently using the backing store.
193     If the widget was already in the list, this function is a no-op.
194  */
195 void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
196 {
197     Q_ASSERT(m_ptr);
198     Q_ASSERT(w->internalWinId());
199     Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
200     m_widgets.insert(w);
201 }
202
203 /*!
204     \internal
205     Remove the widget from the list of widgets currently using the backing store.
206     If the widget was in the list, and removing it causes the list to be empty,
207     the backing store is deleted.
208     If the widget was not in the list, this function is a no-op.
209  */
210 void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
211 {
212     if (m_widgets.remove(w) && m_widgets.isEmpty()) {
213         delete m_ptr;
214         m_ptr = 0;
215     }
216 }
217
218 /*!
219     \internal
220     Recursively remove widget and all of its descendents.
221  */
222 void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
223 {
224     unregisterWidget(widget);
225     foreach (QObject *child, widget->children())
226         if (QWidget *childWidget = qobject_cast<QWidget *>(child))
227             unregisterWidgetSubtree(childWidget);
228 }
229
230 QWidgetPrivate::QWidgetPrivate(int version)
231     : QObjectPrivate(version)
232       , extra(0)
233       , focus_next(0)
234       , focus_prev(0)
235       , focus_child(0)
236       , layout(0)
237       , needsFlush(0)
238       , redirectDev(0)
239       , widgetItem(0)
240       , extraPaintEngine(0)
241       , polished(0)
242       , graphicsEffect(0)
243 #if !defined(QT_NO_IM)
244       , imHints(Qt::ImhNone)
245 #endif
246       , inheritedFontResolveMask(0)
247       , inheritedPaletteResolveMask(0)
248       , leftmargin(0)
249       , topmargin(0)
250       , rightmargin(0)
251       , bottommargin(0)
252       , leftLayoutItemMargin(0)
253       , topLayoutItemMargin(0)
254       , rightLayoutItemMargin(0)
255       , bottomLayoutItemMargin(0)
256       , hd(0)
257       , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
258       , fg_role(QPalette::NoRole)
259       , bg_role(QPalette::NoRole)
260       , dirtyOpaqueChildren(1)
261       , isOpaque(0)
262       , inDirtyList(0)
263       , isScrolled(0)
264       , isMoved(0)
265       , usesDoubleBufferedGLContext(0)
266 #ifndef QT_NO_IM
267       , inheritsInputMethodHints(0)
268 #endif
269 #if defined(Q_OS_WIN)
270       , noPaintOnScreen(0)
271 #endif
272 #if defined(Q_WS_X11)
273       , picture(0)
274 #elif defined(Q_WS_WIN)
275   #ifndef QT_NO_GESTURES
276       , nativeGesturePanEnabled(0)
277   #endif
278 #elif defined(Q_WS_MAC)
279       , needWindowChange(0)
280       , window_event(0)
281       , qd_hd(0)
282 #endif
283 {
284     if (!qApp) {
285         qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
286         return;
287     }
288
289     if (version != QObjectPrivateVersion)
290         qFatal("Cannot mix incompatible Qt libraries");
291
292     isWidget = true;
293     memset(high_attributes, 0, sizeof(high_attributes));
294 #ifdef Q_WS_MAC
295     drawRectOriginalAdded = false;
296     originalDrawMethod = true;
297     changeMethods = false;
298     isInUnifiedToolbar = false;
299     unifiedSurface = 0;
300     toolbar_ancestor = 0;
301     flushRequested = false;
302     touchEventsEnabled = false;
303 #endif // Q_WS_MAC
304 #ifdef QWIDGET_EXTRA_DEBUG
305     static int count = 0;
306     qDebug() << "widgets" << ++count;
307 #endif
308 }
309
310
311 QWidgetPrivate::~QWidgetPrivate()
312 {
313     if (widgetItem)
314         widgetItem->wid = 0;
315
316     if (extra)
317         deleteExtra();
318
319 #ifndef QT_NO_GRAPHICSEFFECT
320     delete graphicsEffect;
321 #endif //QT_NO_GRAPHICSEFFECT
322 }
323
324 /*!
325     \internal
326 */
327 void QWidgetPrivate::scrollChildren(int dx, int dy)
328 {
329     Q_Q(QWidget);
330     if (q->children().size() > 0) {        // scroll children
331         QPoint pd(dx, dy);
332         QObjectList childObjects = q->children();
333         for (int i = 0; i < childObjects.size(); ++i) { // move all children
334             QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
335             if (w && !w->isWindow()) {
336                 QPoint oldp = w->pos();
337                 QRect  r(w->pos() + pd, w->size());
338                 w->data->crect = r;
339                 if (w->testAttribute(Qt::WA_WState_Created))
340                     w->d_func()->setWSGeometry();
341                 w->d_func()->setDirtyOpaqueRegion();
342                 QMoveEvent e(r.topLeft(), oldp);
343                 QApplication::sendEvent(w, &e);
344             }
345         }
346     }
347 }
348
349 void QWidgetPrivate::updateWidgetTransform()
350 {
351     Q_Q(QWidget);
352     if (q == qGuiApp->focusObject()) {
353         QTransform t;
354         QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
355         t.translate(p.x(), p.y());
356         qApp->inputMethod()->setInputItemTransform(t);
357     }
358 }
359
360 #ifdef QT_KEYPAD_NAVIGATION
361 QPointer<QWidget> QWidgetPrivate::editingWidget;
362
363 /*!
364     Returns true if this widget currently has edit focus; otherwise false.
365
366     This feature is only available in Qt for Embedded Linux.
367
368     \sa setEditFocus(), QApplication::keypadNavigationEnabled()
369 */
370 bool QWidget::hasEditFocus() const
371 {
372     const QWidget* w = this;
373     while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
374         w = w->d_func()->extra->focus_proxy;
375     return QWidgetPrivate::editingWidget == w;
376 }
377
378 /*!
379     \fn void QWidget::setEditFocus(bool enable)
380
381     If \a enable is true, make this widget have edit focus, in which
382     case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
383     normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
384     change focus.
385
386     This feature is only available in Qt for Embedded Linux.
387
388     \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
389 */
390 void QWidget::setEditFocus(bool on)
391 {
392     QWidget *f = this;
393     while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
394         f = f->d_func()->extra->focus_proxy;
395
396     if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
397         QWidgetPrivate::editingWidget->setEditFocus(false);
398
399     if (on && !f->hasFocus())
400         f->setFocus();
401
402     if ((!on && !QWidgetPrivate::editingWidget)
403         || (on && QWidgetPrivate::editingWidget == f)) {
404         return;
405     }
406
407     if (!on && QWidgetPrivate::editingWidget == f) {
408         QWidgetPrivate::editingWidget = 0;
409         QEvent event(QEvent::LeaveEditFocus);
410         QApplication::sendEvent(f, &event);
411         QApplication::sendEvent(f->style(), &event);
412     } else if (on) {
413         QWidgetPrivate::editingWidget = f;
414         QEvent event(QEvent::EnterEditFocus);
415         QApplication::sendEvent(f, &event);
416         QApplication::sendEvent(f->style(), &event);
417     }
418 }
419 #endif
420
421 /*!
422     \property QWidget::autoFillBackground
423     \brief whether the widget background is filled automatically
424     \since 4.1
425
426     If enabled, this property will cause Qt to fill the background of the
427     widget before invoking the paint event. The color used is defined by the
428     QPalette::Window color role from the widget's \l{QPalette}{palette}.
429
430     In addition, Windows are always filled with QPalette::Window, unless the
431     WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
432
433     This property cannot be turned off (i.e., set to false) if a widget's
434     parent has a static gradient for its background.
435
436     \warning Use this property with caution in conjunction with
437     \l{Qt Style Sheets}. When a widget has a style sheet with a valid
438     background or a border-image, this property is automatically disabled.
439
440     By default, this property is false.
441
442     \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
443     {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
444 */
445 bool QWidget::autoFillBackground() const
446 {
447     Q_D(const QWidget);
448     return d->extra && d->extra->autoFillBackground;
449 }
450
451 void QWidget::setAutoFillBackground(bool enabled)
452 {
453     Q_D(QWidget);
454     if (!d->extra)
455         d->createExtra();
456     if (d->extra->autoFillBackground == enabled)
457         return;
458
459     d->extra->autoFillBackground = enabled;
460     d->updateIsOpaque();
461     update();
462     d->updateIsOpaque();
463 }
464
465 /*!
466     \class QWidget
467     \brief The QWidget class is the base class of all user interface objects.
468
469     \ingroup basicwidgets
470     \inmodule QtWidgets
471
472     The widget is the atom of the user interface: it receives mouse, keyboard
473     and other events from the window system, and paints a representation of
474     itself on the screen. Every widget is rectangular, and they are sorted in a
475     Z-order. A widget is clipped by its parent and by the widgets in front of
476     it.
477
478     A widget that is not embedded in a parent widget is called a window.
479     Usually, windows have a frame and a title bar, although it is also possible
480     to create windows without such decoration using suitable
481     \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
482     subclasses of QDialog are the most common window types.
483
484     Every widget's constructor accepts one or two standard arguments:
485
486     \list 1
487         \li  \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
488             (the default), the new widget will be a window. If not, it will be
489             a child of \e parent, and be constrained by \e parent's geometry
490             (unless you specify Qt::Window as window flag).
491         \li  \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
492             the default is suitable for almost all widgets, but to get, for
493             example, a window without a window system frame, you must use
494             special flags.
495     \endlist
496
497     QWidget has many member functions, but some of them have little direct
498     functionality; for example, QWidget has a font property, but never uses
499     this itself. There are many subclasses which provide real functionality,
500     such as QLabel, QPushButton, QListWidget, and QTabWidget.
501
502
503     \section1 Top-Level and Child Widgets
504
505     A widget without a parent widget is always an independent window (top-level
506     widget). For these widgets, setWindowTitle() and setWindowIcon() set the
507     title bar and icon respectively.
508
509     Non-window widgets are child widgets, displayed within their parent
510     widgets. Most widgets in Qt are mainly useful as child widgets. For
511     example, it is possible to display a button as a top-level window, but most
512     people prefer to put their buttons inside other widgets, such as QDialog.
513
514     \image parent-child-widgets.png A parent widget containing various child widgets.
515
516     The diagram above shows a QGroupBox widget being used to hold various child
517     widgets in a layout provided by QGridLayout. The QLabel child widgets have
518     been outlined to indicate their full sizes.
519
520     If you want to use a QWidget to hold child widgets you will usually want to
521     add a layout to the parent QWidget. See \l{Layout Management} for more
522     information.
523
524
525     \section1 Composite Widgets
526
527     When a widget is used as a container to group a number of child widgets, it
528     is known as a composite widget. These can be created by constructing a
529     widget with the required visual properties - a QFrame, for example - and
530     adding child widgets to it, usually managed by a layout. The above diagram
531     shows such a composite widget that was created using Qt Designer.
532
533     Composite widgets can also be created by subclassing a standard widget,
534     such as QWidget or QFrame, and adding the necessary layout and child
535     widgets in the constructor of the subclass. Many of the \l{Qt Examples}
536     {examples provided with Qt} use this approach, and it is also covered in
537     the Qt \l{Tutorials}.
538
539
540     \section1 Custom Widgets and Painting
541
542     Since QWidget is a subclass of QPaintDevice, subclasses can be used to
543     display custom content that is composed using a series of painting
544     operations with an instance of the QPainter class. This approach contrasts
545     with the canvas-style approach used by the \l{Graphics View}
546     {Graphics View Framework} where items are added to a scene by the
547     application and are rendered by the framework itself.
548
549     Each widget performs all painting operations from within its paintEvent()
550     function. This is called whenever the widget needs to be redrawn, either
551     as a result of some external change or when requested by the application.
552
553     The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
554     can handle paint events.
555
556
557     \section1 Size Hints and Size Policies
558
559     When implementing a new widget, it is almost always useful to reimplement
560     sizeHint() to provide a reasonable default size for the widget and to set
561     the correct size policy with setSizePolicy().
562
563     By default, composite widgets which do not provide a size hint will be
564     sized according to the space requirements of their child widgets.
565
566     The size policy lets you supply good default behavior for the layout
567     management system, so that other widgets can contain and manage yours
568     easily. The default size policy indicates that the size hint represents
569     the preferred size of the widget, and this is often good enough for many
570     widgets.
571
572     \note The size of top-level widgets are constrained to 2/3 of the desktop's
573     height and width. You can resize() the widget manually if these bounds are
574     inadequate.
575
576
577     \section1 Events
578
579     Widgets respond to events that are typically caused by user actions. Qt
580     delivers events to widgets by calling specific event handler functions with
581     instances of QEvent subclasses containing information about each event.
582
583     If your widget only contains child widgets, you probably do not need to
584     implement any event handlers. If you want to detect a mouse click in a
585     child widget call the child's underMouse() function inside the widget's
586     mousePressEvent().
587
588     The \l{widgets/scribble}{Scribble example} implements a wider set of
589     events to handle mouse movement, button presses, and window resizing.
590
591     You will need to supply the behavior and content for your own widgets, but
592     here is a brief overview of the events that are relevant to QWidget,
593     starting with the most common ones:
594
595     \list
596         \li  paintEvent() is called whenever the widget needs to be repainted.
597             Every widget displaying custom content must implement it. Painting
598             using a QPainter can only take place in a paintEvent() or a
599             function called by a paintEvent().
600         \li  resizeEvent() is called when the widget has been resized.
601         \li  mousePressEvent() is called when a mouse button is pressed while
602             the mouse cursor is inside the widget, or when the widget has
603             grabbed the mouse using grabMouse(). Pressing the mouse without
604             releasing it is effectively the same as calling grabMouse().
605         \li  mouseReleaseEvent() is called when a mouse button is released. A
606             widget receives mouse release events when it has received the
607             corresponding mouse press event. This means that if the user
608             presses the mouse inside \e your widget, then drags the mouse
609             somewhere else before releasing the mouse button, \e your widget
610             receives the release event. There is one exception: if a popup menu
611             appears while the mouse button is held down, this popup immediately
612             steals the mouse events.
613         \li  mouseDoubleClickEvent() is called when the user double-clicks in
614             the widget. If the user double-clicks, the widget receives a mouse
615             press event, a mouse release event, (a mouse click event,) a second
616             mouse press, this event and finally a second mouse release event.
617             (Some mouse move events may also be
618             received if the mouse is not held steady during this operation.) It
619             is \e{not possible} to distinguish a click from a double-click
620             until the second click arrives. (This is one reason why most GUI
621             books recommend that double-clicks be an extension of
622             single-clicks, rather than trigger a different action.)
623     \endlist
624
625     Widgets that accept keyboard input need to reimplement a few more event
626     handlers:
627
628     \list
629         \li  keyPressEvent() is called whenever a key is pressed, and again when
630             a key has been held down long enough for it to auto-repeat. The
631             \uicontrol Tab and \uicontrol Shift+Tab keys are only passed to the widget if
632             they are not used by the focus-change mechanisms. To force those
633             keys to be processed by your widget, you must reimplement
634             QWidget::event().
635         \li  focusInEvent() is called when the widget gains keyboard focus
636             (assuming you have called setFocusPolicy()). Well-behaved widgets
637             indicate that they own the keyboard focus in a clear but discreet
638             way.
639         \li  focusOutEvent() is called when the widget loses keyboard focus.
640     \endlist
641
642     You may be required to also reimplement some of the less common event
643     handlers:
644
645     \list
646         \li  mouseMoveEvent() is called whenever the mouse moves while a mouse
647             button is held down. This can be useful during drag and drop
648             operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
649             you get mouse move events even when no buttons are held down.
650             (See also the \l{Drag and Drop} guide.)
651         \li  keyReleaseEvent() is called whenever a key is released and while it
652             is held down (if the key is auto-repeating). In that case, the
653             widget will receive a pair of key release and key press event for
654             every repeat. The \uicontrol Tab and \uicontrol Shift+Tab keys are only passed
655             to the widget if they are not used by the focus-change mechanisms.
656             To force those keys to be processed by your widget, you must
657             reimplement QWidget::event().
658         \li  wheelEvent() is called whenever the user turns the mouse wheel
659             while the widget has the focus.
660         \li  enterEvent() is called when the mouse enters the widget's screen
661             space. (This excludes screen space owned by any of the widget's
662             children.)
663         \li  leaveEvent() is called when the mouse leaves the widget's screen
664             space. If the mouse enters a child widget it will not cause a
665             leaveEvent().
666         \li  moveEvent() is called when the widget has been moved relative to
667             its parent.
668         \li  closeEvent() is called when the user closes the widget (or when
669             close() is called).
670     \endlist
671
672     There are also some rather obscure events described in the documentation
673     for QEvent::Type. To handle these events, you need to reimplement event()
674     directly.
675
676     The default implementation of event() handles \uicontrol Tab and \uicontrol Shift+Tab
677     (to move the keyboard focus), and passes on most of the other events to
678     one of the more specialized handlers above.
679
680     Events and the mechanism used to deliver them are covered in 
681     \l{The Event System}.
682
683     \section1 Groups of Functions and Properties
684
685     \table
686     \header \li Context \li Functions and Properties
687
688     \row \li Window functions \li
689         show(),
690         hide(),
691         raise(),
692         lower(),
693         close().
694
695     \row \li Top-level windows \li
696         \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
697         \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
698         \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
699         showNormal().
700
701     \row \li Window contents \li
702         update(),
703         repaint(),
704         scroll().
705
706     \row \li Geometry \li
707         \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
708         \l sizePolicy, sizeHint(), minimumSizeHint(),
709         updateGeometry(), layout(),
710         \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
711         adjustSize(),
712         mapFromGlobal(), mapToGlobal(),
713         mapFromParent(), mapToParent(),
714         \l maximumSize, \l minimumSize, \l sizeIncrement,
715         \l baseSize, setFixedSize()
716
717     \row \li Mode \li
718         \l visible, isVisibleTo(),
719         \l enabled, isEnabledTo(),
720         \l modal,
721         isWindow(),
722         \l mouseTracking,
723         \l updatesEnabled,
724         visibleRegion().
725
726     \row \li Look and feel \li
727         style(),
728         setStyle(),
729         \l styleSheet,
730         \l cursor,
731         \l font,
732         \l palette,
733         backgroundRole(), setBackgroundRole(),
734         fontInfo(), fontMetrics().
735
736     \row \li Keyboard focus functions \li
737         \l focus, \l focusPolicy,
738         setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
739         focusNextChild(), focusPreviousChild().
740
741     \row \li Mouse and keyboard grabbing \li
742         grabMouse(), releaseMouse(),
743         grabKeyboard(), releaseKeyboard(),
744         mouseGrabber(), keyboardGrabber().
745
746     \row \li Event handlers \li
747         event(),
748         mousePressEvent(),
749         mouseReleaseEvent(),
750         mouseDoubleClickEvent(),
751         mouseMoveEvent(),
752         keyPressEvent(),
753         keyReleaseEvent(),
754         focusInEvent(),
755         focusOutEvent(),
756         wheelEvent(),
757         enterEvent(),
758         leaveEvent(),
759         paintEvent(),
760         moveEvent(),
761         resizeEvent(),
762         closeEvent(),
763         dragEnterEvent(),
764         dragMoveEvent(),
765         dragLeaveEvent(),
766         dropEvent(),
767         childEvent(),
768         showEvent(),
769         hideEvent(),
770         customEvent().
771         changeEvent(),
772
773     \row \li System functions \li
774         parentWidget(), window(), setParent(), winId(),
775         find(), metric().
776
777     \row \li Interactive help \li
778         setToolTip(), setWhatsThis()
779
780     \endtable
781
782
783     \section1 Widget Style Sheets
784
785     In addition to the standard widget styles for each platform, widgets can
786     also be styled according to rules specified in a \l{styleSheet}
787     {style sheet}. This feature enables you to customize the appearance of
788     specific widgets to provide visual cues to users about their purpose. For
789     example, a button could be styled in a particular way to indicate that it
790     performs a destructive action.
791
792     The use of widget style sheets is described in more detail in the
793     \l{Qt Style Sheets} document.
794
795
796     \section1 Transparency and Double Buffering
797
798     Since Qt 4.0, QWidget automatically double-buffers its painting, so there
799     is no need to write double-buffering code in paintEvent() to avoid
800     flicker.
801
802     Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
803     deprecated. Instead, the contents of parent widgets are propagated by
804     default to each of their children as long as Qt::WA_PaintOnScreen is not
805     set. Custom widgets can be written to take advantage of this feature by
806     updating irregular regions (to create non-rectangular child widgets), or
807     painting with colors that have less than full alpha component. The
808     following diagram shows how attributes and properties of a custom widget
809     can be fine-tuned to achieve different effects.
810
811     \image propagation-custom.png
812
813     In the above diagram, a semi-transparent rectangular child widget with an
814     area removed is constructed and added to a parent widget (a QLabel showing
815     a pixmap). Then, different properties and widget attributes are set to
816     achieve different effects:
817
818     \list
819         \li  The left widget has no additional properties or widget attributes
820             set. This default state suits most custom widgets using
821             transparency, are irregularly-shaped, or do not paint over their
822             entire area with an opaque brush.
823         \li  The center widget has the \l autoFillBackground property set. This
824             property is used with custom widgets that rely on the widget to
825             supply a default background, and do not paint over their entire
826             area with an opaque brush.
827         \li  The right widget has the Qt::WA_OpaquePaintEvent widget attribute
828             set. This indicates that the widget will paint over its entire area
829             with opaque colors. The widget's area will initially be
830             \e{uninitialized}, represented in the diagram with a red diagonal
831             grid pattern that shines through the overpainted area. The
832             Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
833             paint their own specialized contents quickly and do not need a
834             default filled background.
835     \endlist
836
837     To rapidly update custom widgets with simple background colors, such as
838     real-time plotting or graphing widgets, it is better to define a suitable
839     background color (using setBackgroundRole() with the
840     QPalette::Window role), set the \l autoFillBackground property, and only
841     implement the necessary drawing functionality in the widget's paintEvent().
842
843     To rapidly update custom widgets that constantly paint over their entire
844     areas with opaque content, e.g., video streaming widgets, it is better to
845     set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
846     associated with repainting the widget's background.
847
848     If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
849     the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
850     attribute takes precedence. Depending on your requirements, you should
851     choose either one of them.
852
853     Since Qt 4.1, the contents of parent widgets are also propagated to
854     standard Qt widgets. This can lead to some unexpected results if the
855     parent widget is decorated in a non-standard way, as shown in the diagram
856     below.
857
858     \image propagation-standard.png
859
860     The scope for customizing the painting behavior of standard Qt widgets,
861     without resorting to subclassing, is slightly less than that possible for
862     custom widgets. Usually, the desired appearance of a standard widget can be
863     achieved by setting its \l autoFillBackground property.
864
865
866     \section1 Creating Translucent Windows
867
868     Since Qt 4.5, it has been possible to create windows with translucent regions
869     on window systems that support compositing.
870
871     To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
872     attribute with setAttribute() and ensure that its background is painted with
873     non-opaque colors in the regions you want to be partially transparent.
874
875     Platform notes:
876
877     \list
878     \li X11: This feature relies on the use of an X server that supports ARGB visuals
879     and a compositing window manager.
880     \li Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
881     for the translucency to work.
882     \endlist
883
884
885     \section1 Native Widgets vs Alien Widgets
886
887     Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
888     system. They do not have a native window handle associated with them. This
889     feature significantly speeds up widget painting, resizing, and removes flicker.
890
891     Should you require the old behavior with native windows, you can choose
892     one of the following options:
893
894     \list 1
895         \li  Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
896         \li  Set the Qt::AA_NativeWindows attribute on your application. All
897             widgets will be native widgets.
898         \li  Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
899             and all of its ancestors will become native (unless
900             Qt::WA_DontCreateNativeAncestors is set).
901         \li  Call QWidget::winId to enforce a native window (this implies 3).
902         \li  Set the Qt::WA_PaintOnScreen attribute to enforce a native window
903             (this implies 3).
904     \endlist
905
906     \sa QEvent, QPainter, QGridLayout, QBoxLayout
907
908 */
909
910 QWidgetMapper *QWidgetPrivate::mapper = 0;          // widget with wid
911 QWidgetSet *QWidgetPrivate::allWidgets = 0;         // widgets with no wid
912
913
914 /*****************************************************************************
915   QWidget utility functions
916  *****************************************************************************/
917
918 QRegion qt_dirtyRegion(QWidget *widget)
919 {
920     if (!widget)
921         return QRegion();
922
923     QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
924     if (!bs)
925         return QRegion();
926
927     return bs->dirtyRegion(widget);
928 }
929
930 /*****************************************************************************
931   QWidget member functions
932  *****************************************************************************/
933
934 /*
935     Widget state flags:
936   \list
937   \li Qt::WA_WState_Created The widget has a valid winId().
938   \li Qt::WA_WState_Visible The widget is currently visible.
939   \li Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
940   become visible unless you call show() on it. Qt::WA_WState_Hidden
941   implies !Qt::WA_WState_Visible.
942   \li Qt::WA_WState_CompressKeys Compress keyboard events.
943   \li Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
944   \li Qt::WA_WState_InPaintEvent Currently processing a paint event.
945   \li Qt::WA_WState_Reparented The widget has been reparented.
946   \li Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
947   \li Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
948   \endlist
949 */
950
951 struct QWidgetExceptionCleaner
952 {
953     /* this cleans up when the constructor throws an exception */
954     static inline void cleanup(QWidget *that, QWidgetPrivate *d)
955     {
956 #ifdef QT_NO_EXCEPTIONS
957         Q_UNUSED(that);
958         Q_UNUSED(d);
959 #else
960         QWidgetPrivate::allWidgets->remove(that);
961         if (d->focus_next != that) {
962             if (d->focus_next)
963                 d->focus_next->d_func()->focus_prev = d->focus_prev;
964             if (d->focus_prev)
965                 d->focus_prev->d_func()->focus_next = d->focus_next;
966         }
967 #endif
968     }
969 };
970
971 /*!
972     Constructs a widget which is a child of \a parent, with  widget
973     flags set to \a f.
974
975     If \a parent is 0, the new widget becomes a window. If
976     \a parent is another widget, this widget becomes a child window
977     inside \a parent. The new widget is deleted when its \a parent is
978     deleted.
979
980     The widget flags argument, \a f, is normally 0, but it can be set
981     to customize the frame of a window (i.e. \a
982     parent must be 0). To customize the frame, use a value composed
983     from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
984
985     If you add a child widget to an already visible widget you must
986     explicitly show the child to make it visible.
987
988     Note that the X11 version of Qt may not be able to deliver all
989     combinations of style flags on all systems. This is because on
990     X11, Qt can only ask the window manager, and the window manager
991     can override the application's settings. On Windows, Qt can set
992     whatever flags you want.
993
994     \sa windowFlags
995 */
996 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
997     : QObject(*new QWidgetPrivate, 0), QPaintDevice()
998 {
999     QT_TRY {
1000         d_func()->init(parent, f);
1001     } QT_CATCH(...) {
1002         QWidgetExceptionCleaner::cleanup(this, d_func());
1003         QT_RETHROW;
1004     }
1005 }
1006
1007
1008 /*! \internal
1009 */
1010 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1011     : QObject(dd, 0), QPaintDevice()
1012 {
1013     Q_D(QWidget);
1014     QT_TRY {
1015         d->init(parent, f);
1016     } QT_CATCH(...) {
1017         QWidgetExceptionCleaner::cleanup(this, d_func());
1018         QT_RETHROW;
1019     }
1020 }
1021
1022 /*!
1023     \internal
1024 */
1025 int QWidget::devType() const
1026 {
1027     return QInternal::Widget;
1028 }
1029
1030
1031 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1032 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1033 {
1034     bool customize =  (flags & (Qt::CustomizeWindowHint
1035             | Qt::FramelessWindowHint
1036             | Qt::WindowTitleHint
1037             | Qt::WindowSystemMenuHint
1038             | Qt::WindowMinimizeButtonHint
1039             | Qt::WindowMaximizeButtonHint
1040             | Qt::WindowCloseButtonHint
1041             | Qt::WindowContextHelpButtonHint));
1042
1043     uint type = (flags & Qt::WindowType_Mask);
1044
1045     if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1046         type = Qt::Window;
1047         flags |= Qt::Window;
1048     }
1049
1050     if (flags & Qt::CustomizeWindowHint) {
1051         // modify window flags to make them consistent.
1052         // Only enable this on non-Mac platforms. Since the old way of doing this would
1053         // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1054         // we can't just add this in.
1055 #ifndef Q_WS_MAC
1056         if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1057             flags |= Qt::WindowSystemMenuHint;
1058 #else
1059         if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1060                      | Qt::WindowSystemMenuHint)) {
1061 #endif
1062             flags |= Qt::WindowTitleHint;
1063             flags &= ~Qt::FramelessWindowHint;
1064         }
1065     } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1066         // if any of the window hints that affect the titlebar are set
1067         // and the window is supposed to have frame, we add a titlebar
1068         // and system menu by default.
1069         flags |= Qt::WindowSystemMenuHint;
1070         flags |= Qt::WindowTitleHint;
1071     }
1072     if (customize)
1073         ; // don't modify window flags if the user explicitly set them.
1074     else if (type == Qt::Dialog || type == Qt::Sheet)
1075 #ifndef Q_OS_WINCE
1076         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1077 #else
1078         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1079 #endif
1080     else if (type == Qt::Tool)
1081         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1082     else
1083         flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint |
1084                 Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint;
1085
1086 }
1087
1088 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1089 {
1090     Q_Q(QWidget);
1091     if (!qobject_cast<QApplication *>(QCoreApplication::instance()))
1092         qFatal("QWidget: Cannot create a QWidget without QApplication");
1093
1094     Q_ASSERT(allWidgets);
1095     if (allWidgets)
1096         allWidgets->insert(q);
1097
1098     QWidget *desktopWidget = 0;
1099     if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1100         desktopWidget = parentWidget;
1101         parentWidget = 0;
1102     }
1103
1104     q->data = &data;
1105
1106 #ifndef QT_NO_THREAD
1107     if (!parent) {
1108         Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1109                    "Widgets must be created in the GUI thread.");
1110     }
1111 #endif
1112
1113 #if defined(Q_WS_X11)
1114     if (desktopWidget) {
1115         // make sure the widget is created on the same screen as the
1116         // programmer specified desktop widget
1117         xinfo = desktopWidget->d_func()->xinfo;
1118     }
1119 #endif
1120     if (desktopWidget) {
1121         const int screen = desktopWidget->d_func()->topData()->screenIndex;
1122         if (QWindow *window = q->windowHandle())
1123             window->setScreen(QGuiApplication::screens().value(screen, 0));
1124     }
1125
1126     data.fstrut_dirty = true;
1127
1128     data.winid = 0;
1129     data.widget_attributes = 0;
1130     data.window_flags = f;
1131     data.window_state = 0;
1132     data.focus_policy = 0;
1133     data.context_menu_policy = Qt::DefaultContextMenu;
1134     data.window_modality = Qt::NonModal;
1135
1136     data.sizehint_forced = 0;
1137     data.is_closing = 0;
1138     data.in_show = 0;
1139     data.in_set_window_state = 0;
1140     data.in_destructor = false;
1141
1142     // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1143     if (f & Qt::MSWindowsOwnDC)
1144         q->setAttribute(Qt::WA_NativeWindow);
1145
1146 //#ifdef Q_WS_MAC
1147 //    q->setAttribute(Qt::WA_NativeWindow);
1148 //#endif
1149
1150     q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1151     adjustQuitOnCloseAttribute();
1152
1153     q->setAttribute(Qt::WA_WState_Hidden);
1154
1155     //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1156     data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1157     focus_next = focus_prev = q;
1158
1159     if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1160         q->create();
1161     else if (parentWidget)
1162         q->setParent(parentWidget, data.window_flags);
1163     else {
1164         adjustFlags(data.window_flags, q);
1165         resolveLayoutDirection();
1166         // opaque system background?
1167         const QBrush &background = q->palette().brush(QPalette::Window);
1168         setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1169     }
1170     data.fnt = QFont(data.fnt, q);
1171 #if defined(Q_WS_X11)
1172     data.fnt.x11SetScreen(xinfo.screen());
1173 #endif // Q_WS_X11
1174
1175     q->setAttribute(Qt::WA_PendingMoveEvent);
1176     q->setAttribute(Qt::WA_PendingResizeEvent);
1177
1178     if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1179         QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1180
1181     if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1182         q->create();
1183
1184     QEvent e(QEvent::Create);
1185     QApplication::sendEvent(q, &e);
1186     QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1187
1188     extraPaintEngine = 0;
1189
1190 #ifdef Q_WS_MAC
1191     // If we add a child to the unified toolbar, we have to redirect the painting.
1192     if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1193         if (parentWidget->d_func()->unifiedSurface) {
1194             QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1195             parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1196         }
1197     }
1198 #endif // Q_WS_MAC
1199 }
1200
1201
1202
1203 void QWidgetPrivate::createRecursively()
1204 {
1205     Q_Q(QWidget);
1206     q->create(0, true, true);
1207     for (int i = 0; i < children.size(); ++i) {
1208         QWidget *child = qobject_cast<QWidget *>(children.at(i));
1209         if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1210             child->d_func()->createRecursively();
1211     }
1212 }
1213
1214
1215
1216
1217 /*!
1218     Creates a new widget window if \a window is 0, otherwise sets the
1219     widget's window to \a window.
1220
1221     Initializes the window (sets the geometry etc.) if \a
1222     initializeWindow is true. If \a initializeWindow is false, no
1223     initialization is performed. This parameter only makes sense if \a
1224     window is a valid window.
1225
1226     Destroys the old window if \a destroyOldWindow is true. If \a
1227     destroyOldWindow is false, you are responsible for destroying the
1228     window yourself (using platform native code).
1229
1230     The QWidget constructor calls create(0,true,true) to create a
1231     window for this widget.
1232 */
1233
1234 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1235 {
1236     Q_D(QWidget);
1237     if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1238         return;
1239
1240     if (d->data.in_destructor)
1241         return;
1242
1243     Qt::WindowType type = windowType();
1244     Qt::WindowFlags &flags = data->window_flags;
1245
1246     if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1247         type = Qt::Window;
1248         flags |= Qt::Window;
1249     }
1250
1251     if (QWidget *parent = parentWidget()) {
1252         if (type & Qt::Window) {
1253             if (!parent->testAttribute(Qt::WA_WState_Created))
1254                 parent->createWinId();
1255         } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1256                    && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1257             // We're about to create a native child widget that doesn't have a native parent;
1258             // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1259             // attribute is set.
1260             d->createWinId(window);
1261             // Nothing more to do.
1262             Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1263             Q_ASSERT(internalWinId());
1264             return;
1265         }
1266     }
1267
1268
1269     static int paintOnScreenEnv = -1;
1270     if (paintOnScreenEnv == -1)
1271         paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1272     if (paintOnScreenEnv == 1)
1273         setAttribute(Qt::WA_PaintOnScreen);
1274
1275     if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1276         setAttribute(Qt::WA_NativeWindow);
1277
1278 #ifdef ALIEN_DEBUG
1279     qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1280              << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1281 #endif
1282
1283 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1284     // Unregister the dropsite (if already registered) before we
1285     // re-create the widget with a native window.
1286     if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1287             && d->extra && d->extra->dropTarget) {
1288         d->registerDropSite(false);
1289     }
1290 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1291
1292     d->updateIsOpaque();
1293
1294     setAttribute(Qt::WA_WState_Created);                        // set created flag
1295     d->create_sys(window, initializeWindow, destroyOldWindow);
1296
1297     // a real toplevel window needs a backing store
1298     if (isWindow() && windowType() != Qt::Desktop) {
1299         d->topData()->backingStoreTracker.destroy();
1300         if (hasBackingStoreSupport())
1301             d->topData()->backingStoreTracker.create(this);
1302     }
1303
1304     d->setModal_sys();
1305
1306     if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1307         setAttribute(Qt::WA_DropSiteRegistered, true);
1308
1309 #ifdef QT_EVAL
1310     extern void qt_eval_init_widget(QWidget *w);
1311     qt_eval_init_widget(this);
1312 #endif
1313
1314     // need to force the resting of the icon after changing parents
1315     if (testAttribute(Qt::WA_SetWindowIcon))
1316         d->setWindowIcon_sys();
1317
1318     if (isWindow() && !d->topData()->iconText.isEmpty())
1319         d->setWindowIconText_helper(d->topData()->iconText);
1320     if (isWindow() && !d->topData()->caption.isEmpty())
1321         d->setWindowTitle_helper(d->topData()->caption);
1322     if (windowType() != Qt::Desktop) {
1323         d->updateSystemBackground();
1324
1325         if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1326             d->setWindowIcon_sys();
1327     }
1328
1329     // Frame strut update needed in cases where there are native widgets such as QGLWidget,
1330     // as those force native window creation on their ancestors before they are shown.
1331     // If the strut is not updated, any subsequent move of the top level window before show
1332     // will cause window frame to be ignored when positioning the window.
1333     // Note that this only helps on platforms that handle window creation synchronously.
1334     d->updateFrameStrut();
1335 }
1336
1337 /*!
1338     Destroys the widget.
1339
1340     All this widget's children are deleted first. The application
1341     exits if this widget is the main widget.
1342 */
1343
1344 QWidget::~QWidget()
1345 {
1346     Q_D(QWidget);
1347     d->data.in_destructor = true;
1348
1349 #if defined (QT_CHECK_STATE)
1350     if (paintingActive())
1351         qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1352 #endif
1353
1354 #ifndef QT_NO_GESTURES
1355     foreach (Qt::GestureType type, d->gestureContext.keys())
1356         ungrabGesture(type);
1357 #endif
1358
1359     // force acceptDrops false before winId is destroyed.
1360     d->registerDropSite(false);
1361
1362 #ifndef QT_NO_ACTION
1363     // remove all actions from this widget
1364     for (int i = 0; i < d->actions.size(); ++i) {
1365         QActionPrivate *apriv = d->actions.at(i)->d_func();
1366         apriv->widgets.removeAll(this);
1367     }
1368     d->actions.clear();
1369 #endif
1370
1371 #ifndef QT_NO_SHORTCUT
1372     // Remove all shortcuts grabbed by this
1373     // widget, unless application is closing
1374     if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1375         qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1376 #endif
1377
1378     // delete layout while we still are a valid widget
1379     delete d->layout;
1380     d->layout = 0;
1381     // Remove myself from focus list
1382
1383     Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1384     Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1385
1386     if (d->focus_next != this) {
1387         d->focus_next->d_func()->focus_prev = d->focus_prev;
1388         d->focus_prev->d_func()->focus_next = d->focus_next;
1389         d->focus_next = d->focus_prev = 0;
1390     }
1391
1392
1393     QT_TRY {
1394         clearFocus();
1395     } QT_CATCH(...) {
1396         // swallow this problem because we are in a destructor
1397     }
1398
1399     d->setDirtyOpaqueRegion();
1400
1401     if (isWindow() && isVisible() && internalWinId()) {
1402         QT_TRY {
1403             d->close_helper(QWidgetPrivate::CloseNoEvent);
1404         } QT_CATCH(...) {
1405             // if we're out of memory, at least hide the window.
1406             QT_TRY {
1407                 hide();
1408             } QT_CATCH(...) {
1409                 // and if that also doesn't work, then give up
1410             }
1411         }
1412     }
1413
1414 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1415     else if (!internalWinId() && isVisible()) {
1416         qApp->d_func()->sendSyntheticEnterLeave(this);
1417     }
1418 #endif
1419     else if (isVisible()) {
1420         qApp->d_func()->sendSyntheticEnterLeave(this);
1421     }
1422
1423     if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1424         bs->removeDirtyWidget(this);
1425         if (testAttribute(Qt::WA_StaticContents))
1426             bs->removeStaticWidget(this);
1427     }
1428
1429     delete d->needsFlush;
1430     d->needsFlush = 0;
1431
1432     // The next 20 lines are duplicated from QObject, but required here
1433     // since QWidget deletes is children itself
1434     bool blocked = d->blockSig;
1435     d->blockSig = 0; // unblock signals so we always emit destroyed()
1436
1437     if (d->isSignalConnected(0)) {
1438         QT_TRY {
1439             emit destroyed(this);
1440         } QT_CATCH(...) {
1441             // all the signal/slots connections are still in place - if we don't
1442             // quit now, we will crash pretty soon.
1443             qWarning("Detected an unexpected exception in ~QWidget while emitting destroyed().");
1444             QT_RETHROW;
1445         }
1446     }
1447
1448     if (d->declarativeData) {
1449         QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1450         d->declarativeData = 0;                 // don't activate again in ~QObject
1451     }
1452
1453     d->blockSig = blocked;
1454
1455 #ifdef Q_WS_MAC
1456     // QCocoaView holds a pointer back to this widget. Clear it now
1457     // to make sure it's not followed later on. The lifetime of the
1458     // QCocoaView might exceed the lifetime of this widget in cases
1459     // where Cocoa itself holds references to it.
1460     extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1461     qt_mac_clearCocoaViewQWidgetPointers(this);
1462 #endif
1463
1464     if (!d->children.isEmpty())
1465         d->deleteChildren();
1466
1467     QApplication::removePostedEvents(this);
1468
1469     QT_TRY {
1470         destroy();                                        // platform-dependent cleanup
1471     } QT_CATCH(...) {
1472         // if this fails we can't do anything about it but at least we are not allowed to throw.
1473     }
1474     --QWidgetPrivate::instanceCounter;
1475
1476     if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1477         QWidgetPrivate::allWidgets->remove(this);
1478
1479     QT_TRY {
1480         QEvent e(QEvent::Destroy);
1481         QCoreApplication::sendEvent(this, &e);
1482     } QT_CATCH(const std::exception&) {
1483         // if this fails we can't do anything about it but at least we are not allowed to throw.
1484     }
1485 }
1486
1487 int QWidgetPrivate::instanceCounter = 0;  // Current number of widget instances
1488 int QWidgetPrivate::maxInstances = 0;     // Maximum number of widget instances
1489
1490 void QWidgetPrivate::setWinId(WId id)                // set widget identifier
1491 {
1492     Q_Q(QWidget);
1493     // the user might create a widget with Qt::Desktop window
1494     // attribute (or create another QDesktopWidget instance), which
1495     // will have the same windowid (the root window id) as the
1496     // qt_desktopWidget. We should not add the second desktop widget
1497     // to the mapper.
1498     bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1499     if (mapper && data.winid && !userDesktopWidget) {
1500         mapper->remove(data.winid);
1501     }
1502
1503     const WId oldWinId = data.winid;
1504
1505     data.winid = id;
1506 #if defined(Q_WS_X11)
1507     hd = id; // X11: hd == ident
1508 #endif
1509     if (mapper && id && !userDesktopWidget) {
1510         mapper->insert(data.winid, q);
1511     }
1512
1513     if(oldWinId != id) {
1514         QEvent e(QEvent::WinIdChange);
1515         QCoreApplication::sendEvent(q, &e);
1516     }
1517 }
1518
1519 void QWidgetPrivate::createTLExtra()
1520 {
1521     if (!extra)
1522         createExtra();
1523     if (!extra->topextra) {
1524         QTLWExtra* x = extra->topextra = new QTLWExtra;
1525         x->icon = 0;
1526         x->backingStore = 0;
1527         x->sharedPainter = 0;
1528         x->incw = x->inch = 0;
1529         x->basew = x->baseh = 0;
1530         x->frameStrut.setCoords(0, 0, 0, 0);
1531         x->normalGeometry = QRect(0,0,-1,-1);
1532         x->savedFlags = 0;
1533         x->opacity = 255;
1534         x->posIncludesFrame = 0;
1535         x->sizeAdjusted = false;
1536         x->inTopLevelResize = false;
1537         x->inRepaint = false;
1538         x->embedded = 0;
1539 #ifdef Q_WS_MAC
1540         x->wasMaximized = false;
1541 #endif // Q_WS_MAC
1542         createTLSysExtra();
1543 #ifdef QWIDGET_EXTRA_DEBUG
1544         static int count = 0;
1545         qDebug() << "tlextra" << ++count;
1546 #endif
1547     }
1548 }
1549
1550 /*!
1551   \internal
1552   Creates the widget extra data.
1553 */
1554
1555 void QWidgetPrivate::createExtra()
1556 {
1557     if (!extra) {                                // if not exists
1558         extra = new QWExtra;
1559         extra->glContext = 0;
1560         extra->topextra = 0;
1561 #ifndef QT_NO_GRAPHICSVIEW
1562         extra->proxyWidget = 0;
1563 #endif
1564 #ifndef QT_NO_CURSOR
1565         extra->curs = 0;
1566 #endif
1567         extra->minw = 0;
1568         extra->minh = 0;
1569         extra->maxw = QWIDGETSIZE_MAX;
1570         extra->maxh = QWIDGETSIZE_MAX;
1571         extra->customDpiX = 0;
1572         extra->customDpiY = 0;
1573         extra->explicitMinSize = 0;
1574         extra->explicitMaxSize = 0;
1575         extra->autoFillBackground = 0;
1576         extra->nativeChildrenForced = 0;
1577         extra->inRenderWithPainter = 0;
1578         extra->hasMask = 0;
1579         createSysExtra();
1580 #ifdef QWIDGET_EXTRA_DEBUG
1581         static int count = 0;
1582         qDebug() << "extra" << ++count;
1583 #endif
1584     }
1585 }
1586
1587
1588 /*!
1589   \internal
1590   Deletes the widget extra data.
1591 */
1592
1593 void QWidgetPrivate::deleteExtra()
1594 {
1595     if (extra) {                                // if exists
1596 #ifndef QT_NO_CURSOR
1597         delete extra->curs;
1598 #endif
1599         deleteSysExtra();
1600 #ifndef QT_NO_STYLE_STYLESHEET
1601         // dereference the stylesheet style
1602         if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1603             proxy->deref();
1604 #endif
1605         if (extra->topextra) {
1606             deleteTLSysExtra();
1607             // extra->topextra->backingStore destroyed in QWidgetPrivate::deleteTLSysExtra()
1608             delete extra->topextra->icon;
1609             delete extra->topextra;
1610         }
1611         delete extra;
1612         // extra->xic destroyed in QWidget::destroy()
1613         extra = 0;
1614     }
1615 }
1616
1617 /*
1618   Returns true if there are widgets above this which overlap with
1619   \a rect, which is in parent's coordinate system (same as crect).
1620 */
1621
1622 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1623 {
1624     Q_Q(const QWidget);
1625
1626     const QWidget *w = q;
1627     QRect r = rect;
1628     while (w) {
1629         if (w->isWindow())
1630             return false;
1631         QWidgetPrivate *pd = w->parentWidget()->d_func();
1632         bool above = false;
1633         for (int i = 0; i < pd->children.size(); ++i) {
1634             QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1635             if (!sibling || !sibling->isVisible() || sibling->isWindow())
1636                 continue;
1637             if (!above) {
1638                 above = (sibling == w);
1639                 continue;
1640             }
1641
1642             if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1643                 const QWExtra *siblingExtra = sibling->d_func()->extra;
1644                 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1645                     && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1646                     continue;
1647                 }
1648                 return true;
1649             }
1650         }
1651         w = w->parentWidget();
1652         r.translate(pd->data.crect.topLeft());
1653     }
1654     return false;
1655 }
1656
1657 void QWidgetPrivate::syncBackingStore()
1658 {
1659     if (paintOnScreen()) {
1660         repaint_sys(dirty);
1661         dirty = QRegion();
1662     } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1663         bs->sync();
1664     }
1665 }
1666
1667 void QWidgetPrivate::syncBackingStore(const QRegion &region)
1668 {
1669     if (paintOnScreen())
1670         repaint_sys(region);
1671     else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1672         bs->sync(q_func(), region);
1673     }
1674 }
1675
1676 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1677 {
1678     Q_Q(QWidget);
1679
1680     if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1681         return; // nothing we can do
1682
1683     if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1684         return; // nothing to do
1685
1686     q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1687     if (enable)
1688         q->update();
1689
1690     Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1691     for (int i = 0; i < children.size(); ++i) {
1692         QWidget *w = qobject_cast<QWidget *>(children.at(i));
1693         if (w && !w->isWindow() && !w->testAttribute(attribute))
1694             w->d_func()->setUpdatesEnabled_helper(enable);
1695     }
1696 }
1697
1698 /*!
1699     \internal
1700
1701     Propagate this widget's palette to all children, except style sheet
1702     widgets, and windows that don't enable window propagation (palettes don't
1703     normally propagate to windows).
1704 */
1705 void QWidgetPrivate::propagatePaletteChange()
1706 {
1707     Q_Q(QWidget);
1708     // Propagate a new inherited mask to all children.
1709 #ifndef QT_NO_GRAPHICSVIEW
1710     if (!q->parentWidget() && extra && extra->proxyWidget) {
1711         QGraphicsProxyWidget *p = extra->proxyWidget;
1712         inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1713     } else
1714 #endif //QT_NO_GRAPHICSVIEW
1715         if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1716         inheritedPaletteResolveMask = 0;
1717     }
1718     int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1719
1720     QEvent pc(QEvent::PaletteChange);
1721     QApplication::sendEvent(q, &pc);
1722     for (int i = 0; i < children.size(); ++i) {
1723         QWidget *w = qobject_cast<QWidget*>(children.at(i));
1724         if (w && !w->testAttribute(Qt::WA_StyleSheet)
1725             && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1726             QWidgetPrivate *wd = w->d_func();
1727             wd->inheritedPaletteResolveMask = mask;
1728             wd->resolvePalette();
1729         }
1730     }
1731 }
1732
1733 /*
1734   Returns the widget's clipping rectangle.
1735 */
1736 QRect QWidgetPrivate::clipRect() const
1737 {
1738     Q_Q(const QWidget);
1739     const QWidget * w = q;
1740     if (!w->isVisible())
1741         return QRect();
1742     QRect r = effectiveRectFor(q->rect());
1743     int ox = 0;
1744     int oy = 0;
1745     while (w
1746             && w->isVisible()
1747             && !w->isWindow()
1748             && w->parentWidget()) {
1749         ox -= w->x();
1750         oy -= w->y();
1751         w = w->parentWidget();
1752         r &= QRect(ox, oy, w->width(), w->height());
1753     }
1754     return r;
1755 }
1756
1757 /*
1758   Returns the widget's clipping region (without siblings).
1759 */
1760 QRegion QWidgetPrivate::clipRegion() const
1761 {
1762     Q_Q(const QWidget);
1763     if (!q->isVisible())
1764         return QRegion();
1765     QRegion r(q->rect());
1766     const QWidget * w = q;
1767     const QWidget *ignoreUpTo;
1768     int ox = 0;
1769     int oy = 0;
1770     while (w
1771            && w->isVisible()
1772            && !w->isWindow()
1773            && w->parentWidget()) {
1774         ox -= w->x();
1775         oy -= w->y();
1776         ignoreUpTo = w;
1777         w = w->parentWidget();
1778         r &= QRegion(ox, oy, w->width(), w->height());
1779
1780         int i = 0;
1781         while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1782             ;
1783         for ( ; i < w->d_func()->children.size(); ++i) {
1784             if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1785                 if(sibling->isVisible() && !sibling->isWindow()) {
1786                     QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1787                                       sibling->width(), sibling->height());
1788                     if (qRectIntersects(siblingRect, q->rect()))
1789                         r -= QRegion(siblingRect);
1790                 }
1791             }
1792         }
1793     }
1794     return r;
1795 }
1796
1797 void QWidgetPrivate::setSystemClip(QPaintDevice *paintDevice, const QRegion &region)
1798 {
1799 // Transform the system clip region from device-independent pixels to device pixels
1800 // Qt 5.0.0: This is a Mac-only code path for now, can be made cross-platform once
1801 // it has been tested.
1802     QPaintEngine *paintEngine = paintDevice->paintEngine();
1803 #ifdef Q_OS_MAC
1804     const qreal devicePixelRatio = (paintDevice->physicalDpiX() == 0 || paintDevice->logicalDpiX() == 0) ?
1805                                     1.0 : (paintDevice->physicalDpiX() / paintDevice->logicalDpiX());
1806     QTransform scaleTransform;
1807     scaleTransform.scale(devicePixelRatio, devicePixelRatio);
1808     paintEngine->d_func()->systemClip = scaleTransform.map(region);
1809 #else
1810     paintEngine->d_func()->systemClip = region;
1811 #endif
1812 }
1813
1814 #ifndef QT_NO_GRAPHICSEFFECT
1815 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1816 {
1817     Q_Q(QWidget);
1818     QWidget *w = q;
1819     do {
1820         if (w->graphicsEffect()) {
1821             QWidgetEffectSourcePrivate *sourced =
1822                 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1823             if (!sourced->updateDueToGraphicsEffect)
1824                 w->graphicsEffect()->source()->d_func()->invalidateCache();
1825         }
1826         w = w->parentWidget();
1827     } while (w);
1828 }
1829 #endif //QT_NO_GRAPHICSEFFECT
1830
1831 void QWidgetPrivate::setDirtyOpaqueRegion()
1832 {
1833     Q_Q(QWidget);
1834
1835     dirtyOpaqueChildren = true;
1836
1837 #ifndef QT_NO_GRAPHICSEFFECT
1838     invalidateGraphicsEffectsRecursively();
1839 #endif //QT_NO_GRAPHICSEFFECT
1840
1841     if (q->isWindow())
1842         return;
1843
1844     QWidget *parent = q->parentWidget();
1845     if (!parent)
1846         return;
1847
1848     // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1849     QWidgetPrivate *pd = parent->d_func();
1850     if (!pd->dirtyOpaqueChildren)
1851         pd->setDirtyOpaqueRegion();
1852 }
1853
1854 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1855 {
1856     if (!dirtyOpaqueChildren)
1857         return opaqueChildren;
1858
1859     QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1860     that->opaqueChildren = QRegion();
1861
1862     for (int i = 0; i < children.size(); ++i) {
1863         QWidget *child = qobject_cast<QWidget *>(children.at(i));
1864         if (!child || !child->isVisible() || child->isWindow())
1865             continue;
1866
1867         const QPoint offset = child->geometry().topLeft();
1868         QWidgetPrivate *childd = child->d_func();
1869         QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1870         if (childd->extra && childd->extra->hasMask)
1871             r &= childd->extra->mask;
1872         if (r.isEmpty())
1873             continue;
1874         r.translate(offset);
1875         that->opaqueChildren += r;
1876     }
1877
1878     that->opaqueChildren &= q_func()->rect();
1879     that->dirtyOpaqueChildren = false;
1880
1881     return that->opaqueChildren;
1882 }
1883
1884 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1885 {
1886     if (children.isEmpty() || clipRect.isEmpty())
1887         return;
1888
1889     const QRegion &r = getOpaqueChildren();
1890     if (!r.isEmpty())
1891         source -= (r & clipRect);
1892 }
1893
1894 //subtract any relatives that are higher up than me --- this is too expensive !!!
1895 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1896                                             bool alsoNonOpaque) const
1897 {
1898     Q_Q(const QWidget);
1899     static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1900     if (disableSubtractOpaqueSiblings || q->isWindow())
1901         return;
1902
1903 #ifdef Q_WS_MAC
1904     if (q->d_func()->isInUnifiedToolbar)
1905         return;
1906 #endif // Q_WS_MAC
1907
1908     QRect clipBoundingRect;
1909     bool dirtyClipBoundingRect = true;
1910
1911     QRegion parentClip;
1912     bool dirtyParentClip = true;
1913
1914     QPoint parentOffset = data.crect.topLeft();
1915
1916     const QWidget *w = q;
1917
1918     while (w) {
1919         if (w->isWindow())
1920             break;
1921         QWidgetPrivate *pd = w->parentWidget()->d_func();
1922         const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1923         const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1924         for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1925             QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1926             if (!sibling || !sibling->isVisible() || sibling->isWindow())
1927                 continue;
1928
1929             const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1930             if (!qRectIntersects(siblingGeometry, widgetGeometry))
1931                 continue;
1932
1933             if (dirtyClipBoundingRect) {
1934                 clipBoundingRect = sourceRegion.boundingRect();
1935                 dirtyClipBoundingRect = false;
1936             }
1937
1938             if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1939                 continue;
1940
1941             if (dirtyParentClip) {
1942                 parentClip = sourceRegion.translated(parentOffset);
1943                 dirtyParentClip = false;
1944             }
1945
1946             const QPoint siblingPos(sibling->data->crect.topLeft());
1947             const QRect siblingClipRect(sibling->d_func()->clipRect());
1948             QRegion siblingDirty(parentClip);
1949             siblingDirty &= (siblingClipRect.translated(siblingPos));
1950             const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
1951                                  && !sibling->d_func()->graphicsEffect;
1952             if (hasMask)
1953                 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
1954             if (siblingDirty.isEmpty())
1955                 continue;
1956
1957             if (sibling->d_func()->isOpaque || alsoNonOpaque) {
1958                 if (hasMask) {
1959                     siblingDirty.translate(-parentOffset);
1960                     sourceRegion -= siblingDirty;
1961                 } else {
1962                     sourceRegion -= siblingGeometry.translated(-parentOffset);
1963                 }
1964             } else {
1965                 if (hasDirtySiblingsAbove)
1966                     *hasDirtySiblingsAbove = true;
1967                 if (sibling->d_func()->children.isEmpty())
1968                     continue;
1969                 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
1970                 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
1971                 sourceRegion -= opaqueSiblingChildren;
1972             }
1973             if (sourceRegion.isEmpty())
1974                 return;
1975
1976             dirtyClipBoundingRect = true;
1977             dirtyParentClip = true;
1978         }
1979
1980         w = w->parentWidget();
1981         parentOffset += pd->data.crect.topLeft();
1982         dirtyParentClip = true;
1983     }
1984 }
1985
1986 void QWidgetPrivate::clipToEffectiveMask(QRegion &region) const
1987 {
1988     Q_Q(const QWidget);
1989
1990     const QWidget *w = q;
1991     QPoint offset;
1992
1993 #ifndef QT_NO_GRAPHICSEFFECT
1994     if (graphicsEffect) {
1995         w = q->parentWidget();
1996         offset -= data.crect.topLeft();
1997     }
1998 #endif //QT_NO_GRAPHICSEFFECT
1999
2000     while (w) {
2001         const QWidgetPrivate *wd = w->d_func();
2002         if (wd->extra && wd->extra->hasMask)
2003             region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
2004         if (w->isWindow())
2005             return;
2006         offset -= wd->data.crect.topLeft();
2007         w = w->parentWidget();
2008     }
2009 }
2010
2011 bool QWidgetPrivate::paintOnScreen() const
2012 {
2013 #if defined(QT_NO_BACKINGSTORE)
2014     return true;
2015 #else
2016     Q_Q(const QWidget);
2017     if (q->testAttribute(Qt::WA_PaintOnScreen)
2018             || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2019         return true;
2020     }
2021
2022     return !qt_enable_backingstore;
2023 #endif
2024 }
2025
2026 void QWidgetPrivate::updateIsOpaque()
2027 {
2028     // hw: todo: only needed if opacity actually changed
2029     setDirtyOpaqueRegion();
2030
2031 #ifndef QT_NO_GRAPHICSEFFECT
2032     if (graphicsEffect) {
2033         // ### We should probably add QGraphicsEffect::isOpaque at some point.
2034         setOpaque(false);
2035         return;
2036     }
2037 #endif //QT_NO_GRAPHICSEFFECT
2038
2039     Q_Q(QWidget);
2040 #ifdef Q_WS_X11
2041     if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2042         setOpaque(false);
2043         return;
2044     }
2045 #endif
2046
2047     if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2048         setOpaque(true);
2049         return;
2050     }
2051
2052     const QPalette &pal = q->palette();
2053
2054     if (q->autoFillBackground()) {
2055         const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2056         if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2057             setOpaque(true);
2058             return;
2059         }
2060     }
2061
2062     if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2063         const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2064         if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2065             setOpaque(true);
2066             return;
2067         }
2068     }
2069     setOpaque(false);
2070 }
2071
2072 void QWidgetPrivate::setOpaque(bool opaque)
2073 {
2074     if (isOpaque != opaque) {
2075         isOpaque = opaque;
2076         updateIsTranslucent();
2077     }
2078 }
2079
2080 void QWidgetPrivate::updateIsTranslucent()
2081 {
2082     Q_Q(QWidget);
2083     if (QWindow *window = q->windowHandle())
2084         window->setOpacity(isOpaque ? qreal(1.0) : qreal(0.0));
2085 }
2086
2087 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2088 {
2089     Q_ASSERT(painter);
2090
2091     if (brush.style() == Qt::TexturePattern) {
2092 #ifdef Q_WS_MAC
2093         // Optimize pattern filling on mac by using HITheme directly
2094         // when filling with the standard widget background.
2095         // Defined in qmacstyle_mac.cpp
2096         extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2097         qt_mac_fill_background(painter, rgn, brush);
2098 #else
2099         {
2100             const QRect rect(rgn.boundingRect());
2101             painter->setClipRegion(rgn);
2102             painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2103         }
2104 #endif // Q_WS_MAC
2105
2106     } else if (brush.gradient()
2107                && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2108         painter->save();
2109         painter->setClipRegion(rgn);
2110         painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2111         painter->restore();
2112     } else {
2113         const QVector<QRect> &rects = rgn.rects();
2114         for (int i = 0; i < rects.size(); ++i)
2115             painter->fillRect(rects.at(i), brush);
2116     }
2117 }
2118
2119 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2120 {
2121     Q_Q(const QWidget);
2122
2123 #ifndef QT_NO_SCROLLAREA
2124     bool resetBrushOrigin = false;
2125     QPointF oldBrushOrigin;
2126     //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2127     QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2128     if (scrollArea && scrollArea->viewport() == q) {
2129         QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2130         QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2131         oldBrushOrigin = painter->brushOrigin();
2132         resetBrushOrigin = true;
2133         painter->setBrushOrigin(-priv->contentsOffset());
2134
2135     }
2136 #endif // QT_NO_SCROLLAREA
2137
2138     const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2139
2140     if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2141         const QBrush bg = q->palette().brush(QPalette::Window);
2142         if (!(flags & DontSetCompositionMode)) {
2143             //copy alpha straight in
2144             QPainter::CompositionMode oldMode = painter->compositionMode();
2145             painter->setCompositionMode(QPainter::CompositionMode_Source);
2146             fillRegion(painter, rgn, bg);
2147             painter->setCompositionMode(oldMode);
2148         } else {
2149             fillRegion(painter, rgn, bg);
2150         }
2151     }
2152
2153     if (q->autoFillBackground())
2154         fillRegion(painter, rgn, autoFillBrush);
2155
2156     if (q->testAttribute(Qt::WA_StyledBackground)) {
2157         painter->setClipRegion(rgn);
2158         QStyleOption opt;
2159         opt.initFrom(q);
2160         q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2161     }
2162
2163 #ifndef QT_NO_SCROLLAREA
2164     if (resetBrushOrigin)
2165         painter->setBrushOrigin(oldBrushOrigin);
2166 #endif // QT_NO_SCROLLAREA
2167 }
2168
2169 /*
2170   \internal
2171   This function is called when a widget is hidden or destroyed.
2172   It resets some application global pointers that should only refer active,
2173   visible widgets.
2174 */
2175
2176 #ifdef Q_WS_MAC
2177     extern QPointer<QWidget> qt_button_down;
2178 #else
2179     extern QWidget *qt_button_down;
2180 #endif
2181
2182 void QWidgetPrivate::deactivateWidgetCleanup()
2183 {
2184     Q_Q(QWidget);
2185     // If this was the active application window, reset it
2186     if (QApplication::activeWindow() == q)
2187         QApplication::setActiveWindow(0);
2188     // If the is the active mouse press widget, reset it
2189     if (q == qt_button_down)
2190         qt_button_down = 0;
2191 }
2192
2193
2194 /*!
2195     Returns a pointer to the widget with window identifer/handle \a
2196     id.
2197
2198     The window identifier type depends on the underlying window
2199     system, see \c qwindowdefs.h for the actual definition. If there
2200     is no widget with this identifier, 0 is returned.
2201 */
2202
2203 QWidget *QWidget::find(WId id)
2204 {
2205     return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2206 }
2207
2208
2209
2210 /*!
2211     \fn WId QWidget::internalWinId() const
2212     \internal
2213     Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2214
2215 */
2216
2217 /*!
2218     \fn WId QWidget::winId() const
2219
2220     Returns the window system identifier of the widget.
2221
2222     Portable in principle, but if you use it you are probably about to
2223     do something non-portable. Be careful.
2224
2225     If a widget is non-native (alien) and winId() is invoked on it, that widget
2226     will be provided a native handle.
2227
2228     On Mac OS X, the type returned depends on which framework Qt was linked
2229     against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2230     is using Cocoa, {WId} is a pointer to an NSView.
2231
2232     This value may change at run-time. An event with type QEvent::WinIdChange
2233     will be sent to the widget following a change in window system identifier.
2234
2235     \sa find()
2236 */
2237 WId QWidget::winId() const
2238 {
2239     if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2240 #ifdef ALIEN_DEBUG
2241         qDebug() << "QWidget::winId: creating native window for" << this;
2242 #endif
2243         QWidget *that = const_cast<QWidget*>(this);
2244         that->setAttribute(Qt::WA_NativeWindow);
2245         that->d_func()->createWinId();
2246         return that->data->winid;
2247     }
2248     return data->winid;
2249 }
2250
2251
2252 void QWidgetPrivate::createWinId(WId winid)
2253 {
2254     Q_Q(QWidget);
2255
2256 #ifdef ALIEN_DEBUG
2257     qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2258 #endif
2259     const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2260     if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2261         if (!q->isWindow()) {
2262             QWidget *parent = q->parentWidget();
2263             QWidgetPrivate *pd = parent->d_func();
2264             if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2265                 parent->setAttribute(Qt::WA_NativeWindow);
2266             if (!parent->internalWinId()) {
2267                 pd->createWinId();
2268             }
2269
2270             for (int i = 0; i < pd->children.size(); ++i) {
2271                 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2272                 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2273                                             || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2274                     if (w!=q) {
2275                         w->create();
2276                     } else {
2277                         w->create(winid);
2278                         // if the window has already been created, we
2279                         // need to raise it to its proper stacking position
2280                         if (winid)
2281                             w->raise();
2282                     }
2283                 }
2284             }
2285         } else {
2286             q->create();
2287         }
2288     }
2289 }
2290
2291
2292 /*!
2293 \internal
2294 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2295
2296 */
2297
2298 void QWidget::createWinId()
2299 {
2300     Q_D(QWidget);
2301 #ifdef ALIEN_DEBUG
2302     qDebug()  << "QWidget::createWinId" << this;
2303 #endif
2304 //    qWarning("QWidget::createWinId is obsolete, please fix your code.");
2305     d->createWinId();
2306 }
2307
2308 /*!
2309     \since 4.4
2310
2311     Returns the effective window system identifier of the widget, i.e. the
2312     native parent's window system identifier.
2313
2314     If the widget is native, this function returns the native widget ID.
2315     Otherwise, the window ID of the first native parent widget, i.e., the
2316     top-level widget that contains this widget, is returned.
2317
2318     \note We recommend that you do not store this value as it is likely to
2319     change at run-time.
2320
2321     \sa nativeParentWidget()
2322 */
2323 WId QWidget::effectiveWinId() const
2324 {
2325     const WId id = internalWinId();
2326     if (id || !testAttribute(Qt::WA_WState_Created))
2327         return id;
2328     if (const QWidget *realParent = nativeParentWidget())
2329         return realParent->internalWinId();
2330     return 0;
2331 }
2332
2333 #ifndef QT_NO_STYLE_STYLESHEET
2334
2335 /*!
2336     \property QWidget::styleSheet
2337     \brief the widget's style sheet
2338     \since 4.2
2339
2340     The style sheet contains a textual description of customizations to the
2341     widget's style, as described in the \l{Qt Style Sheets} document.
2342
2343     Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2344
2345     \warning Qt style sheets are currently not supported for custom QStyle
2346     subclasses. We plan to address this in some future release.
2347
2348     \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2349 */
2350 QString QWidget::styleSheet() const
2351 {
2352     Q_D(const QWidget);
2353     if (!d->extra)
2354         return QString();
2355     return d->extra->styleSheet;
2356 }
2357
2358 void QWidget::setStyleSheet(const QString& styleSheet)
2359 {
2360     Q_D(QWidget);
2361     d->createExtra();
2362
2363     QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2364     d->extra->styleSheet = styleSheet;
2365     if (styleSheet.isEmpty()) { // stylesheet removed
2366         if (!proxy)
2367             return;
2368
2369         d->inheritStyle();
2370         return;
2371     }
2372
2373     if (proxy) { // style sheet update
2374         proxy->repolish(this);
2375         return;
2376     }
2377
2378     if (testAttribute(Qt::WA_SetStyle)) {
2379         d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2380     } else {
2381         d->setStyle_helper(new QStyleSheetStyle(0), true);
2382     }
2383 }
2384
2385 #endif // QT_NO_STYLE_STYLESHEET
2386
2387 /*!
2388     \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2389 */
2390
2391 QStyle *QWidget::style() const
2392 {
2393     Q_D(const QWidget);
2394
2395     if (d->extra && d->extra->style)
2396         return d->extra->style;
2397     return QApplication::style();
2398 }
2399
2400 /*!
2401     Sets the widget's GUI style to \a style. The ownership of the style
2402     object is not transferred.
2403
2404     If no style is set, the widget uses the application's style,
2405     QApplication::style() instead.
2406
2407     Setting a widget's style has no effect on existing or future child
2408     widgets.
2409
2410     \warning This function is particularly useful for demonstration
2411     purposes, where you want to show Qt's styling capabilities. Real
2412     applications should avoid it and use one consistent GUI style
2413     instead.
2414
2415     \warning Qt style sheets are currently not supported for custom QStyle
2416     subclasses. We plan to address this in some future release.
2417
2418     \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2419 */
2420
2421 void QWidget::setStyle(QStyle *style)
2422 {
2423     Q_D(QWidget);
2424     setAttribute(Qt::WA_SetStyle, style != 0);
2425     d->createExtra();
2426 #ifndef QT_NO_STYLE_STYLESHEET
2427     if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2428         //if for some reason someone try to set a QStyleSheetStyle, ref it
2429         //(this may happen for exemple in QButtonDialogBox which propagates its style)
2430         proxy->ref();
2431         d->setStyle_helper(style, false);
2432     } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2433         // if we have an application stylesheet or have a proxy already, propagate
2434         d->setStyle_helper(new QStyleSheetStyle(style), true);
2435     } else
2436 #endif
2437         d->setStyle_helper(style, false);
2438 }
2439
2440 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2441 #ifdef Q_WS_MAC
2442         metalHack
2443 #endif
2444         )
2445 {
2446     Q_Q(QWidget);
2447     QStyle *oldStyle  = q->style();
2448 #ifndef QT_NO_STYLE_STYLESHEET
2449     QPointer<QStyle> origStyle;
2450 #endif
2451
2452 #ifdef Q_WS_MAC
2453     // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2454     // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2455     // set when changing that attribute and passes the widget's CURRENT style.
2456     // therefore no need to do a reassignment.
2457     if (!metalHack)
2458 #endif
2459     {
2460         createExtra();
2461
2462 #ifndef QT_NO_STYLE_STYLESHEET
2463         origStyle = extra->style.data();
2464 #endif
2465         extra->style = newStyle;
2466     }
2467
2468     // repolish
2469     if (q->windowType() != Qt::Desktop) {
2470         if (polished) {
2471             oldStyle->unpolish(q);
2472 #ifdef Q_WS_MAC
2473             if (metalHack)
2474                 macUpdateMetalAttribute();
2475 #endif
2476             q->style()->polish(q);
2477 #ifdef Q_WS_MAC
2478         } else if (metalHack) {
2479             macUpdateMetalAttribute();
2480 #endif
2481         }
2482     }
2483
2484     if (propagate) {
2485         // We copy the list because the order may be modified
2486         const QObjectList childrenList = children;
2487         for (int i = 0; i < childrenList.size(); ++i) {
2488             QWidget *c = qobject_cast<QWidget*>(childrenList.at(i));
2489             if (c)
2490                 c->d_func()->inheritStyle();
2491         }
2492     }
2493
2494 #ifndef QT_NO_STYLE_STYLESHEET
2495     if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2496         if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2497             cssStyle->clearWidgetFont(q);
2498         }
2499     }
2500 #endif
2501
2502     QEvent e(QEvent::StyleChange);
2503     QApplication::sendEvent(q, &e);
2504
2505 #ifndef QT_NO_STYLE_STYLESHEET
2506     // dereference the old stylesheet style
2507     if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2508         proxy->deref();
2509 #endif
2510 }
2511
2512 // Inherits style from the current parent and propagates it as necessary
2513 void QWidgetPrivate::inheritStyle()
2514 {
2515 #ifndef QT_NO_STYLE_STYLESHEET
2516     Q_Q(QWidget);
2517
2518     QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2519
2520     if (!q->styleSheet().isEmpty()) {
2521         Q_ASSERT(proxy);
2522         proxy->repolish(q);
2523         return;
2524     }
2525
2526     QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2527     QWidget *parent = q->parentWidget();
2528     QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2529     // If we have stylesheet on app or parent has stylesheet style, we need
2530     // to be running a proxy
2531     if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2532         QStyle *newStyle = parentStyle;
2533         if (q->testAttribute(Qt::WA_SetStyle))
2534             newStyle = new QStyleSheetStyle(origStyle);
2535         else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2536             newProxy->ref();
2537
2538         setStyle_helper(newStyle, true);
2539         return;
2540     }
2541
2542     // So, we have no stylesheet on parent/app and we have an empty stylesheet
2543     // we just need our original style back
2544     if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2545         return;
2546
2547     // We could have inherited the proxy from our parent (which has a custom style)
2548     // In such a case we need to start following the application style (i.e revert
2549     // the propagation behavior of QStyleSheetStyle)
2550     if (!q->testAttribute(Qt::WA_SetStyle))
2551         origStyle = 0;
2552
2553     setStyle_helper(origStyle, true);
2554 #endif // QT_NO_STYLE_STYLESHEET
2555 }
2556
2557
2558 /*!
2559     \fn bool QWidget::isWindow() const
2560
2561     Returns true if the widget is an independent window, otherwise
2562     returns false.
2563
2564     A window is a widget that isn't visually the child of any other
2565     widget and that usually has a frame and a
2566     \l{QWidget::setWindowTitle()}{window title}.
2567
2568     A window can have a \l{QWidget::parentWidget()}{parent widget}.
2569     It will then be grouped with its parent and deleted when the
2570     parent is deleted, minimized when the parent is minimized etc. If
2571     supported by the window manager, it will also have a common
2572     taskbar entry with its parent.
2573
2574     QDialog and QMainWindow widgets are by default windows, even if a
2575     parent widget is specified in the constructor. This behavior is
2576     specified by the Qt::Window flag.
2577
2578     \sa window(), isModal(), parentWidget()
2579 */
2580
2581 /*!
2582     \property QWidget::modal
2583     \brief whether the widget is a modal widget
2584
2585     This property only makes sense for windows. A modal widget
2586     prevents widgets in all other windows from getting any input.
2587
2588     By default, this property is false.
2589
2590     \sa isWindow(), windowModality, QDialog
2591 */
2592
2593 /*!
2594     \property QWidget::windowModality
2595     \brief which windows are blocked by the modal widget
2596     \since 4.1
2597
2598     This property only makes sense for windows. A modal widget
2599     prevents widgets in other windows from getting input. The value of
2600     this property controls which windows are blocked when the widget
2601     is visible. Changing this property while the window is visible has
2602     no effect; you must hide() the widget first, then show() it again.
2603
2604     By default, this property is Qt::NonModal.
2605
2606     \sa isWindow(), QWidget::modal, QDialog
2607 */
2608
2609 Qt::WindowModality QWidget::windowModality() const
2610 {
2611     return static_cast<Qt::WindowModality>(data->window_modality);
2612 }
2613
2614 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2615 {
2616     data->window_modality = windowModality;
2617     // setModal_sys() will be called by setAttribute()
2618     setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2619     setAttribute(Qt::WA_SetWindowModality, true);
2620 }
2621
2622 /*!
2623     \fn bool QWidget::underMouse() const
2624
2625     Returns true if the widget is under the mouse cursor; otherwise
2626     returns false.
2627
2628     This value is not updated properly during drag and drop
2629     operations.
2630
2631     \sa enterEvent(), leaveEvent()
2632 */
2633
2634 /*!
2635     \property QWidget::minimized
2636     \brief whether this widget is minimized (iconified)
2637
2638     This property is only relevant for windows.
2639
2640     By default, this property is false.
2641
2642     \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2643 */
2644 bool QWidget::isMinimized() const
2645 { return data->window_state & Qt::WindowMinimized; }
2646
2647 /*!
2648     Shows the widget minimized, as an icon.
2649
2650     Calling this function only affects \l{isWindow()}{windows}.
2651
2652     \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2653         isMinimized()
2654 */
2655 void QWidget::showMinimized()
2656 {
2657     bool isMin = isMinimized();
2658     if (isMin && isVisible())
2659         return;
2660
2661     ensurePolished();
2662
2663     if (!isMin)
2664         setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2665     setVisible(true);
2666 }
2667
2668 /*!
2669     \property QWidget::maximized
2670     \brief whether this widget is maximized
2671
2672     This property is only relevant for windows.
2673
2674     \note Due to limitations on some window systems, this does not always
2675     report the expected results (e.g., if the user on X11 maximizes the
2676     window via the window manager, Qt has no way of distinguishing this
2677     from any other resize). This is expected to improve as window manager
2678     protocols evolve.
2679
2680     By default, this property is false.
2681
2682     \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2683 */
2684 bool QWidget::isMaximized() const
2685 { return data->window_state & Qt::WindowMaximized; }
2686
2687
2688
2689 /*!
2690     Returns the current window state. The window state is a OR'ed
2691     combination of Qt::WindowState: Qt::WindowMinimized,
2692     Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2693
2694   \sa Qt::WindowState, setWindowState()
2695  */
2696 Qt::WindowStates QWidget::windowState() const
2697 {
2698     return Qt::WindowStates(data->window_state);
2699 }
2700
2701 /*!\internal
2702
2703    The function sets the window state on child widgets similar to
2704    setWindowState(). The difference is that the window state changed
2705    event has the isOverride() flag set. It exists mainly to keep
2706    QWorkspace working.
2707  */
2708 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2709 {
2710     QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2711     data->window_state  = newstate;
2712     QApplication::sendEvent(this, &e);
2713 }
2714
2715 /*!
2716     \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2717
2718     Sets the window state to \a windowState. The window state is a OR'ed
2719     combination of Qt::WindowState: Qt::WindowMinimized,
2720     Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2721
2722     If the window is not visible (i.e. isVisible() returns false), the
2723     window state will take effect when show() is called. For visible
2724     windows, the change is immediate. For example, to toggle between
2725     full-screen and normal mode, use the following code:
2726
2727     \snippet code/src_gui_kernel_qwidget.cpp 0
2728
2729     In order to restore and activate a minimized window (while
2730     preserving its maximized and/or full-screen state), use the following:
2731
2732     \snippet code/src_gui_kernel_qwidget.cpp 1
2733
2734     Calling this function will hide the widget. You must call show() to make
2735     the widget visible again.
2736
2737     \note On some window systems Qt::WindowActive is not immediate, and may be
2738     ignored in certain cases.
2739
2740     When the window state changes, the widget receives a changeEvent()
2741     of type QEvent::WindowStateChange.
2742
2743     \sa Qt::WindowState, windowState()
2744 */
2745
2746 /*!
2747     \property QWidget::fullScreen
2748     \brief whether the widget is shown in full screen mode
2749
2750     A widget in full screen mode occupies the whole screen area and does not
2751     display window decorations, such as a title bar.
2752
2753     By default, this property is false.
2754
2755     \sa windowState(), minimized, maximized
2756 */
2757 bool QWidget::isFullScreen() const
2758 { return data->window_state & Qt::WindowFullScreen; }
2759
2760 /*!
2761     Shows the widget in full-screen mode.
2762
2763     Calling this function only affects \l{isWindow()}{windows}.
2764
2765     To return from full-screen mode, call showNormal().
2766
2767     Full-screen mode works fine under Windows, but has certain
2768     problems under X. These problems are due to limitations of the
2769     ICCCM protocol that specifies the communication between X11
2770     clients and the window manager. ICCCM simply does not understand
2771     the concept of non-decorated full-screen windows. Therefore, the
2772     best we can do is to request a borderless window and place and
2773     resize it to fill the entire screen. Depending on the window
2774     manager, this may or may not work. The borderless window is
2775     requested using MOTIF hints, which are at least partially
2776     supported by virtually all modern window managers.
2777
2778     An alternative would be to bypass the window manager entirely and
2779     create a window with the Qt::X11BypassWindowManagerHint flag. This
2780     has other severe problems though, like totally broken keyboard focus
2781     and very strange effects on desktop changes or when the user raises
2782     other windows.
2783
2784     X11 window managers that follow modern post-ICCCM specifications
2785     support full-screen mode properly.
2786
2787     \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2788 */
2789 void QWidget::showFullScreen()
2790 {
2791 #ifdef Q_WS_MAC
2792     // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2793     QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2794     if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2795         mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2796         QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2797         mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2798     }
2799 #endif // Q_WS_MAC
2800     ensurePolished();
2801
2802     setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2803                    | Qt::WindowFullScreen);
2804     setVisible(true);
2805     activateWindow();
2806 }
2807
2808 /*!
2809     Shows the widget maximized.
2810
2811     Calling this function only affects \l{isWindow()}{windows}.
2812
2813     On X11, this function may not work properly with certain window
2814     managers. See the \l{Window Geometry} documentation for an explanation.
2815
2816     \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2817 */
2818 void QWidget::showMaximized()
2819 {
2820     ensurePolished();
2821
2822     setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2823                    | Qt::WindowMaximized);
2824 #ifdef Q_WS_MAC
2825     // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2826     QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2827     if (mainWindow)
2828     {
2829         QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2830         if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2831             mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2832             mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2833         }
2834     }
2835 #endif // Q_WS_MAC
2836     setVisible(true);
2837 }
2838
2839 /*!
2840     Restores the widget after it has been maximized or minimized.
2841
2842     Calling this function only affects \l{isWindow()}{windows}.
2843
2844     \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2845 */
2846 void QWidget::showNormal()
2847 {
2848     ensurePolished();
2849
2850     setWindowState(windowState() & ~(Qt::WindowMinimized
2851                                      | Qt::WindowMaximized
2852                                      | Qt::WindowFullScreen));
2853 #ifdef Q_WS_MAC
2854     // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2855     QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2856     if (mainWindow)
2857     {
2858         QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2859         if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2860             mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2861             mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2862         }
2863     }
2864 #endif // Q_WS_MAC
2865     setVisible(true);
2866 }
2867
2868 /*!
2869     Returns true if this widget would become enabled if \a ancestor is
2870     enabled; otherwise returns false.
2871
2872
2873
2874     This is the case if neither the widget itself nor every parent up
2875     to but excluding \a ancestor has been explicitly disabled.
2876
2877     isEnabledTo(0) is equivalent to isEnabled().
2878
2879     \sa setEnabled(), enabled
2880 */
2881
2882 bool QWidget::isEnabledTo(const QWidget *ancestor) const
2883 {
2884     const QWidget * w = this;
2885     while (!w->testAttribute(Qt::WA_ForceDisabled)
2886             && !w->isWindow()
2887             && w->parentWidget()
2888             && w->parentWidget() != ancestor)
2889         w = w->parentWidget();
2890     return !w->testAttribute(Qt::WA_ForceDisabled);
2891 }
2892
2893 #ifndef QT_NO_ACTION
2894 /*!
2895     Appends the action \a action to this widget's list of actions.
2896
2897     All QWidgets have a list of \l{QAction}s, however they can be
2898     represented graphically in many different ways. The default use of
2899     the QAction list (as returned by actions()) is to create a context
2900     QMenu.
2901
2902     A QWidget should only have one of each action and adding an action
2903     it already has will not cause the same action to be in the widget twice.
2904
2905     The ownership of \a action is not transferred to this QWidget.
2906
2907     \sa removeAction(), insertAction(), actions(), QMenu
2908 */
2909 void QWidget::addAction(QAction *action)
2910 {
2911     insertAction(0, action);
2912 }
2913
2914 /*!
2915     Appends the actions \a actions to this widget's list of actions.
2916
2917     \sa removeAction(), QMenu, addAction()
2918 */
2919 void QWidget::addActions(QList<QAction*> actions)
2920 {
2921     for(int i = 0; i < actions.count(); i++)
2922         insertAction(0, actions.at(i));
2923 }
2924
2925 /*!
2926     Inserts the action \a action to this widget's list of actions,
2927     before the action \a before. It appends the action if \a before is 0 or
2928     \a before is not a valid action for this widget.
2929
2930     A QWidget should only have one of each action.
2931
2932     \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2933 */
2934 void QWidget::insertAction(QAction *before, QAction *action)
2935 {
2936     if(!action) {
2937         qWarning("QWidget::insertAction: Attempt to insert null action");
2938         return;
2939     }
2940
2941     Q_D(QWidget);
2942     if(d->actions.contains(action))
2943         removeAction(action);
2944
2945     int pos = d->actions.indexOf(before);
2946     if (pos < 0) {
2947         before = 0;
2948         pos = d->actions.size();
2949     }
2950     d->actions.insert(pos, action);
2951
2952     QActionPrivate *apriv = action->d_func();
2953     apriv->widgets.append(this);
2954
2955     QActionEvent e(QEvent::ActionAdded, action, before);
2956     QApplication::sendEvent(this, &e);
2957 }
2958
2959 /*!
2960     Inserts the actions \a actions to this widget's list of actions,
2961     before the action \a before. It appends the action if \a before is 0 or
2962     \a before is not a valid action for this widget.
2963
2964     A QWidget can have at most one of each action.
2965
2966     \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
2967 */
2968 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
2969 {
2970     for(int i = 0; i < actions.count(); ++i)
2971         insertAction(before, actions.at(i));
2972 }
2973
2974 /*!
2975     Removes the action \a action from this widget's list of actions.
2976     \sa insertAction(), actions(), insertAction()
2977 */
2978 void QWidget::removeAction(QAction *action)
2979 {
2980     if (!action)
2981         return;
2982
2983     Q_D(QWidget);
2984
2985     QActionPrivate *apriv = action->d_func();
2986     apriv->widgets.removeAll(this);
2987
2988     if (d->actions.removeAll(action)) {
2989         QActionEvent e(QEvent::ActionRemoved, action);
2990         QApplication::sendEvent(this, &e);
2991     }
2992 }
2993
2994 /*!
2995     Returns the (possibly empty) list of this widget's actions.
2996
2997     \sa contextMenuPolicy, insertAction(), removeAction()
2998 */
2999 QList<QAction*> QWidget::actions() const
3000 {
3001     Q_D(const QWidget);
3002     return d->actions;
3003 }
3004 #endif // QT_NO_ACTION
3005
3006 /*!
3007   \fn bool QWidget::isEnabledToTLW() const
3008   \obsolete
3009
3010   This function is deprecated. It is equivalent to isEnabled()
3011 */
3012
3013 /*!
3014     \property QWidget::enabled
3015     \brief whether the widget is enabled
3016
3017     In general an enabled widget handles keyboard and mouse events; a disabled
3018     widget does not. An exception is made with \l{QAbstractButton}.
3019
3020     Some widgets display themselves differently when they are
3021     disabled. For example a button might draw its label grayed out. If
3022     your widget needs to know when it becomes enabled or disabled, you
3023     can use the changeEvent() with type QEvent::EnabledChange.
3024
3025     Disabling a widget implicitly disables all its children. Enabling
3026     respectively enables all child widgets unless they have been
3027     explicitly disabled.
3028
3029     By default, this property is true.
3030
3031     \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3032 */
3033 void QWidget::setEnabled(bool enable)
3034 {
3035     Q_D(QWidget);
3036     setAttribute(Qt::WA_ForceDisabled, !enable);
3037     d->setEnabled_helper(enable);
3038 }
3039
3040 void QWidgetPrivate::setEnabled_helper(bool enable)
3041 {
3042     Q_Q(QWidget);
3043
3044     if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3045         return; // nothing we can do
3046
3047     if (enable != q->testAttribute(Qt::WA_Disabled))
3048         return; // nothing to do
3049
3050     q->setAttribute(Qt::WA_Disabled, !enable);
3051     updateSystemBackground();
3052
3053     if (!enable && q->window()->focusWidget() == q) {
3054         bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3055         if (!parentIsEnabled || !q->focusNextChild())
3056             q->clearFocus();
3057     }
3058
3059     Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3060     for (int i = 0; i < children.size(); ++i) {
3061         QWidget *w = qobject_cast<QWidget *>(children.at(i));
3062         if (w && !w->testAttribute(attribute))
3063             w->d_func()->setEnabled_helper(enable);
3064     }
3065 #if defined(Q_WS_X11)
3066     if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3067         // enforce the windows behavior of clearing the cursor on
3068         // disabled widgets
3069         qt_x11_enforce_cursor(q);
3070     }
3071 #endif
3072 #ifndef QT_NO_CURSOR
3073     if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3074         // enforce the windows behavior of clearing the cursor on
3075         // disabled widgets
3076         qt_qpa_set_cursor(q, false);
3077     }
3078 #endif
3079 #if defined(Q_WS_MAC)
3080     setEnabled_helper_sys(enable);
3081 #endif
3082 #ifndef QT_NO_IM
3083     if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3084         QWidget *focusWidget = effectiveFocusWidget();
3085
3086         if (enable) {
3087             if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3088                 qApp->inputMethod()->update(Qt::ImEnabled);
3089         } else {
3090             qApp->inputMethod()->commit();
3091             qApp->inputMethod()->update(Qt::ImEnabled);
3092         }
3093     }
3094 #endif //QT_NO_IM
3095     QEvent e(QEvent::EnabledChange);
3096     QApplication::sendEvent(q, &e);
3097 }
3098
3099 /*!
3100     \property QWidget::acceptDrops
3101     \brief whether drop events are enabled for this widget
3102
3103     Setting this property to true announces to the system that this
3104     widget \e may be able to accept drop events.
3105
3106     If the widget is the desktop (windowType() == Qt::Desktop), this may
3107     fail if another application is using the desktop; you can call
3108     acceptDrops() to test if this occurs.
3109
3110     \warning Do not modify this property in a drag and drop event handler.
3111
3112     By default, this property is false.
3113
3114     \sa {Drag and Drop}
3115 */
3116 bool QWidget::acceptDrops() const
3117 {
3118     return testAttribute(Qt::WA_AcceptDrops);
3119 }
3120
3121 void QWidget::setAcceptDrops(bool on)
3122 {
3123     setAttribute(Qt::WA_AcceptDrops, on);
3124
3125 }
3126
3127
3128 /*!
3129     Disables widget input events if \a disable is true; otherwise
3130     enables input events.
3131
3132     See the \l enabled documentation for more information.
3133
3134     \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3135 */
3136 void QWidget::setDisabled(bool disable)
3137 {
3138     setEnabled(!disable);
3139 }
3140
3141 /*!
3142     \property QWidget::frameGeometry
3143     \brief geometry of the widget relative to its parent including any
3144     window frame
3145
3146     See the \l{Window Geometry} documentation for an overview of geometry
3147     issues with windows.
3148
3149     By default, this property contains a value that depends on the user's
3150     platform and screen geometry.
3151
3152     \sa geometry(), x(), y(), pos()
3153 */
3154 QRect QWidget::frameGeometry() const
3155 {
3156     Q_D(const QWidget);
3157     if (isWindow() && ! (windowType() == Qt::Popup)) {
3158         QRect fs = d->frameStrut();
3159         return QRect(data->crect.x() - fs.left(),
3160                      data->crect.y() - fs.top(),
3161                      data->crect.width() + fs.left() + fs.right(),
3162                      data->crect.height() + fs.top() + fs.bottom());
3163     }
3164     return data->crect;
3165 }
3166
3167 /*!
3168     \property QWidget::x
3169
3170     \brief the x coordinate of the widget relative to its parent including
3171     any window frame
3172
3173     See the \l{Window Geometry} documentation for an overview of geometry
3174     issues with windows.
3175
3176     By default, this property has a value of 0.
3177
3178     \sa frameGeometry, y, pos
3179 */
3180 int QWidget::x() const
3181 {
3182     Q_D(const QWidget);
3183     if (isWindow() && ! (windowType() == Qt::Popup))
3184         return data->crect.x() - d->frameStrut().left();
3185     return data->crect.x();
3186 }
3187
3188 /*!
3189     \property QWidget::y
3190     \brief the y coordinate of the widget relative to its parent and
3191     including any window frame
3192
3193     See the \l{Window Geometry} documentation for an overview of geometry
3194     issues with windows.
3195
3196     By default, this property has a value of 0.
3197
3198     \sa frameGeometry, x, pos
3199 */
3200 int QWidget::y() const
3201 {
3202     Q_D(const QWidget);
3203     if (isWindow() && ! (windowType() == Qt::Popup))
3204         return data->crect.y() - d->frameStrut().top();
3205     return data->crect.y();
3206 }
3207
3208 /*!
3209     \property QWidget::pos
3210     \brief the position of the widget within its parent widget
3211
3212     If the widget is a window, the position is that of the widget on
3213     the desktop, including its frame.
3214
3215     When changing the position, the widget, if visible, receives a
3216     move event (moveEvent()) immediately. If the widget is not
3217     currently visible, it is guaranteed to receive an event before it
3218     is shown.
3219
3220     By default, this property contains a position that refers to the
3221     origin.
3222
3223     \warning Calling move() or setGeometry() inside moveEvent() can
3224     lead to infinite recursion.
3225
3226     See the \l{Window Geometry} documentation for an overview of geometry
3227     issues with windows.
3228
3229     \sa frameGeometry, size, x(), y()
3230 */
3231 QPoint QWidget::pos() const
3232 {
3233     Q_D(const QWidget);
3234     QPoint result = data->crect.topLeft();
3235     if (isWindow() && ! (windowType() == Qt::Popup))
3236         if (!d->maybeTopData() || !d->maybeTopData()->posIncludesFrame)
3237             result -= d->frameStrut().topLeft();
3238     return result;
3239 }
3240
3241 /*!
3242     \property QWidget::geometry
3243     \brief the geometry of the widget relative to its parent and
3244     excluding the window frame
3245
3246     When changing the geometry, the widget, if visible, receives a
3247     move event (moveEvent()) and/or a resize event (resizeEvent())
3248     immediately. If the widget is not currently visible, it is
3249     guaranteed to receive appropriate events before it is shown.
3250
3251     The size component is adjusted if it lies outside the range
3252     defined by minimumSize() and maximumSize().
3253
3254     \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3255     can lead to infinite recursion.
3256
3257     See the \l{Window Geometry} documentation for an overview of geometry
3258     issues with windows.
3259
3260     By default, this property contains a value that depends on the user's
3261     platform and screen geometry.
3262
3263     \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3264         resizeEvent(), minimumSize(), maximumSize()
3265 */
3266
3267 /*!
3268     \property QWidget::normalGeometry
3269
3270     \brief the geometry of the widget as it will appear when shown as
3271     a normal (not maximized or full screen) top-level widget
3272
3273     For child widgets this property always holds an empty rectangle.
3274
3275     By default, this property contains an empty rectangle.
3276
3277     \sa QWidget::windowState(), QWidget::geometry
3278 */
3279
3280 /*!
3281     \property QWidget::size
3282     \brief the size of the widget excluding any window frame
3283
3284     If the widget is visible when it is being resized, it receives a resize event
3285     (resizeEvent()) immediately. If the widget is not currently
3286     visible, it is guaranteed to receive an event before it is shown.
3287
3288     The size is adjusted if it lies outside the range defined by
3289     minimumSize() and maximumSize().
3290
3291     By default, this property contains a value that depends on the user's
3292     platform and screen geometry.
3293
3294     \warning Calling resize() or setGeometry() inside resizeEvent() can
3295     lead to infinite recursion.
3296
3297     \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3298     appear on screen. This also applies to windows.
3299
3300     \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3301 */
3302
3303 /*!
3304     \property QWidget::width
3305     \brief the width of the widget excluding any window frame
3306
3307     See the \l{Window Geometry} documentation for an overview of geometry
3308     issues with windows.
3309
3310     \note Do not use this function to find the width of a screen on
3311     a \l{QDesktopWidget}{multiple screen desktop}. Read
3312     \l{QDesktopWidget#Screen Geometry}{this note} for details.
3313
3314     By default, this property contains a value that depends on the user's
3315     platform and screen geometry.
3316
3317     \sa geometry, height, size
3318 */
3319
3320 /*!
3321     \property QWidget::height
3322     \brief the height of the widget excluding any window frame
3323
3324     See the \l{Window Geometry} documentation for an overview of geometry
3325     issues with windows.
3326
3327     \note Do not use this function to find the height of a screen
3328     on a \l{QDesktopWidget}{multiple screen desktop}. Read
3329     \l{QDesktopWidget#Screen Geometry}{this note} for details.
3330
3331     By default, this property contains a value that depends on the user's
3332     platform and screen geometry.
3333
3334     \sa geometry, width, size
3335 */
3336
3337 /*!
3338     \property QWidget::rect
3339     \brief the internal geometry of the widget excluding any window
3340     frame
3341
3342     The rect property equals QRect(0, 0, width(), height()).
3343
3344     See the \l{Window Geometry} documentation for an overview of geometry
3345     issues with windows.
3346
3347     By default, this property contains a value that depends on the user's
3348     platform and screen geometry.
3349
3350     \sa size
3351 */
3352
3353
3354 QRect QWidget::normalGeometry() const
3355 {
3356     Q_D(const QWidget);
3357     if (!d->extra || !d->extra->topextra)
3358         return QRect();
3359
3360     if (!isMaximized() && !isFullScreen())
3361         return geometry();
3362
3363     return d->topData()->normalGeometry;
3364 }
3365
3366
3367 /*!
3368     \property QWidget::childrenRect
3369     \brief the bounding rectangle of the widget's children
3370
3371     Hidden children are excluded.
3372
3373     By default, for a widget with no children, this property contains a
3374     rectangle with zero width and height located at the origin.
3375
3376     \sa childrenRegion(), geometry()
3377 */
3378
3379 QRect QWidget::childrenRect() const
3380 {
3381     Q_D(const QWidget);
3382     QRect r(0, 0, 0, 0);
3383     for (int i = 0; i < d->children.size(); ++i) {
3384         QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3385         if (w && !w->isWindow() && !w->isHidden())
3386             r |= w->geometry();
3387     }
3388     return r;
3389 }
3390
3391 /*!
3392     \property QWidget::childrenRegion
3393     \brief the combined region occupied by the widget's children
3394
3395     Hidden children are excluded.
3396
3397     By default, for a widget with no children, this property contains an
3398     empty region.
3399
3400     \sa childrenRect(), geometry(), mask()
3401 */
3402
3403 QRegion QWidget::childrenRegion() const
3404 {
3405     Q_D(const QWidget);
3406     QRegion r;
3407     for (int i = 0; i < d->children.size(); ++i) {
3408         QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3409         if (w && !w->isWindow() && !w->isHidden()) {
3410             QRegion mask = w->mask();
3411             if (mask.isEmpty())
3412                 r |= w->geometry();
3413             else
3414                 r |= mask.translated(w->pos());
3415         }
3416     }
3417     return r;
3418 }
3419
3420
3421 /*!
3422     \property QWidget::minimumSize
3423     \brief the widget's minimum size
3424
3425     The widget cannot be resized to a smaller size than the minimum
3426     widget size. The widget's size is forced to the minimum size if
3427     the current size is smaller.
3428
3429     The minimum size set by this function will override the minimum size
3430     defined by QLayout. In order to unset the minimum size, use a
3431     value of \c{QSize(0, 0)}.
3432
3433     By default, this property contains a size with zero width and height.
3434
3435     \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3436 */
3437
3438 QSize QWidget::minimumSize() const
3439 {
3440     Q_D(const QWidget);
3441     return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3442 }
3443
3444 /*!
3445     \property QWidget::maximumSize
3446     \brief the widget's maximum size in pixels
3447
3448     The widget cannot be resized to a larger size than the maximum
3449     widget size.
3450
3451     By default, this property contains a size in which both width and height
3452     have values of 16777215.
3453
3454     \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3455     of widgets.
3456
3457     \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3458 */
3459
3460 QSize QWidget::maximumSize() const
3461 {
3462     Q_D(const QWidget);
3463     return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3464                  : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3465 }
3466
3467
3468 /*!
3469     \property QWidget::minimumWidth
3470     \brief the widget's minimum width in pixels
3471
3472     This property corresponds to the width held by the \l minimumSize property.
3473
3474     By default, this property has a value of 0.
3475
3476     \sa minimumSize, minimumHeight
3477 */
3478
3479 /*!
3480     \property QWidget::minimumHeight
3481     \brief the widget's minimum height in pixels
3482
3483     This property corresponds to the height held by the \l minimumSize property.
3484
3485     By default, this property has a value of 0.
3486
3487     \sa minimumSize, minimumWidth
3488 */
3489
3490 /*!
3491     \property QWidget::maximumWidth
3492     \brief the widget's maximum width in pixels
3493
3494     This property corresponds to the width held by the \l maximumSize property.
3495
3496     By default, this property contains a value of 16777215.
3497
3498     \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3499     of widgets.
3500
3501     \sa maximumSize, maximumHeight
3502 */
3503
3504 /*!
3505     \property QWidget::maximumHeight
3506     \brief the widget's maximum height in pixels
3507
3508     This property corresponds to the height held by the \l maximumSize property.
3509
3510     By default, this property contains a value of 16777215.
3511
3512     \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3513     of widgets.
3514
3515     \sa maximumSize, maximumWidth
3516 */
3517
3518 /*!
3519     \property QWidget::sizeIncrement
3520     \brief the size increment of the widget
3521
3522     When the user resizes the window, the size will move in steps of
3523     sizeIncrement().width() pixels horizontally and
3524     sizeIncrement.height() pixels vertically, with baseSize() as the
3525     basis. Preferred widget sizes are for non-negative integers \e i
3526     and \e j:
3527     \snippet code/src_gui_kernel_qwidget.cpp 2
3528
3529     Note that while you can set the size increment for all widgets, it
3530     only affects windows.
3531
3532     By default, this property contains a size with zero width and height.
3533
3534     \warning The size increment has no effect under Windows, and may
3535     be disregarded by the window manager on X11.
3536
3537     \sa size, minimumSize, maximumSize
3538 */
3539 QSize QWidget::sizeIncrement() const
3540 {
3541     Q_D(const QWidget);
3542     return (d->extra && d->extra->topextra)
3543         ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3544         : QSize(0, 0);
3545 }
3546
3547 /*!
3548     \property QWidget::baseSize
3549     \brief the base size of the widget
3550
3551     The base size is used to calculate a proper widget size if the
3552     widget defines sizeIncrement().
3553
3554     By default, for a newly-created widget, this property contains a size with
3555     zero width and height.
3556
3557     \sa setSizeIncrement()
3558 */
3559
3560 QSize QWidget::baseSize() const
3561 {
3562     Q_D(const QWidget);
3563     return (d->extra != 0 && d->extra->topextra != 0)
3564         ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3565         : QSize(0, 0);
3566 }
3567
3568 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3569 {
3570     Q_Q(QWidget);
3571
3572     int mw = minw, mh = minh;
3573     if (mw == QWIDGETSIZE_MAX)
3574         mw = 0;
3575     if (mh == QWIDGETSIZE_MAX)
3576         mh = 0;
3577     if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3578         qWarning("QWidget::setMinimumSize: (%s/%s) "
3579                 "The largest allowed size is (%d,%d)",
3580                  q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3581                 QWIDGETSIZE_MAX);
3582         minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3583         minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3584     }
3585     if (minw < 0 || minh < 0) {
3586         qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3587                 "are not possible",
3588                 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3589         minw = mw = qMax(minw, 0);
3590         minh = mh = qMax(minh, 0);
3591     }
3592     createExtra();
3593     if (extra->minw == mw && extra->minh == mh)
3594         return false;
3595     extra->minw = mw;
3596     extra->minh = mh;
3597     extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3598     return true;
3599 }
3600
3601 /*!
3602     \overload
3603
3604     This function corresponds to setMinimumSize(QSize(minw, minh)).
3605     Sets the minimum width to \a minw and the minimum height to \a
3606     minh.
3607 */
3608
3609 void QWidget::setMinimumSize(int minw, int minh)
3610 {
3611     Q_D(QWidget);
3612     if (!d->setMinimumSize_helper(minw, minh))
3613         return;
3614
3615     if (isWindow())
3616         d->setConstraints_sys();
3617     if (minw > width() || minh > height()) {
3618         bool resized = testAttribute(Qt::WA_Resized);
3619         bool maximized = isMaximized();
3620         resize(qMax(minw,width()), qMax(minh,height()));
3621         setAttribute(Qt::WA_Resized, resized); //not a user resize
3622         if (maximized)
3623             data->window_state = data->window_state | Qt::WindowMaximized;
3624     }
3625 #ifndef QT_NO_GRAPHICSVIEW
3626     if (d->extra) {
3627         if (d->extra->proxyWidget)
3628             d->extra->proxyWidget->setMinimumSize(minw, minh);
3629     }
3630 #endif
3631     d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3632 }
3633
3634 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3635 {
3636     Q_Q(QWidget);
3637     if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3638         qWarning("QWidget::setMaximumSize: (%s/%s) "
3639                 "The largest allowed size is (%d,%d)",
3640                  q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3641                 QWIDGETSIZE_MAX);
3642         maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3643         maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3644     }
3645     if (maxw < 0 || maxh < 0) {
3646         qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3647                 "are not possible",
3648                 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3649         maxw = qMax(maxw, 0);
3650         maxh = qMax(maxh, 0);
3651     }
3652     createExtra();
3653     if (extra->maxw == maxw && extra->maxh == maxh)
3654         return false;
3655     extra->maxw = maxw;
3656     extra->maxh = maxh;
3657     extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3658                              (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3659     return true;
3660 }
3661
3662 /*!
3663     \overload
3664
3665     This function corresponds to setMaximumSize(QSize(\a maxw, \a
3666     maxh)). Sets the maximum width to \a maxw and the maximum height
3667     to \a maxh.
3668 */
3669 void QWidget::setMaximumSize(int maxw, int maxh)
3670 {
3671     Q_D(QWidget);
3672     if (!d->setMaximumSize_helper(maxw, maxh))
3673         return;
3674
3675     if (isWindow())
3676         d->setConstraints_sys();
3677     if (maxw < width() || maxh < height()) {
3678         bool resized = testAttribute(Qt::WA_Resized);
3679         resize(qMin(maxw,width()), qMin(maxh,height()));
3680         setAttribute(Qt::WA_Resized, resized); //not a user resize
3681     }
3682
3683 #ifndef QT_NO_GRAPHICSVIEW
3684     if (d->extra) {
3685         if (d->extra->proxyWidget)
3686             d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3687     }
3688 #endif
3689
3690     d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3691 }
3692
3693 /*!
3694     \overload
3695
3696     Sets the x (width) size increment to \a w and the y (height) size
3697     increment to \a h.
3698 */
3699 void QWidget::setSizeIncrement(int w, int h)
3700 {
3701     Q_D(QWidget);
3702     d->createTLExtra();
3703     QTLWExtra* x = d->topData();
3704     if (x->incw == w && x->inch == h)
3705         return;
3706     x->incw = w;
3707     x->inch = h;
3708     if (isWindow())
3709         d->setConstraints_sys();
3710 }
3711
3712 /*!
3713     \overload
3714
3715     This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3716     the widgets base size to width \a basew and height \a baseh.
3717 */
3718 void QWidget::setBaseSize(int basew, int baseh)
3719 {
3720     Q_D(QWidget);
3721     d->createTLExtra();
3722     QTLWExtra* x = d->topData();
3723     if (x->basew == basew && x->baseh == baseh)
3724         return;
3725     x->basew = basew;
3726     x->baseh = baseh;
3727     if (isWindow())
3728         d->setConstraints_sys();
3729 }
3730
3731 /*!
3732     Sets both the minimum and maximum sizes of the widget to \a s,
3733     thereby preventing it from ever growing or shrinking.
3734
3735     This will override the default size constraints set by QLayout.
3736
3737     To remove constraints, set the size to QWIDGETSIZE_MAX.
3738
3739     Alternatively, if you want the widget to have a
3740     fixed size based on its contents, you can call
3741     QLayout::setSizeConstraint(QLayout::SetFixedSize);
3742
3743     \sa maximumSize, minimumSize
3744 */
3745
3746 void QWidget::setFixedSize(const QSize & s)
3747 {
3748     setFixedSize(s.width(), s.height());
3749 }
3750
3751
3752 /*!
3753     \fn void QWidget::setFixedSize(int w, int h)
3754     \overload
3755
3756     Sets the width of the widget to \a w and the height to \a h.
3757 */
3758
3759 void QWidget::setFixedSize(int w, int h)
3760 {
3761     Q_D(QWidget);
3762     bool minSizeSet = d->setMinimumSize_helper(w, h);
3763     bool maxSizeSet = d->setMaximumSize_helper(w, h);
3764     if (!minSizeSet && !maxSizeSet)
3765         return;
3766
3767     if (isWindow())
3768         d->setConstraints_sys();
3769     else
3770         d->updateGeometry_helper(true);
3771
3772     if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3773         resize(w, h);
3774 }
3775
3776 void QWidget::setMinimumWidth(int w)
3777 {
3778     Q_D(QWidget);
3779     d->createExtra();
3780     uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3781     setMinimumSize(w, minimumSize().height());
3782     d->extra->explicitMinSize = expl;
3783 }
3784
3785 void QWidget::setMinimumHeight(int h)
3786 {
3787     Q_D(QWidget);
3788     d->createExtra();
3789     uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3790     setMinimumSize(minimumSize().width(), h);
3791     d->extra->explicitMinSize = expl;
3792 }
3793
3794 void QWidget::setMaximumWidth(int w)
3795 {
3796     Q_D(QWidget);
3797     d->createExtra();
3798     uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3799     setMaximumSize(w, maximumSize().height());
3800     d->extra->explicitMaxSize = expl;
3801 }
3802
3803 void QWidget::setMaximumHeight(int h)
3804 {
3805     Q_D(QWidget);
3806     d->createExtra();
3807     uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3808     setMaximumSize(maximumSize().width(), h);
3809     d->extra->explicitMaxSize = expl;
3810 }
3811
3812 /*!
3813     Sets both the minimum and maximum width of the widget to \a w
3814     without changing the heights. Provided for convenience.
3815
3816     \sa sizeHint(), minimumSize(), maximumSize(), setFixedSize()
3817 */
3818
3819 void QWidget::setFixedWidth(int w)
3820 {
3821     Q_D(QWidget);
3822     d->createExtra();
3823     uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3824     uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3825     setMinimumSize(w, minimumSize().height());
3826     setMaximumSize(w, maximumSize().height());
3827     d->extra->explicitMinSize = explMin;
3828     d->extra->explicitMaxSize = explMax;
3829 }
3830
3831
3832 /*!
3833     Sets both the minimum and maximum heights of the widget to \a h
3834     without changing the widths. Provided for convenience.
3835
3836     \sa sizeHint(), minimumSize(), maximumSize(), setFixedSize()
3837 */
3838
3839 void QWidget::setFixedHeight(int h)
3840 {
3841     Q_D(QWidget);
3842     d->createExtra();
3843     uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3844     uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3845     setMinimumSize(minimumSize().width(), h);
3846     setMaximumSize(maximumSize().width(), h);
3847     d->extra->explicitMinSize = explMin;
3848     d->extra->explicitMaxSize = explMax;
3849 }
3850
3851
3852 /*!
3853     Translates the widget coordinate \a pos to the coordinate system
3854     of \a parent. The \a parent must not be 0 and must be a parent
3855     of the calling widget.
3856
3857     \sa mapFrom(), mapToParent(), mapToGlobal(), underMouse()
3858 */
3859
3860 QPoint QWidget::mapTo(const QWidget * parent, const QPoint & pos) const
3861 {
3862     QPoint p = pos;
3863     if (parent) {
3864         const QWidget * w = this;
3865         while (w != parent) {
3866             Q_ASSERT_X(w, "QWidget::mapTo(const QWidget *parent, const QPoint &pos)",
3867                        "parent must be in parent hierarchy");
3868             p = w->mapToParent(p);
3869             w = w->parentWidget();
3870         }
3871     }
3872     return p;
3873 }
3874
3875
3876 /*!
3877     Translates the widget coordinate \a pos from the coordinate system
3878     of \a parent to this widget's coordinate system. The \a parent
3879     must not be 0 and must be a parent of the calling widget.
3880
3881     \sa mapTo(), mapFromParent(), mapFromGlobal(), underMouse()
3882 */
3883
3884 QPoint QWidget::mapFrom(const QWidget * parent, const QPoint & pos) const
3885 {
3886     QPoint p(pos);
3887     if (parent) {
3888         const QWidget * w = this;
3889         while (w != parent) {
3890             Q_ASSERT_X(w, "QWidget::mapFrom(const QWidget *parent, const QPoint &pos)",
3891                        "parent must be in parent hierarchy");
3892
3893             p = w->mapFromParent(p);
3894             w = w->parentWidget();
3895         }
3896     }
3897     return p;
3898 }
3899
3900
3901 /*!
3902     Translates the widget coordinate \a pos to a coordinate in the
3903     parent widget.
3904
3905     Same as mapToGlobal() if the widget has no parent.
3906
3907     \sa mapFromParent(), mapTo(), mapToGlobal(), underMouse()
3908 */
3909
3910 QPoint QWidget::mapToParent(const QPoint &pos) const
3911 {
3912     return pos + data->crect.topLeft();
3913 }
3914
3915 /*!
3916     Translates the parent widget coordinate \a pos to widget
3917     coordinates.
3918
3919     Same as mapFromGlobal() if the widget has no parent.
3920
3921     \sa mapToParent(), mapFrom(), mapFromGlobal(), underMouse()
3922 */
3923
3924 QPoint QWidget::mapFromParent(const QPoint &pos) const
3925 {
3926     return pos - data->crect.topLeft();
3927 }
3928
3929
3930 /*!
3931     Returns the window for this widget, i.e. the next ancestor widget
3932     that has (or could have) a window-system frame.
3933
3934     If the widget is a window, the widget itself is returned.
3935
3936     Typical usage is changing the window title:
3937
3938     \snippet code/src_gui_kernel_qwidget.cpp 3
3939
3940     \sa isWindow()
3941 */
3942
3943 QWidget *QWidget::window() const
3944 {
3945     QWidget *w = (QWidget *)this;
3946     QWidget *p = w->parentWidget();
3947     while (!w->isWindow() && p) {
3948         w = p;
3949         p = p->parentWidget();
3950     }
3951     return w;
3952 }
3953
3954 /*!
3955     \since 4.4
3956
3957     Returns the native parent for this widget, i.e. the next ancestor widget
3958     that has a system identifier, or 0 if it does not have any native parent.
3959
3960     \sa effectiveWinId()
3961 */
3962 QWidget *QWidget::nativeParentWidget() const
3963 {
3964     QWidget *parent = parentWidget();
3965     while (parent && !parent->internalWinId())
3966         parent = parent->parentWidget();
3967     return parent;
3968 }
3969
3970 /*! \fn QWidget *QWidget::topLevelWidget() const
3971     \obsolete
3972
3973     Use window() instead.
3974 */
3975
3976
3977
3978 /*!
3979   Returns the background role of the widget.
3980
3981   The background role defines the brush from the widget's \l palette that
3982   is used to render the background.
3983
3984   If no explicit background role is set, the widget inherts its parent
3985   widget's background role.
3986
3987   \sa setBackgroundRole(), foregroundRole()
3988  */
3989 QPalette::ColorRole QWidget::backgroundRole() const
3990 {
3991
3992     const QWidget *w = this;
3993     do {
3994         QPalette::ColorRole role = w->d_func()->bg_role;
3995         if (role != QPalette::NoRole)
3996             return role;
3997         if (w->isWindow() || w->windowType() == Qt::SubWindow)
3998             break;
3999         w = w->parentWidget();
4000     } while (w);
4001     return QPalette::Window;
4002 }
4003
4004 /*!
4005   Sets the background role of the widget to \a role.
4006
4007   The background role defines the brush from the widget's \l palette that
4008   is used to render the background.
4009
4010   If \a role is QPalette::NoRole, then the widget inherits its
4011   parent's background role.
4012
4013   Note that styles are free to choose any color from the palette.
4014   You can modify the palette or set a style sheet if you don't
4015   achieve the result you want with setBackgroundRole().
4016
4017   \sa backgroundRole(), foregroundRole()
4018  */
4019
4020 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4021 {
4022     Q_D(QWidget);
4023     d->bg_role = role;
4024     d->updateSystemBackground();
4025     d->propagatePaletteChange();
4026     d->updateIsOpaque();
4027 }
4028
4029 /*!
4030   Returns the foreground role.
4031
4032   The foreground role defines the color from the widget's \l palette that
4033   is used to draw the foreground.
4034
4035   If no explicit foreground role is set, the function returns a role
4036   that contrasts with the background role.
4037
4038   \sa setForegroundRole(), backgroundRole()
4039  */
4040 QPalette::ColorRole QWidget::foregroundRole() const
4041 {
4042     Q_D(const QWidget);
4043     QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4044     if (rl != QPalette::NoRole)
4045         return rl;
4046     QPalette::ColorRole role = QPalette::WindowText;
4047     switch (backgroundRole()) {
4048     case QPalette::Button:
4049         role = QPalette::ButtonText;
4050         break;
4051     case QPalette::Base:
4052         role = QPalette::Text;
4053         break;
4054     case QPalette::Dark:
4055     case QPalette::Shadow:
4056         role = QPalette::Light;
4057         break;
4058     case QPalette::Highlight:
4059         role = QPalette::HighlightedText;
4060         break;
4061     case QPalette::ToolTipBase:
4062         role = QPalette::ToolTipText;
4063         break;
4064     default:
4065         ;
4066     }
4067     return role;
4068 }
4069
4070 /*!
4071   Sets the foreground role of the widget to \a role.
4072
4073   The foreground role defines the color from the widget's \l palette that
4074   is used to draw the foreground.
4075
4076   If \a role is QPalette::NoRole, the widget uses a foreground role
4077   that contrasts with the background role.
4078
4079   Note that styles are free to choose any color from the palette.
4080   You can modify the palette or set a style sheet if you don't
4081   achieve the result you want with setForegroundRole().
4082
4083   \sa foregroundRole(), backgroundRole()
4084  */
4085 void QWidget::setForegroundRole(QPalette::ColorRole role)
4086 {
4087     Q_D(QWidget);
4088     d->fg_role = role;
4089     d->updateSystemBackground();
4090     d->propagatePaletteChange();
4091 }
4092
4093 /*!
4094     \property QWidget::palette
4095     \brief the widget's palette
4096
4097     This property describes the widget's palette. The palette is used by the
4098     widget's style when rendering standard components, and is available as a
4099     means to ensure that custom widgets can maintain consistency with the
4100     native platform's look and feel. It's common that different platforms, or
4101     different styles, have different palettes.
4102
4103     When you assign a new palette to a widget, the color roles from this
4104     palette are combined with the widget's default palette to form the
4105     widget's final palette. The palette entry for the widget's background role
4106     is used to fill the widget's background (see QWidget::autoFillBackground),
4107     and the foreground role initializes QPainter's pen.
4108
4109     The default depends on the system environment. QApplication maintains a
4110     system/theme palette which serves as a default for all widgets.  There may
4111     also be special palette defaults for certain types of widgets (e.g., on
4112     Windows XP and Vista, all classes that derive from QMenuBar have a special
4113     default palette). You can also define default palettes for widgets
4114     yourself by passing a custom palette and the name of a widget to
4115     QApplication::setPalette(). Finally, the style always has the option of
4116     polishing the palette as it's assigned (see QStyle::polish()).
4117
4118     QWidget propagates explicit palette roles from parent to child. If you
4119     assign a brush or color to a specific role on a palette and assign that
4120     palette to a widget, that role will propagate to all the widget's
4121     children, overriding any system defaults for that role. Note that palettes
4122     by default don't propagate to windows (see isWindow()) unless the
4123     Qt::WA_WindowPropagation attribute is enabled.
4124
4125     QWidget's palette propagation is similar to its font propagation.
4126
4127     The current style, which is used to render the content of all standard Qt
4128     widgets, is free to choose colors and brushes from the widget palette, or
4129     in some cases, to ignore the palette (partially, or completely). In
4130     particular, certain styles like GTK style, Mac style, Windows XP, and
4131     Vista style, depend on third party APIs to render the content of widgets,
4132     and these styles typically do not follow the palette. Because of this,
4133     assigning roles to a widget's palette is not guaranteed to change the
4134     appearance of the widget. Instead, you may choose to apply a \l
4135     styleSheet. You can refer to our Knowledge Base article
4136     \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4137     information.
4138
4139     \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4140     When using style sheets, the palette of a widget can be customized using
4141     the "color", "background-color", "selection-color",
4142     "selection-background-color" and "alternate-background-color".
4143
4144     \sa QApplication::palette(), QWidget::font()
4145 */
4146 const QPalette &QWidget::palette() const
4147 {
4148     if (!isEnabled()) {
4149         data->pal.setCurrentColorGroup(QPalette::Disabled);
4150     } else if ((!isVisible() || isActiveWindow())
4151 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
4152         && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4153 #endif
4154         ) {
4155         data->pal.setCurrentColorGroup(QPalette::Active);
4156     } else {
4157 #ifdef Q_WS_MAC
4158         extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4159         if (qt_mac_can_clickThrough(this))
4160             data->pal.setCurrentColorGroup(QPalette::Active);
4161         else
4162 #endif
4163             data->pal.setCurrentColorGroup(QPalette::Inactive);
4164     }
4165     return data->pal;
4166 }
4167
4168 void QWidget::setPalette(const QPalette &palette)
4169 {
4170     Q_D(QWidget);
4171     setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4172
4173     // Determine which palette is inherited from this widget's ancestors and
4174     // QApplication::palette, resolve this against \a palette (attributes from
4175     // the inherited palette are copied over this widget's palette). Then
4176     // propagate this palette to this widget's children.
4177     QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4178     QPalette resolvedPalette = palette.resolve(naturalPalette);
4179     d->setPalette_helper(resolvedPalette);
4180 }
4181
4182 /*!
4183     \internal
4184
4185     Returns the palette that the widget \a w inherits from its ancestors and
4186     QApplication::palette. \a inheritedMask is the combination of the widget's
4187     ancestors palette request masks (i.e., which attributes from the parent
4188     widget's palette are implicitly imposed on this widget by the user). Note
4189     that this font does not take into account the palette set on \a w itself.
4190 */
4191 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4192 {
4193     Q_Q(const QWidget);
4194     QPalette naturalPalette = QApplication::palette(q);
4195     if (!q->testAttribute(Qt::WA_StyleSheet)
4196         && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4197 #ifndef QT_NO_GRAPHICSVIEW
4198             || (extra && extra->proxyWidget)
4199 #endif //QT_NO_GRAPHICSVIEW
4200             )) {
4201         if (QWidget *p = q->parentWidget()) {
4202             if (!p->testAttribute(Qt::WA_StyleSheet)) {
4203                 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4204                     QPalette inheritedPalette = p->palette();
4205                     inheritedPalette.resolve(inheritedMask);
4206                     naturalPalette = inheritedPalette.resolve(naturalPalette);
4207                 } else {
4208                     naturalPalette = p->palette();
4209                 }
4210             }
4211         }
4212 #ifndef QT_NO_GRAPHICSVIEW
4213         else if (extra && extra->proxyWidget) {
4214             QPalette inheritedPalette = extra->proxyWidget->palette();
4215             inheritedPalette.resolve(inheritedMask);
4216             naturalPalette = inheritedPalette.resolve(naturalPalette);
4217         }
4218 #endif //QT_NO_GRAPHICSVIEW
4219     }
4220     naturalPalette.resolve(0);
4221     return naturalPalette;
4222 }
4223 /*!
4224     \internal
4225
4226     Determine which palette is inherited from this widget's ancestors and
4227     QApplication::palette, resolve this against this widget's palette
4228     (attributes from the inherited palette are copied over this widget's
4229     palette). Then propagate this palette to this widget's children.
4230 */
4231 void QWidgetPrivate::resolvePalette()
4232 {
4233     QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4234     QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4235     setPalette_helper(resolvedPalette);
4236 }
4237
4238 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4239 {
4240     Q_Q(QWidget);
4241     if (data.pal == palette && data.pal.resolve() == palette.resolve())
4242         return;
4243     data.pal = palette;
4244     updateSystemBackground();
4245     propagatePaletteChange();
4246     updateIsOpaque();
4247     q->update();
4248     updateIsOpaque();
4249 }
4250
4251 /*!
4252     \property QWidget::font
4253     \brief the font currently set for the widget
4254
4255     This property describes the widget's requested font. The font is used by
4256     the widget's style when rendering standard components, and is available as
4257     a means to ensure that custom widgets can maintain consistency with the
4258     native platform's look and feel. It's common that different platforms, or
4259     different styles, define different fonts for an application.
4260
4261     When you assign a new font to a widget, the properties from this font are
4262     combined with the widget's default font to form the widget's final
4263     font. You can call fontInfo() to get a copy of the widget's final
4264     font. The final font is also used to initialize QPainter's font.
4265
4266     The default depends on the system environment. QApplication maintains a
4267     system/theme font which serves as a default for all widgets.  There may
4268     also be special font defaults for certain types of widgets. You can also
4269     define default fonts for widgets yourself by passing a custom font and the
4270     name of a widget to QApplication::setFont(). Finally, the font is matched
4271     against Qt's font database to find the best match.
4272
4273     QWidget propagates explicit font properties from parent to child. If you
4274     change a specific property on a font and assign that font to a widget,
4275     that property will propagate to all the widget's children, overriding any
4276     system defaults for that property. Note that fonts by default don't
4277     propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4278     attribute is enabled.
4279
4280     QWidget's font propagation is similar to its palette propagation.
4281
4282     The current style, which is used to render the content of all standard Qt
4283     widgets, is free to choose to use the widget font, or in some cases, to
4284     ignore it (partially, or completely). In particular, certain styles like
4285     GTK style, Mac style, Windows XP, and Vista style, apply special
4286     modifications to the widget font to match the platform's native look and
4287     feel. Because of this, assigning properties to a widget's font is not
4288     guaranteed to change the appearance of the widget. Instead, you may choose
4289     to apply a \l styleSheet.
4290
4291     \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4292     style sheets will take precedence if the settings conflict.
4293
4294     \sa fontInfo(), fontMetrics()
4295 */
4296
4297 void QWidget::setFont(const QFont &font)
4298 {
4299     Q_D(QWidget);
4300
4301 #ifndef QT_NO_STYLE_STYLESHEET
4302     const QStyleSheetStyle* style;
4303     if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4304         style->saveWidgetFont(this, font);
4305     }
4306 #endif
4307
4308     setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4309
4310     // Determine which font is inherited from this widget's ancestors and
4311     // QApplication::font, resolve this against \a font (attributes from the
4312     // inherited font are copied over). Then propagate this font to this
4313     // widget's children.
4314     QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4315     QFont resolvedFont = font.resolve(naturalFont);
4316     d->setFont_helper(resolvedFont);
4317 }
4318
4319 /*
4320     \internal
4321
4322     Returns the font that the widget \a w inherits from its ancestors and
4323     QApplication::font. \a inheritedMask is the combination of the widget's
4324     ancestors font request masks (i.e., which attributes from the parent
4325     widget's font are implicitly imposed on this widget by the user). Note
4326     that this font does not take into account the font set on \a w itself.
4327
4328     ### Stylesheet has a different font propagation mechanism. When a stylesheet
4329         is applied, fonts are not propagated anymore
4330 */
4331 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4332 {
4333     Q_Q(const QWidget);
4334     QFont naturalFont = QApplication::font(q);
4335     if (!q->testAttribute(Qt::WA_StyleSheet)
4336         && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4337 #ifndef QT_NO_GRAPHICSVIEW
4338             || (extra && extra->proxyWidget)
4339 #endif //QT_NO_GRAPHICSVIEW
4340             )) {
4341         if (QWidget *p = q->parentWidget()) {
4342             if (!p->testAttribute(Qt::WA_StyleSheet)) {
4343                 if (!naturalFont.isCopyOf(QApplication::font())) {
4344                     QFont inheritedFont = p->font();
4345                     inheritedFont.resolve(inheritedMask);
4346                     naturalFont = inheritedFont.resolve(naturalFont);
4347                 } else {
4348                     naturalFont = p->font();
4349                 }
4350             }
4351         }
4352 #ifndef QT_NO_GRAPHICSVIEW
4353         else if (extra && extra->proxyWidget) {
4354             QFont inheritedFont = extra->proxyWidget->font();
4355             inheritedFont.resolve(inheritedMask);
4356             naturalFont = inheritedFont.resolve(naturalFont);
4357         }
4358 #endif //QT_NO_GRAPHICSVIEW
4359     }
4360     naturalFont.resolve(0);
4361     return naturalFont;
4362 }
4363
4364 /*!
4365     \internal
4366
4367     Determine which font is implicitly imposed on this widget by its ancestors
4368     and QApplication::font, resolve this against its own font (attributes from
4369     the implicit font are copied over). Then propagate this font to this
4370     widget's children.
4371 */
4372 void QWidgetPrivate::resolveFont()
4373 {
4374     QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4375     QFont resolvedFont = data.fnt.resolve(naturalFont);
4376     setFont_helper(resolvedFont);
4377 }
4378
4379 /*!
4380     \internal
4381
4382     Assign \a font to this widget, and propagate it to all children, except
4383     style sheet widgets (handled differently) and windows that don't enable
4384     window propagation.  \a implicitMask is the union of all ancestor widgets'
4385     font request masks, and determines which attributes from this widget's
4386     font should propagate.
4387 */
4388 void QWidgetPrivate::updateFont(const QFont &font)
4389 {
4390     Q_Q(QWidget);
4391 #ifndef QT_NO_STYLE_STYLESHEET
4392     const QStyleSheetStyle* cssStyle;
4393     cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4394 #endif
4395
4396     data.fnt = QFont(font, q);
4397 #if defined(Q_WS_X11)
4398     // make sure the font set on this widget is associated with the correct screen
4399     data.fnt.x11SetScreen(xinfo.screen());
4400 #endif
4401     // Combine new mask with natural mask and propagate to children.
4402 #ifndef QT_NO_GRAPHICSVIEW
4403     if (!q->parentWidget() && extra && extra->proxyWidget) {
4404         QGraphicsProxyWidget *p = extra->proxyWidget;
4405         inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4406     } else
4407 #endif //QT_NO_GRAPHICSVIEW
4408     if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4409         inheritedFontResolveMask = 0;
4410     }
4411     uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4412
4413     for (int i = 0; i < children.size(); ++i) {
4414         QWidget *w = qobject_cast<QWidget*>(children.at(i));
4415         if (w) {
4416             if (0) {
4417 #ifndef QT_NO_STYLE_STYLESHEET
4418             } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4419                 // Style sheets follow a different font propagation scheme.
4420                 if (cssStyle)
4421                     cssStyle->updateStyleSheetFont(w);
4422 #endif
4423             } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4424                 // Propagate font changes.
4425                 QWidgetPrivate *wd = w->d_func();
4426                 wd->inheritedFontResolveMask = newMask;
4427                 wd->resolveFont();
4428             }
4429         }
4430     }
4431
4432 #ifndef QT_NO_STYLE_STYLESHEET
4433     if (cssStyle) {
4434         cssStyle->updateStyleSheetFont(q);
4435     }
4436 #endif
4437
4438     QEvent e(QEvent::FontChange);
4439     QApplication::sendEvent(q, &e);
4440 }
4441
4442 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4443 {
4444     Q_Q(QWidget);
4445
4446     if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4447         return;
4448     q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4449     if (!children.isEmpty()) {
4450         for (int i = 0; i < children.size(); ++i) {
4451             QWidget *w = qobject_cast<QWidget*>(children.at(i));
4452             if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4453                 w->d_func()->setLayoutDirection_helper(direction);
4454         }
4455     }
4456     QEvent e(QEvent::LayoutDirectionChange);
4457     QApplication::sendEvent(q, &e);
4458 }
4459
4460 void QWidgetPrivate::resolveLayoutDirection()
4461 {
4462     Q_Q(const QWidget);
4463     if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4464         setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4465 }
4466
4467 /*!
4468     \property QWidget::layoutDirection
4469
4470     \brief the layout direction for this widget
4471
4472     By default, this property is set to Qt::LeftToRight.
4473
4474     When the layout direction is set on a widget, it will propagate to
4475     the widget's children, but not to a child that is a window and not
4476     to a child for which setLayoutDirection() has been explicitly
4477     called. Also, child widgets added \e after setLayoutDirection()
4478     has been called for the parent do not inherit the parent's layout
4479     direction.
4480
4481     This method no longer affects text layout direction since Qt 4.7.
4482
4483     \sa QApplication::layoutDirection
4484 */
4485 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4486 {
4487     Q_D(QWidget);
4488
4489     if (direction == Qt::LayoutDirectionAuto) {
4490         unsetLayoutDirection();
4491         return;
4492     }
4493
4494     setAttribute(Qt::WA_SetLayoutDirection);
4495     d->setLayoutDirection_helper(direction);
4496 }
4497
4498 Qt::LayoutDirection QWidget::layoutDirection() const
4499 {
4500     return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4501 }
4502
4503 void QWidget::unsetLayoutDirection()
4504 {
4505     Q_D(QWidget);
4506     setAttribute(Qt::WA_SetLayoutDirection, false);
4507     d->resolveLayoutDirection();
4508 }
4509
4510 /*!
4511     \fn QFontMetrics QWidget::fontMetrics() const
4512
4513     Returns the font metrics for the widget's current font.
4514     Equivalent to QFontMetrics(widget->font()).
4515
4516     \sa font(), fontInfo(), setFont()
4517 */
4518
4519 /*!
4520     \fn QFontInfo QWidget::fontInfo() const
4521
4522     Returns the font info for the widget's current font.
4523     Equivalent to QFontInto(widget->font()).
4524
4525     \sa font(), fontMetrics(), setFont()
4526 */
4527
4528
4529 /*!
4530     \property QWidget::cursor
4531     \brief the cursor shape for this widget
4532
4533     The mouse cursor will assume this shape when it's over this
4534     widget. See the \l{Qt::CursorShape}{list of predefined cursor objects} for a range of useful shapes.
4535
4536     An editor widget might use an I-beam cursor:
4537     \snippet code/src_gui_kernel_qwidget.cpp 6
4538
4539     If no cursor has been set, or after a call to unsetCursor(), the
4540     parent's cursor is used.
4541
4542     By default, this property contains a cursor with the Qt::ArrowCursor
4543     shape.
4544
4545     Some underlying window implementations will reset the cursor if it
4546     leaves a widget even if the mouse is grabbed. If you want to have
4547     a cursor set for all widgets, even when outside the window, consider
4548     QApplication::setOverrideCursor().
4549
4550     \sa QApplication::setOverrideCursor()
4551 */
4552
4553 #ifndef QT_NO_CURSOR
4554 QCursor QWidget::cursor() const
4555 {
4556     Q_D(const QWidget);
4557     if (testAttribute(Qt::WA_SetCursor))
4558         return (d->extra && d->extra->curs)
4559             ? *d->extra->curs
4560             : QCursor(Qt::ArrowCursor);
4561     if (isWindow() || !parentWidget())
4562         return QCursor(Qt::ArrowCursor);
4563     return parentWidget()->cursor();
4564 }
4565
4566 void QWidget::setCursor(const QCursor &cursor)
4567 {
4568     Q_D(QWidget);
4569 // On Mac we must set the cursor even if it is the ArrowCursor.
4570 #if !defined(Q_WS_MAC)
4571     if (cursor.shape() != Qt::ArrowCursor
4572         || (d->extra && d->extra->curs))
4573 #endif
4574     {
4575         d->createExtra();
4576         QCursor *newCursor = new QCursor(cursor);
4577         delete d->extra->curs;
4578         d->extra->curs = newCursor;
4579     }
4580     setAttribute(Qt::WA_SetCursor);
4581     d->setCursor_sys(cursor);
4582
4583     QEvent event(QEvent::CursorChange);
4584     QApplication::sendEvent(this, &event);
4585 }
4586
4587 void QWidget::unsetCursor()
4588 {
4589     Q_D(QWidget);
4590     if (d->extra) {
4591         delete d->extra->curs;
4592         d->extra->curs = 0;
4593     }
4594     if (!isWindow())
4595         setAttribute(Qt::WA_SetCursor, false);
4596     d->unsetCursor_sys();
4597
4598     QEvent event(QEvent::CursorChange);
4599     QApplication::sendEvent(this, &event);
4600 }
4601
4602 #endif
4603
4604 /*!
4605     \enum QWidget::RenderFlag
4606
4607     This enum describes how to render the widget when calling QWidget::render().
4608
4609     \value DrawWindowBackground If you enable this option, the widget's background
4610     is rendered into the target even if autoFillBackground is not set. By default,
4611     this option is enabled.
4612
4613     \value DrawChildren If you enable this option, the widget's children
4614     are rendered recursively into the target. By default, this option is enabled.
4615
4616     \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4617     is ignored when rendering into the target. By default, this option is disabled.
4618
4619     \since 4.3
4620 */
4621
4622 /*!
4623     \since 4.3
4624
4625     Renders the \a sourceRegion of this widget into the \a target
4626     using \a renderFlags to determine how to render. Rendering
4627     starts at \a targetOffset in the \a target. For example:
4628
4629     \snippet code/src_gui_kernel_qwidget.cpp 7
4630
4631     If \a sourceRegion is a null region, this function will use QWidget::rect() as
4632     the region, i.e. the entire widget.
4633
4634     Ensure that you call QPainter::end() for the \a target device's
4635     active painter (if any) before rendering. For example:
4636
4637     \snippet code/src_gui_kernel_qwidget.cpp 8
4638
4639     \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4640     or QGLWidget::renderPixmap() instead.
4641 */
4642 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4643                      const QRegion &sourceRegion, RenderFlags renderFlags)
4644 {
4645     d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4646 }
4647
4648 /*!
4649     \overload
4650
4651     Renders the widget into the \a painter's QPainter::device().
4652
4653     Transformations and settings applied to the \a painter will be used
4654     when rendering.
4655
4656     \note The \a painter must be active. On Mac OS X the widget will be
4657     rendered into a QPixmap and then drawn by the \a painter.
4658
4659     \sa QPainter::device()
4660 */
4661 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4662                      const QRegion &sourceRegion, RenderFlags renderFlags)
4663 {
4664     if (!painter) {
4665         qWarning("QWidget::render: Null pointer to painter");
4666         return;
4667     }
4668
4669     if (!painter->isActive()) {
4670         qWarning("QWidget::render: Cannot render with an inactive painter");
4671         return;
4672     }
4673
4674     const qreal opacity = painter->opacity();
4675     if (qFuzzyIsNull(opacity))
4676         return; // Fully transparent.
4677
4678     Q_D(QWidget);
4679     const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4680     const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4681                                                      : sourceRegion;
4682     if (toBePainted.isEmpty())
4683         return;
4684
4685     if (!d->extra)
4686         d->createExtra();
4687     d->extra->inRenderWithPainter = true;
4688
4689 #ifdef Q_WS_MAC
4690     d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4691 #else
4692     QPaintEngine *engine = painter->paintEngine();
4693     Q_ASSERT(engine);
4694     QPaintEnginePrivate *enginePriv = engine->d_func();
4695     Q_ASSERT(enginePriv);
4696     QPaintDevice *target = engine->paintDevice();
4697     Q_ASSERT(target);
4698
4699     // Render via a pixmap when dealing with non-opaque painters or printers.
4700     if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4701         d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4702         d->extra->inRenderWithPainter = false;
4703         return;
4704     }
4705
4706     // Set new shared painter.
4707     QPainter *oldPainter = d->sharedPainter();
4708     d->setSharedPainter(painter);
4709
4710     // Save current system clip, viewport and transform,
4711     const QTransform oldTransform = enginePriv->systemTransform;
4712     const QRegion oldSystemClip = enginePriv->systemClip;
4713     const QRegion oldSystemViewport = enginePriv->systemViewport;
4714
4715     // This ensures that all painting triggered by render() is clipped to the current engine clip.
4716     if (painter->hasClipping()) {
4717         const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4718         enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4719     } else {
4720         enginePriv->setSystemViewport(oldSystemClip);
4721     }
4722
4723     render(target, targetOffset, toBePainted, renderFlags);
4724
4725     // Restore system clip, viewport and transform.
4726     enginePriv->systemClip = oldSystemClip;
4727     enginePriv->setSystemViewport(oldSystemViewport);
4728     enginePriv->setSystemTransform(oldTransform);
4729
4730     // Restore shared painter.
4731     d->setSharedPainter(oldPainter);
4732 #endif
4733
4734     d->extra->inRenderWithPainter = false;
4735 }
4736
4737 static void sendResizeEvents(QWidget *target)
4738 {
4739     QResizeEvent e(target->size(), QSize());
4740     QApplication::sendEvent(target, &e);
4741
4742     const QObjectList children = target->children();
4743     for (int i = 0; i < children.size(); ++i) {
4744         QWidget *child = static_cast<QWidget*>(children.at(i));
4745         if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4746             sendResizeEvents(child);
4747     }
4748 }
4749
4750 /*!
4751     \since 5.0
4752
4753     Renders the widget into a pixmap restricted by the
4754     given \a rectangle. If the widget has any children, then
4755     they are also painted in the appropriate positions.
4756
4757     If a rectangle with an invalid size is specified  (the default),
4758     the entire widget is painted.
4759
4760     \sa render(), QPixmap
4761 */
4762
4763 /* INVOKABLE since used by QPixmap::grabWidget(). */
4764 QPixmap QWidget::grab(const QRect &rectangle)
4765 {
4766     Q_D(QWidget);
4767     if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4768         sendResizeEvents(this);
4769
4770     const QWidget::RenderFlags renderFlags = QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask;
4771
4772     const bool oldDirtyOpaqueChildren =  d->dirtyOpaqueChildren;
4773     QRect r(rectangle);
4774     if (r.width() < 0 || r.height() < 0) {
4775         // For grabbing widgets that haven't been shown yet,
4776         // we trigger the layouting mechanism to determine the widget's size.
4777         r = d->prepareToRender(QRegion(), renderFlags).boundingRect();
4778         r.setTopLeft(rectangle.topLeft());
4779     }
4780
4781     if (!r.intersects(rect()))
4782         return QPixmap();
4783
4784     QPixmap res(r.size());
4785     if (!d->isOpaque)
4786         res.fill(Qt::transparent);
4787     render(&res, QPoint(), QRegion(r), renderFlags);
4788
4789     d->dirtyOpaqueChildren = oldDirtyOpaqueChildren;
4790     return res;
4791 }
4792
4793 /*!
4794     \brief The graphicsEffect function returns a pointer to the
4795     widget's graphics effect.
4796
4797     If the widget has no graphics effect, 0 is returned.
4798
4799     \since 4.6
4800
4801     \sa setGraphicsEffect()
4802 */
4803 #ifndef QT_NO_GRAPHICSEFFECT
4804 QGraphicsEffect *QWidget::graphicsEffect() const
4805 {
4806     Q_D(const QWidget);
4807     return d->graphicsEffect;
4808 }
4809 #endif //QT_NO_GRAPHICSEFFECT
4810
4811 /*!
4812
4813   \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4814
4815     Sets \a effect as the widget's effect. If there already is an effect installed
4816     on this widget, QWidget will delete the existing effect before installing
4817     the new \a effect.
4818
4819     If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4820     the effect from the widget and install it on this widget.
4821
4822     QWidget takes ownership of \a effect.
4823
4824     \note This function will apply the effect on itself and all its children.
4825
4826     \since 4.6
4827
4828     \sa graphicsEffect()
4829 */
4830 #ifndef QT_NO_GRAPHICSEFFECT
4831 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4832 {
4833     Q_D(QWidget);
4834     if (d->graphicsEffect == effect)
4835         return;
4836
4837     if (d->graphicsEffect) {
4838         d->invalidateBuffer(rect());
4839         delete d->graphicsEffect;
4840         d->graphicsEffect = 0;
4841     }
4842
4843     if (effect) {
4844         // Set new effect.
4845         QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4846         QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4847         d->graphicsEffect = effect;
4848         effect->d_func()->setGraphicsEffectSource(source);
4849         update();
4850     }
4851
4852     d->updateIsOpaque();
4853 }
4854 #endif //QT_NO_GRAPHICSEFFECT
4855
4856 bool QWidgetPrivate::isAboutToShow() const
4857 {
4858     if (data.in_show)
4859         return true;
4860
4861     Q_Q(const QWidget);
4862     if (q->isHidden())
4863         return false;
4864
4865     // The widget will be shown if any of its ancestors are about to show.
4866     QWidget *parent = q->parentWidget();
4867     return parent ? parent->d_func()->isAboutToShow() : false;
4868 }
4869
4870 QRegion QWidgetPrivate::prepareToRender(const QRegion &region, QWidget::RenderFlags renderFlags)
4871 {
4872     Q_Q(QWidget);
4873     const bool isVisible = q->isVisible();
4874
4875     // Make sure the widget is laid out correctly.
4876     if (!isVisible && !isAboutToShow()) {
4877         QWidget *topLevel = q->window();
4878         (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4879         topLevel->ensurePolished();
4880
4881         // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4882         // they're not explicitly hidden.
4883         QWidget *widget = q;
4884         QWidgetList hiddenWidgets;
4885         while (widget) {
4886             if (widget->isHidden()) {
4887                 widget->setAttribute(Qt::WA_WState_Hidden, false);
4888                 hiddenWidgets.append(widget);
4889                 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4890                     widget->d_func()->updateGeometry_helper(true);
4891             }
4892             widget = widget->parentWidget();
4893         }
4894
4895         // Activate top-level layout.
4896         if (topLevel->d_func()->layout)
4897             topLevel->d_func()->layout->activate();
4898
4899         // Adjust size if necessary.
4900         QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4901         if (topLevelExtra && !topLevelExtra->sizeAdjusted
4902             && !topLevel->testAttribute(Qt::WA_Resized)) {
4903             topLevel->adjustSize();
4904             topLevel->setAttribute(Qt::WA_Resized, false);
4905         }
4906
4907         // Activate child layouts.
4908         topLevel->d_func()->activateChildLayoutsRecursively();
4909
4910         // We're not cheating with WA_WState_Hidden anymore.
4911         for (int i = 0; i < hiddenWidgets.size(); ++i) {
4912             QWidget *widget = hiddenWidgets.at(i);
4913             widget->setAttribute(Qt::WA_WState_Hidden);
4914             if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4915                 widget->parentWidget()->d_func()->layout->invalidate();
4916         }
4917     } else if (isVisible) {
4918         q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
4919     }
4920
4921     // Calculate the region to be painted.
4922     QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
4923     if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
4924         toBePainted &= extra->mask;
4925     return toBePainted;
4926 }
4927
4928 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
4929                                    QWidget::RenderFlags renderFlags)
4930 {
4931     Q_ASSERT(painter);
4932     Q_ASSERT(!toBePainted.isEmpty());
4933
4934     Q_Q(QWidget);
4935 #ifndef Q_WS_MAC
4936     const QTransform originalTransform = painter->worldTransform();
4937     const bool useDeviceCoordinates = originalTransform.isScaling();
4938     if (!useDeviceCoordinates) {
4939 #endif
4940         // Render via a pixmap.
4941         const QRect rect = toBePainted.boundingRect();
4942         const QSize size = rect.size();
4943         if (size.isNull())
4944             return;
4945
4946         QPixmap pixmap(size);
4947         if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
4948             pixmap.fill(Qt::transparent);
4949         q->render(&pixmap, QPoint(), toBePainted, renderFlags);
4950
4951         const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
4952         painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
4953
4954         painter->drawPixmap(targetOffset, pixmap);
4955
4956         if (restore)
4957             painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
4958
4959 #ifndef Q_WS_MAC
4960     } else {
4961         // Render via a pixmap in device coordinates (to avoid pixmap scaling).
4962         QTransform transform = originalTransform;
4963         transform.translate(targetOffset.x(), targetOffset.y());
4964
4965         QPaintDevice *device = painter->device();
4966         Q_ASSERT(device);
4967
4968         // Calculate device rect.
4969         const QRectF rect(toBePainted.boundingRect());
4970         QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
4971         deviceRect &= QRect(0, 0, device->width(), device->height());
4972
4973         QPixmap pixmap(deviceRect.size());
4974         pixmap.fill(Qt::transparent);
4975
4976         // Create a pixmap device coordinate painter.
4977         QPainter pixmapPainter(&pixmap);
4978         pixmapPainter.setRenderHints(painter->renderHints());
4979         transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
4980         pixmapPainter.setTransform(transform);
4981
4982         q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
4983         pixmapPainter.end();
4984
4985         // And then draw the pixmap.
4986         painter->setTransform(QTransform());
4987         painter->drawPixmap(deviceRect.topLeft(), pixmap);
4988         painter->setTransform(originalTransform);
4989     }
4990 #endif
4991 }
4992
4993 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
4994                                 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
4995 {
4996     if (rgn.isEmpty())
4997         return;
4998
4999 #ifdef Q_WS_MAC
5000     if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5001         dirtyOnWidget = QRegion();
5002
5003     // We disable the rendering of QToolBar in the backingStore if
5004     // it's supposed to be in the unified toolbar on Mac OS X.
5005     if (backingStore && isInUnifiedToolbar)
5006         return;
5007 #endif // Q_WS_MAC
5008
5009
5010     Q_Q(QWidget);
5011 #ifndef QT_NO_GRAPHICSEFFECT
5012     if (graphicsEffect && graphicsEffect->isEnabled()) {
5013         QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5014         QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5015                                                          (source->d_func());
5016         if (!sourced->context) {
5017             QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5018             sourced->context = &context;
5019             if (!sharedPainter) {
5020                 setSystemClip(pdev, rgn.translated(offset));
5021                 QPainter p(pdev);
5022                 p.translate(offset);
5023                 context.painter = &p;
5024                 graphicsEffect->draw(&p);
5025                 setSystemClip(pdev, QRegion());
5026             } else {
5027                 context.painter = sharedPainter;
5028                 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5029                     sourced->invalidateCache();
5030                     sourced->lastEffectTransform = sharedPainter->worldTransform();
5031                 }
5032                 sharedPainter->save();
5033                 sharedPainter->translate(offset);
5034                 graphicsEffect->draw(sharedPainter);
5035                 sharedPainter->restore();
5036             }
5037             sourced->context = 0;
5038             return;
5039         }
5040     }
5041 #endif //QT_NO_GRAFFICSEFFECT
5042
5043     const bool asRoot = flags & DrawAsRoot;
5044     const bool alsoOnScreen = flags & DrawPaintOnScreen;
5045     const bool recursive = flags & DrawRecursive;
5046     const bool alsoInvisible = flags & DrawInvisible;
5047
5048     Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5049
5050     QRegion toBePainted(rgn);
5051     if (asRoot && !alsoInvisible)
5052         toBePainted &= clipRect(); //(rgn & visibleRegion());
5053     if (!(flags & DontSubtractOpaqueChildren))
5054         subtractOpaqueChildren(toBePainted, q->rect());
5055
5056     if (!toBePainted.isEmpty()) {
5057         bool onScreen = paintOnScreen();
5058         if (!onScreen || alsoOnScreen) {
5059             //update the "in paint event" flag
5060             if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5061                 qWarning("QWidget::repaint: Recursive repaint detected");
5062             q->setAttribute(Qt::WA_WState_InPaintEvent);
5063
5064             //clip away the new area
5065 #ifndef QT_NO_PAINT_DEBUG
5066             bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5067 #endif
5068             QPaintEngine *paintEngine = pdev->paintEngine();
5069             if (paintEngine) {
5070                 setRedirected(pdev, -offset);
5071
5072 #ifdef Q_WS_MAC
5073                 // (Alien support) Special case for Mac when redirecting: If the paint device
5074                 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5075                 // outside the paint event is not supported on QWidgets. The attributeis
5076                 // restored further down.
5077                 if (pdev->devType() == QInternal::Widget)
5078                     static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5079
5080 #endif
5081                 if (sharedPainter)
5082                     setSystemClip(pdev, toBePainted);
5083                 else
5084                     paintEngine->d_func()->systemRect = q->data->crect;
5085
5086                 //paint the background
5087                 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5088                     && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5089                     QPainter p(q);
5090                     paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5091                 }
5092
5093                 if (!sharedPainter)
5094                     setSystemClip(pdev, toBePainted.translated(offset));
5095
5096                 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5097                     QPainter p(q);
5098                     QColor tint = q->palette().window().color();
5099                     tint.setAlphaF(qreal(.6));
5100                     p.fillRect(toBePainted.boundingRect(), tint);
5101                 }
5102             }
5103
5104 #if 0
5105             qDebug() << "painting" << q << "opaque ==" << isOpaque();
5106             qDebug() << "clipping to" << toBePainted << "location == " << offset
5107                      << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5108 #endif
5109
5110             //actually send the paint event
5111             QPaintEvent e(toBePainted);
5112             QCoreApplication::sendSpontaneousEvent(q, &e);
5113
5114             // Native widgets need to be marked dirty on screen so painting will be done in correct context
5115             if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
5116                 backingStore->markDirtyOnScreen(toBePainted, q, offset);
5117
5118             //restore
5119             if (paintEngine) {
5120 #ifdef Q_WS_MAC
5121                 if (pdev->devType() == QInternal::Widget)
5122                     static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5123 #endif
5124                 restoreRedirected();
5125                 if (!sharedPainter)
5126                     paintEngine->d_func()->systemRect = QRect();
5127                 else
5128                     paintEngine->d_func()->currentClipDevice = 0;
5129
5130                 setSystemClip(pdev, QRegion());
5131             }
5132             q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5133             if (q->paintingActive())
5134                 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5135
5136             if (paintEngine && paintEngine->autoDestruct()) {
5137                 delete paintEngine;
5138             }
5139
5140 #ifndef QT_NO_PAINT_DEBUG
5141             if (flushed)
5142                 QWidgetBackingStore::unflushPaint(q, toBePainted);
5143 #endif
5144         } else if (q->isWindow()) {
5145             QPaintEngine *engine = pdev->paintEngine();
5146             if (engine) {
5147                 QPainter p(pdev);
5148                 p.setClipRegion(toBePainted);
5149                 const QBrush bg = q->palette().brush(QPalette::Window);
5150                 if (bg.style() == Qt::TexturePattern)
5151                     p.drawTiledPixmap(q->rect(), bg.texture());
5152                 else
5153                     p.fillRect(q->rect(), bg);
5154
5155                 if (engine->autoDestruct())
5156                     delete engine;
5157             }
5158         }
5159     }
5160
5161     if (recursive && !children.isEmpty()) {
5162         paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5163                                 , sharedPainter, backingStore);
5164     }
5165 }
5166
5167 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5168                             const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5169                             bool readyToRender)
5170 {
5171     if (!target) {
5172         qWarning("QWidget::render: null pointer to paint device");
5173         return;
5174     }
5175
5176     const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5177     QRegion paintRegion = !inRenderWithPainter && !readyToRender
5178                           ? prepareToRender(sourceRegion, renderFlags)
5179                           : sourceRegion;
5180     if (paintRegion.isEmpty())
5181         return;
5182
5183 #ifndef Q_WS_MAC
5184     QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5185
5186     // Use the target's shared painter if set (typically set when doing
5187     // "other->render(widget);" in the widget's paintEvent.
5188     if (target->devType() == QInternal::Widget) {
5189         QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5190         if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5191             QPainter *targetPainter = targetPrivate->sharedPainter();
5192             if (targetPainter && targetPainter->isActive())
5193                 setSharedPainter(targetPainter);
5194         }
5195     }
5196 #endif
5197
5198     // Use the target's redirected device if set and adjust offset and paint
5199     // region accordingly. This is typically the case when people call render
5200     // from the paintEvent.
5201     QPoint offset = targetOffset;
5202     offset -= paintRegion.boundingRect().topLeft();
5203     QPoint redirectionOffset;
5204     QPaintDevice *redirected = 0;
5205
5206     if (target->devType() == QInternal::Widget)
5207         redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5208     if (!redirected)
5209         redirected = QPainter::redirected(target, &redirectionOffset);
5210
5211     if (redirected) {
5212         target = redirected;
5213         offset -= redirectionOffset;
5214     }
5215
5216     if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5217         if (QPaintEngine *targetEngine = target->paintEngine()) {
5218             const QRegion targetSystemClip = targetEngine->systemClip();
5219             if (!targetSystemClip.isEmpty())
5220                 paintRegion &= targetSystemClip.translated(-offset);
5221         }
5222     }
5223
5224     // Set backingstore flags.
5225     int flags = DrawPaintOnScreen | DrawInvisible;
5226     if (renderFlags & QWidget::DrawWindowBackground)
5227         flags |= DrawAsRoot;
5228
5229     if (renderFlags & QWidget::DrawChildren)
5230         flags |= DrawRecursive;
5231     else
5232         flags |= DontSubtractOpaqueChildren;
5233
5234     flags |= DontSetCompositionMode;
5235
5236     if (target->devType() == QInternal::Printer) {
5237         QPainter p(target);
5238         render_helper(&p, targetOffset, paintRegion, renderFlags);
5239         return;
5240     }
5241
5242 #ifndef Q_WS_MAC
5243     // Render via backingstore.
5244     drawWidget(target, paintRegion, offset, flags, sharedPainter());
5245
5246     // Restore shared painter.
5247     if (oldSharedPainter)
5248         setSharedPainter(oldSharedPainter);
5249 #else
5250     // Render via backingstore (no shared painter).
5251     drawWidget(target, paintRegion, offset, flags, 0);
5252 #endif
5253 }
5254
5255 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5256                                             const QPoint &offset, int flags
5257                                             , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5258 {
5259     QWidget *w = 0;
5260     QRect boundingRect;
5261     bool dirtyBoundingRect = true;
5262     const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5263     const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5264
5265     do {
5266         QWidget *x =  qobject_cast<QWidget*>(siblings.at(index));
5267         if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5268             && !(excludeNativeChildren && x->internalWinId())) {
5269             if (dirtyBoundingRect) {
5270                 boundingRect = rgn.boundingRect();
5271                 dirtyBoundingRect = false;
5272             }
5273
5274             if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5275                 w = x;
5276                 break;
5277             }
5278         }
5279         --index;
5280     } while (index >= 0);
5281
5282     if (!w)
5283         return;
5284
5285     QWidgetPrivate *wd = w->d_func();
5286     const QPoint widgetPos(w->data->crect.topLeft());
5287     const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5288     if (index > 0) {
5289         QRegion wr(rgn);
5290         if (wd->isOpaque)
5291             wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5292         paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5293                                , sharedPainter, backingStore);
5294     }
5295
5296     if (w->updatesEnabled()
5297 #ifndef QT_NO_GRAPHICSVIEW
5298             && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5299 #endif //QT_NO_GRAPHICSVIEW
5300        ) {
5301         QRegion wRegion(rgn);
5302         wRegion &= wd->effectiveRectFor(w->data->crect);
5303         wRegion.translate(-widgetPos);
5304         if (hasMask)
5305             wRegion &= wd->extra->mask;
5306         wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5307     }
5308 }
5309
5310 #ifndef QT_NO_GRAPHICSEFFECT
5311 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5312 {
5313     if (system != Qt::DeviceCoordinates)
5314         return m_widget->rect();
5315
5316     if (!context) {
5317         // Device coordinates without context not yet supported.
5318         qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5319         return QRectF();
5320     }
5321
5322     return context->painter->worldTransform().mapRect(m_widget->rect());
5323 }
5324
5325 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5326 {
5327     if (!context || context->painter != painter) {
5328         m_widget->render(painter);
5329         return;
5330     }
5331
5332     // The region saved in the context is neither clipped to the rect
5333     // nor the mask, so we have to clip it here before calling drawWidget.
5334     QRegion toBePainted = context->rgn;
5335     toBePainted &= m_widget->rect();
5336     QWidgetPrivate *wd = qt_widget_private(m_widget);
5337     if (wd->extra && wd->extra->hasMask)
5338         toBePainted &= wd->extra->mask;
5339
5340     wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5341                    context->sharedPainter, context->backingStore);
5342 }
5343
5344 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5345                                            QGraphicsEffect::PixmapPadMode mode) const
5346 {
5347     const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5348     if (!context && deviceCoordinates) {
5349         // Device coordinates without context not yet supported.
5350         qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5351         return QPixmap();
5352     }
5353
5354     QPoint pixmapOffset;
5355     QRectF sourceRect = m_widget->rect();
5356
5357     if (deviceCoordinates) {
5358         const QTransform &painterTransform = context->painter->worldTransform();
5359         sourceRect = painterTransform.mapRect(sourceRect);
5360         pixmapOffset = painterTransform.map(pixmapOffset);
5361     }
5362
5363     QRect effectRect;
5364
5365     if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5366         effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5367     else if (mode == QGraphicsEffect::PadToTransparentBorder)
5368         effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5369     else
5370         effectRect = sourceRect.toAlignedRect();
5371
5372     if (offset)
5373         *offset = effectRect.topLeft();
5374
5375     pixmapOffset -= effectRect.topLeft();
5376
5377     QPixmap pixmap(effectRect.size());
5378     pixmap.fill(Qt::transparent);
5379     m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5380     return pixmap;
5381 }
5382 #endif //QT_NO_GRAPHICSEFFECT
5383
5384 #ifndef QT_NO_GRAPHICSVIEW
5385 /*!
5386     \internal
5387
5388     Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5389     widget and its ancestors. The search starts at \a origin (inclusive).
5390     If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5391     widget was found.
5392 */
5393 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5394 {
5395     if (origin) {
5396         QWExtra *extra = origin->d_func()->extra;
5397         if (extra && extra->proxyWidget)
5398             return extra->proxyWidget;
5399         return nearestGraphicsProxyWidget(origin->parentWidget());
5400     }
5401     return 0;
5402 }
5403 #endif
5404
5405 /*!
5406     \property QWidget::locale
5407     \brief the widget's locale
5408     \since 4.3
5409
5410     As long as no special locale has been set, this is either
5411     the parent's locale or (if this widget is a top level widget),
5412     the default locale.
5413
5414     If the widget displays dates or numbers, these should be formatted
5415     using the widget's locale.
5416
5417     \sa QLocale, QLocale::setDefault()
5418 */
5419
5420 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5421 {
5422     Q_Q(QWidget);
5423     if (locale == loc && !forceUpdate)
5424         return;
5425
5426     locale = loc;
5427
5428     if (!children.isEmpty()) {
5429         for (int i = 0; i < children.size(); ++i) {
5430             QWidget *w = qobject_cast<QWidget*>(children.at(i));
5431             if (!w)
5432                 continue;
5433             if (w->testAttribute(Qt::WA_SetLocale))
5434                 continue;
5435             if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5436                 continue;
5437             w->d_func()->setLocale_helper(loc, forceUpdate);
5438         }
5439     }
5440     QEvent e(QEvent::LocaleChange);
5441     QApplication::sendEvent(q, &e);
5442 }
5443
5444 void QWidget::setLocale(const QLocale &locale)
5445 {
5446     Q_D(QWidget);
5447
5448     setAttribute(Qt::WA_SetLocale);
5449     d->setLocale_helper(locale);
5450 }
5451
5452 QLocale QWidget::locale() const
5453 {
5454     Q_D(const QWidget);
5455
5456     return d->locale;
5457 }
5458
5459 void QWidgetPrivate::resolveLocale()
5460 {
5461     Q_Q(const QWidget);
5462
5463     if (!q->testAttribute(Qt::WA_SetLocale)) {
5464         setLocale_helper(q->isWindow()
5465                             ? QLocale()
5466                             : q->parentWidget()->locale());
5467     }
5468 }
5469
5470 void QWidget::unsetLocale()
5471 {
5472     Q_D(QWidget);
5473     setAttribute(Qt::WA_SetLocale, false);
5474     d->resolveLocale();
5475 }
5476
5477 static QString constructWindowTitleFromFilePath(const QString &filePath)
5478 {
5479     QFileInfo fi(filePath);
5480     QString windowTitle = fi.fileName() + QLatin1String("[*]");
5481 #ifndef Q_WS_MAC
5482     QString appName = QApplication::applicationName();
5483     if (!appName.isEmpty())
5484         windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5485 #endif
5486     return windowTitle;
5487 }
5488
5489 /*!
5490     \property QWidget::windowTitle
5491     \brief the window title (caption)
5492
5493     This property only makes sense for top-level widgets, such as
5494     windows and dialogs. If no caption has been set, the title is based of the
5495     \l windowFilePath. If neither of these is set, then the title is
5496     an empty string.
5497
5498     If you use the \l windowModified mechanism, the window title must
5499     contain a "[*]" placeholder, which indicates where the '*' should
5500     appear. Normally, it should appear right after the file name
5501     (e.g., "document1.txt[*] - Text Editor"). If the \l
5502     windowModified property is false (the default), the placeholder
5503     is simply removed.
5504
5505     \sa windowIcon, windowIconText, windowModified, windowFilePath
5506 */
5507 QString QWidget::windowTitle() const
5508 {
5509     Q_D(const QWidget);
5510     if (d->extra && d->extra->topextra) {
5511         if (!d->extra->topextra->caption.isEmpty())
5512             return d->extra->topextra->caption;
5513         if (!d->extra->topextra->filePath.isEmpty())
5514             return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5515     }
5516     return QString();
5517 }
5518
5519 /*!
5520     Returns a modified window title with the [*] place holder
5521     replaced according to the rules described in QWidget::setWindowTitle
5522
5523     This function assumes that "[*]" can be quoted by another
5524     "[*]", so it will replace two place holders by one and
5525     a single last one by either "*" or nothing depending on
5526     the modified flag.
5527
5528     \internal
5529 */
5530 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5531 {
5532     Q_ASSERT(widget);
5533
5534 #ifdef QT_EVAL
5535     extern QString qt_eval_adapt_window_title(const QString &title);
5536     QString cap = qt_eval_adapt_window_title(title);
5537 #else
5538     QString cap = title;
5539 #endif
5540
5541     if (cap.isEmpty())
5542         return cap;
5543
5544     QLatin1String placeHolder("[*]");
5545     int index = cap.indexOf(placeHolder);
5546
5547     // here the magic begins
5548     while (index != -1) {
5549         index += placeHolder.size();
5550         int count = 1;
5551         while (cap.indexOf(placeHolder, index) == index) {
5552             ++count;
5553             index += placeHolder.size();
5554         }
5555
5556         if (count%2) { // odd number of [*] -> replace last one
5557             int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5558             if (widget->isWindowModified()
5559              && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5560                 cap.replace(lastIndex, 3, QWidget::tr("*"));
5561             else
5562                 cap.remove(lastIndex, 3);
5563         }
5564
5565         index = cap.indexOf(placeHolder, index);
5566     }
5567
5568     cap.replace(QLatin1String("[*][*]"), placeHolder);
5569
5570     return cap;
5571 }
5572
5573 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5574 {
5575     Q_Q(QWidget);
5576     if (q->testAttribute(Qt::WA_WState_Created))
5577         setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5578 }
5579
5580 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5581 {
5582     Q_Q(QWidget);
5583     if (q->testAttribute(Qt::WA_WState_Created))
5584         setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5585 }
5586
5587 void QWidget::setWindowIconText(const QString &iconText)
5588 {
5589     if (QWidget::windowIconText() == iconText)
5590         return;
5591
5592     Q_D(QWidget);
5593     d->topData()->iconText = iconText;
5594     d->setWindowIconText_helper(iconText);
5595
5596     QEvent e(QEvent::IconTextChange);
5597     QApplication::sendEvent(this, &e);
5598 }
5599
5600 void QWidget::setWindowTitle(const QString &title)
5601 {
5602     if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5603         return;
5604
5605     Q_D(QWidget);
5606     d->topData()->caption = title;
5607     d->setWindowTitle_helper(title);
5608
5609     QEvent e(QEvent::WindowTitleChange);
5610     QApplication::sendEvent(this, &e);
5611 }
5612
5613
5614 /*!
5615     \property QWidget::windowIcon
5616     \brief the widget's icon
5617
5618     This property only makes sense for windows. If no icon
5619     has been set, windowIcon() returns the application icon
5620     (QApplication::windowIcon()).
5621
5622     \sa windowIconText, windowTitle
5623 */
5624 QIcon QWidget::windowIcon() const
5625 {
5626     const QWidget *w = this;
5627     while (w) {
5628         const QWidgetPrivate *d = w->d_func();
5629         if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5630             return *d->extra->topextra->icon;
5631         w = w->parentWidget();
5632     }
5633     return QApplication::windowIcon();
5634 }
5635
5636 void QWidgetPrivate::setWindowIcon_helper()
5637 {
5638     QEvent e(QEvent::WindowIconChange);
5639     QApplication::sendEvent(q_func(), &e);
5640     for (int i = 0; i < children.size(); ++i) {
5641         QWidget *w = qobject_cast<QWidget *>(children.at(i));
5642         if (w && !w->isWindow())
5643             QApplication::sendEvent(w, &e);
5644     }
5645 }
5646
5647 void QWidget::setWindowIcon(const QIcon &icon)
5648 {
5649     Q_D(QWidget);
5650
5651     setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5652     d->createTLExtra();
5653
5654     if (!d->extra->topextra->icon)
5655         d->extra->topextra->icon = new QIcon();
5656     *d->extra->topextra->icon = icon;
5657
5658     d->setWindowIcon_sys();
5659     d->setWindowIcon_helper();
5660 }
5661
5662
5663 /*!
5664     \property QWidget::windowIconText
5665     \brief the widget's icon text
5666
5667     This property only makes sense for windows. If no icon
5668     text has been set, this functions returns an empty string.
5669
5670     \sa windowIcon, windowTitle
5671 */
5672
5673 QString QWidget::windowIconText() const
5674 {
5675     Q_D(const QWidget);
5676     return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5677 }
5678
5679 /*!
5680     \property QWidget::windowFilePath
5681     \since 4.4
5682     \brief the file path associated with a widget
5683
5684     This property only makes sense for windows. It associates a file path with
5685     a window. If you set the file path, but have not set the window title, Qt
5686     sets the window title to contain a string created using the following
5687     components.
5688
5689     On Mac OS X:
5690
5691     \list
5692     \li The file name of the specified path, obtained using QFileInfo::fileName().
5693     \endlist
5694
5695     On Windows and X11:
5696
5697     \list
5698     \li The file name of the specified path, obtained using QFileInfo::fileName().
5699     \li An optional \c{*} character, if the \l windowModified property is set.
5700     \li The \c{0x2014} unicode character, padded either side by spaces.
5701     \li The application name, obtained from the application's
5702     \l{QCoreApplication::}{applicationName} property.
5703     \endlist
5704
5705     If the window title is set at any point, then the window title takes precedence and
5706     will be shown instead of the file path string.
5707
5708     Additionally, on Mac OS X, this has an added benefit that it sets the
5709     \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5710     for the window, assuming that the file path exists.
5711
5712     If no file path is set, this property contains an empty string.
5713
5714     By default, this property contains an empty string.
5715
5716     \sa windowTitle, windowIcon
5717 */
5718
5719 QString QWidget::windowFilePath() const
5720 {
5721     Q_D(const QWidget);
5722     return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5723 }
5724
5725 void QWidget::setWindowFilePath(const QString &filePath)
5726 {
5727     if (filePath == windowFilePath())
5728         return;
5729
5730     Q_D(QWidget);
5731
5732     d->createTLExtra();
5733     d->extra->topextra->filePath = filePath;
5734     d->setWindowFilePath_helper(filePath);
5735 }
5736
5737 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5738 {
5739     if (extra->topextra && extra->topextra->caption.isEmpty()) {
5740 #ifdef Q_OS_MAC
5741         setWindowTitle_helper(QFileInfo(filePath).fileName());
5742 #else
5743         Q_Q(QWidget);
5744         Q_UNUSED(filePath);
5745         setWindowTitle_helper(q->windowTitle());
5746 #endif
5747     }
5748 #ifdef Q_OS_MAC
5749     setWindowFilePath_sys(filePath);
5750 #endif
5751 }
5752
5753 /*!
5754     Returns the window's role, or an empty string.
5755
5756     \sa windowIcon, windowTitle
5757 */
5758
5759 QString QWidget::windowRole() const
5760 {
5761     Q_D(const QWidget);
5762     return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5763 }
5764
5765 /*!
5766     Sets the window's role to \a role. This only makes sense for
5767     windows on X11.
5768 */
5769 void QWidget::setWindowRole(const QString &role)
5770 {
5771 #if defined(Q_WS_X11)
5772     Q_D(QWidget);
5773     d->topData()->role = role;
5774     d->setWindowRole();
5775 #else
5776     Q_UNUSED(role)
5777 #endif
5778 }
5779
5780 /*!
5781     \property QWidget::mouseTracking
5782     \brief whether mouse tracking is enabled for the widget
5783
5784     If mouse tracking is disabled (the default), the widget only
5785     receives mouse move events when at least one mouse button is
5786     pressed while the mouse is being moved.
5787
5788     If mouse tracking is enabled, the widget receives mouse move
5789     events even if no buttons are pressed.
5790
5791     \sa mouseMoveEvent()
5792 */
5793
5794
5795 /*!
5796     Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5797     function resets this widget to have no focus proxy.
5798
5799     Some widgets can "have focus", but create a child widget, such as
5800     QLineEdit, to actually handle the focus. In this case, the widget
5801     can set the line edit to be its focus proxy.
5802
5803     setFocusProxy() sets the widget which will actually get focus when
5804     "this widget" gets it. If there is a focus proxy, setFocus() and
5805     hasFocus() operate on the focus proxy.
5806
5807     \sa focusProxy()
5808 */
5809
5810 void QWidget::setFocusProxy(QWidget * w)
5811 {
5812     Q_D(QWidget);
5813     if (!w && !d->extra)
5814         return;
5815
5816     for (QWidget* fp  = w; fp; fp = fp->focusProxy()) {
5817         if (fp == this) {
5818             qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5819             return;
5820         }
5821     }
5822
5823     d->createExtra();
5824     d->extra->focus_proxy = w;
5825 }
5826
5827
5828 /*!
5829     Returns the focus proxy, or 0 if there is no focus proxy.
5830
5831     \sa setFocusProxy()
5832 */
5833
5834 QWidget * QWidget::focusProxy() const
5835 {
5836     Q_D(const QWidget);
5837     return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5838 }
5839
5840
5841 /*!
5842     \property QWidget::focus
5843     \brief whether this widget (or its focus proxy) has the keyboard
5844     input focus
5845
5846     By default, this property is false.
5847
5848     \note Obtaining the value of this property for a widget is effectively equivalent
5849     to checking whether QApplication::focusWidget() refers to the widget.
5850
5851     \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5852 */
5853 bool QWidget::hasFocus() const
5854 {
5855     const QWidget* w = this;
5856     while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5857         w = w->d_func()->extra->focus_proxy;
5858     if (QWidget *window = w->window()) {
5859 #ifndef QT_NO_GRAPHICSVIEW
5860         QWExtra *e = window->d_func()->extra;
5861         if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5862             return true;
5863 #endif
5864     }
5865     return (QApplication::focusWidget() == w);
5866 }
5867
5868 /*!
5869     Gives the keyboard input focus to this widget (or its focus
5870     proxy) if this widget or one of its parents is the \l{isActiveWindow()}{active window}. The \a reason argument will
5871     be passed into any focus event sent from this function, it is used
5872     to give an explanation of what caused the widget to get focus.
5873     If the window is not active, the widget will be given the focus when
5874     the window becomes active.
5875
5876     First, a focus about to change event is sent to the focus widget (if any) to
5877     tell it that it is about to lose the focus. Then focus is changed, a
5878     focus out event is sent to the previous focus item and a focus in event is sent
5879     to the new item to tell it that it just received the focus.
5880     (Nothing happens if the focus in and focus out widgets are the
5881     same.)
5882
5883     \note On embedded platforms, setFocus() will not cause an input panel
5884     to be opened by the input method. If you want this to happen, you
5885     have to send a QEvent::RequestSoftwareInputPanel event to the
5886     widget yourself.
5887
5888     setFocus() gives focus to a widget regardless of its focus policy,
5889     but does not clear any keyboard grab (see grabKeyboard()).
5890
5891     Be aware that if the widget is hidden, it will not accept focus
5892     until it is shown.
5893
5894     \warning If you call setFocus() in a function which may itself be
5895     called from focusOutEvent() or focusInEvent(), you may get an
5896     infinite recursion.
5897
5898     \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5899     setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5900     grabMouse(), {Keyboard Focus in Widgets}, QEvent::RequestSoftwareInputPanel
5901 */
5902
5903 void QWidget::setFocus(Qt::FocusReason reason)
5904 {
5905     if (!isEnabled())
5906         return;
5907
5908     QWidget *f = this;
5909     while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5910         f = f->d_func()->extra->focus_proxy;
5911
5912     if (QApplication::focusWidget() == f
5913 #if defined(Q_WS_WIN)
5914         && GetFocus() == f->internalWinId()
5915 #endif
5916        )
5917         return;
5918
5919 #ifndef QT_NO_GRAPHICSVIEW
5920     QWidget *previousProxyFocus = 0;
5921     if (QWExtra *topData = window()->d_func()->extra) {
5922         if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5923             previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5924             if (previousProxyFocus && previousProxyFocus->focusProxy())
5925                 previousProxyFocus = previousProxyFocus->focusProxy();
5926             if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
5927                 return;
5928         }
5929     }
5930 #endif
5931
5932 #ifndef QT_NO_GRAPHICSVIEW
5933     // Update proxy state
5934     if (QWExtra *topData = window()->d_func()->extra) {
5935         if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
5936             f->d_func()->updateFocusChild();
5937             topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
5938             topData->proxyWidget->setFocus(reason);
5939             topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
5940         }
5941     }
5942 #endif
5943
5944     if (f->isActiveWindow()) {
5945         QWidget *prev = QApplicationPrivate::focus_widget;
5946         if (prev) {
5947             if (reason != Qt::PopupFocusReason && reason != Qt::MenuBarFocusReason
5948                 && prev->testAttribute(Qt::WA_InputMethodEnabled)) {
5949                 qApp->inputMethod()->commit();
5950             }
5951
5952             if (reason != Qt::NoFocusReason) {
5953                 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, reason);
5954                 QApplication::sendEvent(prev, &focusAboutToChange);
5955             }
5956         }
5957
5958         f->d_func()->updateFocusChild();
5959
5960         QApplicationPrivate::setFocusWidget(f, reason);
5961 #ifndef QT_NO_ACCESSIBILITY
5962 # ifdef Q_OS_WIN
5963         // The negation of the condition in setFocus_sys
5964         if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
5965             //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
5966 # endif
5967 # ifdef  Q_OS_UNIX
5968         // menus update the focus manually and this would create bogus events
5969         if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
5970 # endif
5971         {
5972             QAccessibleEvent event(f, QAccessible::Focus);
5973             QAccessible::updateAccessibility(&event);
5974         }
5975 #endif
5976 #ifndef QT_NO_GRAPHICSVIEW
5977         if (QWExtra *topData = window()->d_func()->extra) {
5978             if (topData->proxyWidget) {
5979                 if (previousProxyFocus && previousProxyFocus != f) {
5980                     // Send event to self
5981                     QFocusEvent event(QEvent::FocusOut, reason);
5982                     QPointer<QWidget> that = previousProxyFocus;
5983                     QApplication::sendEvent(previousProxyFocus, &event);
5984                     if (that)
5985                         QApplication::sendEvent(that->style(), &event);
5986                 }
5987                 if (!isHidden()) {
5988 #ifndef QT_NO_GRAPHICSVIEW
5989                     // Update proxy state
5990                     if (QWExtra *topData = window()->d_func()->extra)
5991                         if (topData->proxyWidget && topData->proxyWidget->hasFocus())
5992                             topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
5993 #endif
5994                     // Send event to self
5995                     QFocusEvent event(QEvent::FocusIn, reason);
5996                     QPointer<QWidget> that = f;
5997                     QApplication::sendEvent(f, &event);
5998                     if (that)
5999                         QApplication::sendEvent(that->style(), &event);
6000                 }
6001             }
6002         }
6003 #endif
6004     } else {
6005         f->d_func()->updateFocusChild();
6006     }
6007
6008     if (QTLWExtra *extra = f->window()->d_func()->maybeTopData()) {
6009         if (extra->window)
6010             emit extra->window->focusObjectChanged(f);
6011     }
6012 }
6013
6014 // updates focus_child on parent widgets to point into this widget
6015 void QWidgetPrivate::updateFocusChild()
6016 {
6017     Q_Q(QWidget);
6018
6019     QWidget *w = q;
6020     if (q->isHidden()) {
6021         while (w && w->isHidden()) {
6022             w->d_func()->focus_child = q;
6023             w = w->isWindow() ? 0 : w->parentWidget();
6024         }
6025     } else {
6026         while (w) {
6027             w->d_func()->focus_child = q;
6028             w = w->isWindow() ? 0 : w->parentWidget();
6029         }
6030     }
6031 }
6032
6033 /*!
6034     \fn void QWidget::setFocus()
6035     \overload
6036
6037     Gives the keyboard input focus to this widget (or its focus
6038     proxy) if this widget or one of its parents is the
6039     \l{isActiveWindow()}{active window}.
6040 */
6041
6042 /*!
6043     Takes keyboard input focus from the widget.
6044
6045     If the widget has active focus, a \l{focusOutEvent()}{focus out event} is sent to this widget to tell it that it has
6046     lost the focus.
6047
6048     This widget must enable focus setting in order to get the keyboard
6049     input focus, i.e. it must call setFocusPolicy().
6050
6051     \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6052     setFocusPolicy(), QApplication::focusWidget()
6053 */
6054
6055 void QWidget::clearFocus()
6056 {
6057     if (hasFocus()) {
6058         if (testAttribute(Qt::WA_InputMethodEnabled))
6059             qApp->inputMethod()->commit();
6060
6061         QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange);
6062         QApplication::sendEvent(this, &focusAboutToChange);
6063     }
6064
6065     QWidget *w = this;
6066     while (w) {
6067         if (w->d_func()->focus_child == this)
6068             w->d_func()->focus_child = 0;
6069         w = w->parentWidget();
6070     }
6071 #ifndef QT_NO_GRAPHICSVIEW
6072     QWExtra *topData = d_func()->extra;
6073     if (topData && topData->proxyWidget)
6074         topData->proxyWidget->clearFocus();
6075 #endif
6076
6077     if (hasFocus()) {
6078         // Update proxy state
6079         QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6080 #if defined(Q_WS_WIN)
6081         if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6082             SetFocus(0);
6083         else
6084 #endif
6085         {
6086 #ifndef QT_NO_ACCESSIBILITY
6087             QAccessibleEvent event(this, QAccessible::Focus);
6088             QAccessible::updateAccessibility(&event);
6089 #endif
6090         }
6091     }
6092 }
6093
6094
6095 /*!
6096     \fn bool QWidget::focusNextChild()
6097
6098     Finds a new widget to give the keyboard focus to, as appropriate
6099     for \uicontrol Tab, and returns true if it can find a new widget, or
6100     false if it can't.
6101
6102     \sa focusPreviousChild()
6103 */
6104
6105 /*!
6106     \fn bool QWidget::focusPreviousChild()
6107
6108     Finds a new widget to give the keyboard focus to, as appropriate
6109     for \uicontrol Shift+Tab, and returns true if it can find a new widget,
6110     or false if it can't.
6111
6112     \sa focusNextChild()
6113 */
6114
6115 /*!
6116     Finds a new widget to give the keyboard focus to, as appropriate
6117     for Tab and Shift+Tab, and returns true if it can find a new
6118     widget, or false if it can't.
6119
6120     If \a next is true, this function searches forward, if \a next
6121     is false, it searches backward.
6122
6123     Sometimes, you will want to reimplement this function. For
6124     example, a web browser might reimplement it to move its "current
6125     active link" forward or backward, and call
6126     focusNextPrevChild() only when it reaches the last or
6127     first link on the "page".
6128
6129     Child widgets call focusNextPrevChild() on their parent widgets,
6130     but only the window that contains the child widgets decides where
6131     to redirect focus. By reimplementing this function for an object,
6132     you thus gain control of focus traversal for all child widgets.
6133
6134     \sa focusNextChild(), focusPreviousChild()
6135 */
6136
6137 bool QWidget::focusNextPrevChild(bool next)
6138 {
6139     Q_D(QWidget);
6140     QWidget* p = parentWidget();
6141     bool isSubWindow = (windowType() == Qt::SubWindow);
6142     if (!isWindow() && !isSubWindow && p)
6143         return p->focusNextPrevChild(next);
6144 #ifndef QT_NO_GRAPHICSVIEW
6145     if (d->extra && d->extra->proxyWidget)
6146         return d->extra->proxyWidget->focusNextPrevChild(next);
6147 #endif
6148     QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6149     if (!w) return false;
6150
6151     w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6152     return true;
6153 }
6154
6155 /*!
6156     Returns the last child of this widget that setFocus had been
6157     called on.  For top level widgets this is the widget that will get
6158     focus in case this window gets activated
6159
6160     This is not the same as QApplication::focusWidget(), which returns
6161     the focus widget in the currently active window.
6162 */
6163
6164 QWidget *QWidget::focusWidget() const
6165 {
6166     return const_cast<QWidget *>(d_func()->focus_child);
6167 }
6168
6169 /*!
6170     Returns the next widget in this widget's focus chain.
6171
6172     \sa previousInFocusChain()
6173 */
6174 QWidget *QWidget::nextInFocusChain() const
6175 {
6176     return const_cast<QWidget *>(d_func()->focus_next);
6177 }
6178
6179 /*!
6180     \brief The previousInFocusChain function returns the previous
6181     widget in this widget's focus chain.
6182
6183     \sa nextInFocusChain()
6184
6185     \since 4.6
6186 */
6187 QWidget *QWidget::previousInFocusChain() const
6188 {
6189     return const_cast<QWidget *>(d_func()->focus_prev);
6190 }
6191
6192 /*!
6193     \property QWidget::isActiveWindow
6194     \brief whether this widget's window is the active window
6195
6196     The active window is the window that contains the widget that has
6197     keyboard focus (The window may still have focus if it has no
6198     widgets or none of its widgets accepts keyboard focus).
6199
6200     When popup windows are visible, this property is true for both the
6201     active window \e and for the popup.
6202
6203     By default, this property is false.
6204
6205     \sa activateWindow(), QApplication::activeWindow()
6206 */
6207 bool QWidget::isActiveWindow() const
6208 {
6209     QWidget *tlw = window();
6210     if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6211         return true;
6212
6213 #ifndef QT_NO_GRAPHICSVIEW
6214     if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6215         if (isVisible() && tlwExtra->proxyWidget)
6216             return tlwExtra->proxyWidget->isActiveWindow();
6217     }
6218 #endif
6219
6220     if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6221         if(tlw->windowType() == Qt::Tool &&
6222            !tlw->isModal() &&
6223            (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6224            return true;
6225         QWidget *w = QApplication::activeWindow();
6226         while(w && tlw->windowType() == Qt::Tool &&
6227               !w->isModal() && w->parentWidget()) {
6228             w = w->parentWidget()->window();
6229             if(w == tlw)
6230                 return true;
6231         }
6232     }
6233
6234     // Check if platform adaptation thinks the window is active. This is necessary for
6235     // example in case of ActiveQt servers that are embedded into another application.
6236     // Those are separate processes that are not part of the parent application Qt window/widget
6237     // hierarchy, so they need to rely on native methods to determine if they are part of the
6238     // active window.
6239     if (const QWindow *w = tlw->windowHandle()) {
6240         if (w->handle())
6241             return w->handle()->isActive();
6242     }
6243
6244     return false;
6245 }
6246
6247 /*!
6248     Puts the \a second widget after the \a first widget in the focus order.
6249
6250     Note that since the tab order of the \a second widget is changed, you
6251     should order a chain like this:
6252
6253     \snippet code/src_gui_kernel_qwidget.cpp 9
6254
6255     \e not like this:
6256
6257     \snippet code/src_gui_kernel_qwidget.cpp 10
6258
6259     If \a first or \a second has a focus proxy, setTabOrder()
6260     correctly substitutes the proxy.
6261
6262     \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus in Widgets}
6263 */
6264 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6265 {
6266     if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6267         return;
6268
6269     if (first->window() != second->window()) {
6270         qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6271         return;
6272     }
6273
6274     QWidget *fp = first->focusProxy();
6275     if (fp) {
6276         // If first is redirected, set first to the last child of first
6277         // that can take keyboard focus so that second is inserted after
6278         // that last child, and the focus order within first is (more
6279         // likely to be) preserved.
6280         QList<QWidget *> l = first->findChildren<QWidget *>();
6281         for (int i = l.size()-1; i >= 0; --i) {
6282             QWidget * next = l.at(i);
6283             if (next->window() == fp->window()) {
6284                 fp = next;
6285                 if (fp->focusPolicy() != Qt::NoFocus)
6286                     break;
6287             }
6288         }
6289         first = fp;
6290     }
6291
6292     if (fp == second)
6293         return;
6294
6295     if (QWidget *sp = second->focusProxy())
6296         second = sp;
6297
6298 //    QWidget *fp = first->d_func()->focus_prev;
6299     QWidget *fn = first->d_func()->focus_next;
6300
6301     if (fn == second || first == second)
6302         return;
6303
6304     QWidget *sp = second->d_func()->focus_prev;
6305     QWidget *sn = second->d_func()->focus_next;
6306
6307     fn->d_func()->focus_prev = second;
6308     first->d_func()->focus_next = second;
6309
6310     second->d_func()->focus_next = fn;
6311     second->d_func()->focus_prev = first;
6312
6313     sp->d_func()->focus_next = sn;
6314     sn->d_func()->focus_prev = sp;
6315
6316
6317     Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6318     Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6319
6320     Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6321     Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6322 }
6323
6324 /*!\internal
6325
6326   Moves the relevant subwidgets of this widget from the \a oldtlw's
6327   tab chain to that of the new parent, if there's anything to move and
6328   we're really moving
6329
6330   This function is called from QWidget::reparent() *after* the widget
6331   has been reparented.
6332
6333   \sa reparent()
6334 */
6335
6336 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6337 {
6338     Q_Q(QWidget);
6339     if (oldtlw == q->window())
6340         return; // nothing to do
6341
6342     if(focus_child)
6343         focus_child->clearFocus();
6344
6345     // separate the focus chain into new (children of myself) and old (the rest)
6346     QWidget *firstOld = 0;
6347     //QWidget *firstNew = q; //invariant
6348     QWidget *o = 0; // last in the old list
6349     QWidget *n = q; // last in the new list
6350
6351     bool prevWasNew = true;
6352     QWidget *w = focus_next;
6353
6354     //Note: for efficiency, we do not maintain the list invariant inside the loop
6355     //we append items to the relevant list, and we optimize by not changing pointers
6356     //when subsequent items are going into the same list.
6357     while (w  != q) {
6358         bool currentIsNew =  q->isAncestorOf(w);
6359         if (currentIsNew) {
6360             if (!prevWasNew) {
6361                 //prev was old -- append to new list
6362                 n->d_func()->focus_next = w;
6363                 w->d_func()->focus_prev = n;
6364             }
6365             n = w;
6366         } else {
6367             if (prevWasNew) {
6368                 //prev was new -- append to old list, if there is one
6369                 if (o) {
6370                     o->d_func()->focus_next = w;
6371                     w->d_func()->focus_prev = o;
6372                 } else {
6373                     // "create" the old list
6374                     firstOld = w;
6375                 }
6376             }
6377             o = w;
6378         }
6379         w = w->d_func()->focus_next;
6380         prevWasNew = currentIsNew;
6381     }
6382
6383     //repair the old list:
6384     if (firstOld) {
6385         o->d_func()->focus_next = firstOld;
6386         firstOld->d_func()->focus_prev = o;
6387     }
6388
6389     if (!q->isWindow()) {
6390         QWidget *topLevel = q->window();
6391         //insert new chain into toplevel's chain
6392
6393         QWidget *prev = topLevel->d_func()->focus_prev;
6394
6395         topLevel->d_func()->focus_prev = n;
6396         prev->d_func()->focus_next = q;
6397
6398         focus_prev = prev;
6399         n->d_func()->focus_next = topLevel;
6400     } else {
6401         //repair the new list
6402             n->d_func()->focus_next = q;
6403             focus_prev = n;
6404     }
6405
6406 }
6407
6408 /*!\internal
6409
6410   Measures the shortest distance from a point to a rect.
6411
6412   This function is called from QDesktopwidget::screen(QPoint) to find the
6413   closest screen for a point.
6414   In directional KeypadNavigation, it is called to find the closest
6415   widget to the current focus widget center.
6416 */
6417 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6418 {
6419     int dx = 0;
6420     int dy = 0;
6421     if (p.x() < r.left())
6422         dx = r.left() - p.x();
6423     else if (p.x() > r.right())
6424         dx = p.x() - r.right();
6425     if (p.y() < r.top())
6426         dy = r.top() - p.y();
6427     else if (p.y() > r.bottom())
6428         dy = p.y() - r.bottom();
6429     return dx + dy;
6430 }
6431
6432 /*!
6433     \property QWidget::frameSize
6434     \brief the size of the widget including any window frame
6435
6436     By default, this property contains a value that depends on the user's
6437     platform and screen geometry.
6438 */
6439 QSize QWidget::frameSize() const
6440 {
6441     Q_D(const QWidget);
6442     if (isWindow() && !(windowType() == Qt::Popup)) {
6443         QRect fs = d->frameStrut();
6444         return QSize(data->crect.width() + fs.left() + fs.right(),
6445                       data->crect.height() + fs.top() + fs.bottom());
6446     }
6447     return data->crect.size();
6448 }
6449
6450 /*! \fn void QWidget::move(int x, int y)
6451
6452     \overload
6453
6454     This corresponds to move(QPoint(\a x, \a y)).
6455 */
6456
6457 void QWidget::move(const QPoint &p)
6458 {
6459     Q_D(QWidget);
6460     setAttribute(Qt::WA_Moved);
6461     if (testAttribute(Qt::WA_WState_Created)) {
6462         if (isWindow())
6463             d->topData()->posIncludesFrame = false;
6464         d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6465                        p.y() + geometry().y() - QWidget::y(),
6466                        width(), height(), true);
6467         d->setDirtyOpaqueRegion();
6468     } else {
6469         // no frame yet: see also QWidgetPrivate::fixPosIncludesFrame(), QWindowPrivate::PositionPolicy.
6470         if (isWindow())
6471             d->topData()->posIncludesFrame = true;
6472         data->crect.moveTopLeft(p); // no frame yet
6473         setAttribute(Qt::WA_PendingMoveEvent);
6474     }
6475 }
6476
6477 /*! \fn void QWidget::resize(int w, int h)
6478     \overload
6479
6480     This corresponds to resize(QSize(\a w, \a h)).
6481 */
6482
6483 void QWidget::resize(const QSize &s)
6484 {
6485     Q_D(QWidget);
6486     setAttribute(Qt::WA_Resized);
6487     if (testAttribute(Qt::WA_WState_Created)) {
6488         d->fixPosIncludesFrame();
6489         d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6490         d->setDirtyOpaqueRegion();
6491     } else {
6492         data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6493         setAttribute(Qt::WA_PendingResizeEvent);
6494     }
6495 }
6496
6497 void QWidget::setGeometry(const QRect &r)
6498 {
6499     Q_D(QWidget);
6500     setAttribute(Qt::WA_Resized);
6501     setAttribute(Qt::WA_Moved);
6502     if (isWindow())
6503         d->topData()->posIncludesFrame = 0;
6504     if (testAttribute(Qt::WA_WState_Created)) {
6505         d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6506         d->setDirtyOpaqueRegion();
6507     } else {
6508         data->crect.setTopLeft(r.topLeft());
6509         data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6510         setAttribute(Qt::WA_PendingMoveEvent);
6511         setAttribute(Qt::WA_PendingResizeEvent);
6512     }
6513 }
6514
6515 /*!
6516     \since 4.2
6517     Saves the current geometry and state for top-level widgets.
6518
6519     To save the geometry when the window closes, you can
6520     implement a close event like this:
6521
6522     \snippet code/src_gui_kernel_qwidget.cpp 11
6523
6524     See the \l{Window Geometry} documentation for an overview of geometry
6525     issues with windows.
6526
6527     Use QMainWindow::saveState() to save the geometry and the state of
6528     toolbars and dock widgets.
6529
6530     \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6531 */
6532 QByteArray QWidget::saveGeometry() const
6533 {
6534 #ifdef Q_WS_MAC
6535     // We check if the window was maximized during this invocation. If so, we need to record the
6536     // starting position as 0,0.
6537     Q_D(const QWidget);
6538     QRect newFramePosition = frameGeometry();
6539     QRect newNormalPosition = normalGeometry();
6540     if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6541         // Change the starting position
6542         newFramePosition.moveTo(0, 0);
6543         newNormalPosition.moveTo(0, 0);
6544     }
6545 #endif // Q_WS_MAC
6546     QByteArray array;
6547     QDataStream stream(&array, QIODevice::WriteOnly);
6548     stream.setVersion(QDataStream::Qt_4_0);
6549     const quint32 magicNumber = 0x1D9D0CB;
6550     quint16 majorVersion = 1;
6551     quint16 minorVersion = 0;
6552     stream << magicNumber
6553            << majorVersion
6554            << minorVersion
6555 #ifdef Q_WS_MAC
6556            << newFramePosition
6557            << newNormalPosition
6558 #else
6559            << frameGeometry()
6560            << normalGeometry()
6561 #endif // Q_WS_MAC
6562            << qint32(QApplication::desktop()->screenNumber(this))
6563            << quint8(windowState() & Qt::WindowMaximized)
6564            << quint8(windowState() & Qt::WindowFullScreen);
6565     return array;
6566 }
6567
6568 /*!
6569     \since 4.2
6570
6571     Restores the geometry and state top-level widgets stored in the
6572     byte array \a geometry. Returns true on success; otherwise
6573     returns false.
6574
6575     If the restored geometry is off-screen, it will be modified to be
6576     inside the available screen geometry.
6577
6578     To restore geometry saved using QSettings, you can use code like
6579     this:
6580
6581     \snippet code/src_gui_kernel_qwidget.cpp 12
6582
6583     See the \l{Window Geometry} documentation for an overview of geometry
6584     issues with windows.
6585
6586     Use QMainWindow::restoreState() to restore the geometry and the
6587     state of toolbars and dock widgets.
6588
6589     \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6590 */
6591 bool QWidget::restoreGeometry(const QByteArray &geometry)
6592 {
6593     if (geometry.size() < 4)
6594         return false;
6595     QDataStream stream(geometry);
6596     stream.setVersion(QDataStream::Qt_4_0);
6597
6598     const quint32 magicNumber = 0x1D9D0CB;
6599     quint32 storedMagicNumber;
6600     stream >> storedMagicNumber;
6601     if (storedMagicNumber != magicNumber)
6602         return false;
6603
6604     const quint16 currentMajorVersion = 1;
6605     quint16 majorVersion = 0;
6606     quint16 minorVersion = 0;
6607
6608     stream >> majorVersion >> minorVersion;
6609
6610     if (majorVersion != currentMajorVersion)
6611         return false;
6612     // (Allow all minor versions.)
6613
6614     QRect restoredFrameGeometry;
6615      QRect restoredNormalGeometry;
6616     qint32 restoredScreenNumber;
6617     quint8 maximized;
6618     quint8 fullScreen;
6619
6620     stream >> restoredFrameGeometry
6621            >> restoredNormalGeometry
6622            >> restoredScreenNumber
6623            >> maximized
6624            >> fullScreen;
6625
6626     const int frameHeight = 20;
6627     if (!restoredFrameGeometry.isValid())
6628         restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6629
6630     if (!restoredNormalGeometry.isValid())
6631         restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6632     if (!restoredNormalGeometry.isValid()) {
6633         // use the widget's adjustedSize if the sizeHint() doesn't help
6634         restoredNormalGeometry.setSize(restoredNormalGeometry
6635                                        .size()
6636                                        .expandedTo(d_func()->adjustedSize()));
6637     }
6638
6639     const QDesktopWidget * const desktop = QApplication::desktop();
6640     if (restoredScreenNumber >= desktop->numScreens())
6641         restoredScreenNumber = desktop->primaryScreen();
6642
6643     const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6644
6645     // Modify the restored geometry if we are about to restore to coordinates
6646     // that would make the window "lost". This happens if:
6647     // - The restored geometry is completely oustside the available geometry
6648     // - The title bar is outside the available geometry.
6649     // - (Mac only) The window is higher than the available geometry. It must
6650     //   be possible to bring the size grip on screen by moving the window.
6651 #ifdef Q_WS_MAC
6652     restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6653     restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6654 #endif
6655
6656     if (!restoredFrameGeometry.intersects(availableGeometry)) {
6657         restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6658         restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6659         restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6660     }
6661     restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6662
6663     if (!restoredNormalGeometry.intersects(availableGeometry)) {
6664         restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6665         restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6666         restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6667     }
6668     restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6669
6670     if (maximized || fullScreen) {
6671         // set geometry before setting the window state to make
6672         // sure the window is maximized to the right screen.
6673         // Skip on windows: the window is restored into a broken
6674         // half-maximized state.
6675 #ifndef Q_OS_WIN
6676         setGeometry(restoredNormalGeometry);
6677 #endif
6678         Qt::WindowStates ws = windowState();
6679         if (maximized)
6680             ws |= Qt::WindowMaximized;
6681         if (fullScreen)
6682             ws |= Qt::WindowFullScreen;
6683        setWindowState(ws);
6684        d_func()->topData()->normalGeometry = restoredNormalGeometry;
6685     } else {
6686         QPoint offset;
6687 #ifdef Q_WS_X11
6688         if (isFullScreen())
6689             offset = d_func()->topData()->fullScreenOffset;
6690 #endif
6691         setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6692         move(restoredFrameGeometry.topLeft() + offset);
6693         resize(restoredNormalGeometry.size());
6694     }
6695     return true;
6696 }
6697
6698 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6699     \overload
6700
6701     This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6702 */
6703
6704 /*!
6705   Sets the margins around the contents of the widget to have the sizes
6706   \a left, \a top, \a right, and \a bottom. The margins are used by
6707   the layout system, and may be used by subclasses to specify the area
6708   to draw in (e.g. excluding the frame).
6709
6710   Changing the margins will trigger a resizeEvent().
6711
6712   \sa contentsRect(), getContentsMargins()
6713 */
6714 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6715 {
6716     Q_D(QWidget);
6717     if (left == d->leftmargin && top == d->topmargin
6718          && right == d->rightmargin && bottom == d->bottommargin)
6719         return;
6720     d->leftmargin = left;
6721     d->topmargin = top;
6722     d->rightmargin = right;
6723     d->bottommargin = bottom;
6724
6725     if (QLayout *l=d->layout)
6726         l->update(); //force activate; will do updateGeometry
6727     else
6728         updateGeometry();
6729
6730     if (isVisible()) {
6731         update();
6732         QResizeEvent e(data->crect.size(), data->crect.size());
6733         QApplication::sendEvent(this, &e);
6734     } else {
6735         setAttribute(Qt::WA_PendingResizeEvent, true);
6736     }
6737
6738     QEvent e(QEvent::ContentsRectChange);
6739     QApplication::sendEvent(this, &e);
6740 }
6741
6742 /*!
6743   \overload
6744   \since 4.6
6745
6746   \brief The setContentsMargins function sets the margins around the
6747   widget's contents.
6748
6749   Sets the margins around the contents of the widget to have the
6750   sizes determined by \a margins. The margins are
6751   used by the layout system, and may be used by subclasses to
6752   specify the area to draw in (e.g. excluding the frame).
6753
6754   Changing the margins will trigger a resizeEvent().
6755
6756   \sa contentsRect(), getContentsMargins()
6757 */
6758 void QWidget::setContentsMargins(const QMargins &margins)
6759 {
6760     setContentsMargins(margins.left(), margins.top(),
6761                        margins.right(), margins.bottom());
6762 }
6763
6764 /*!
6765   Returns the widget's contents margins for \a left, \a top, \a
6766   right, and \a bottom.
6767
6768   \sa setContentsMargins(), contentsRect()
6769  */
6770 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6771 {
6772     Q_D(const QWidget);
6773     if (left)
6774         *left = d->leftmargin;
6775     if (top)
6776         *top = d->topmargin;
6777     if (right)
6778         *right = d->rightmargin;
6779     if (bottom)
6780         *bottom = d->bottommargin;
6781 }
6782
6783 /*!
6784   \since 4.6
6785
6786   \brief The contentsMargins function returns the widget's contents margins.
6787
6788   \sa getContentsMargins(), setContentsMargins(), contentsRect()
6789  */
6790 QMargins QWidget::contentsMargins() const
6791 {
6792     Q_D(const QWidget);
6793     return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6794 }
6795
6796
6797 /*!
6798     Returns the area inside the widget's margins.
6799
6800     \sa setContentsMargins(), getContentsMargins()
6801 */
6802 QRect QWidget::contentsRect() const
6803 {
6804     Q_D(const QWidget);
6805     return QRect(QPoint(d->leftmargin, d->topmargin),
6806                  QPoint(data->crect.width() - 1 - d->rightmargin,
6807                         data->crect.height() - 1 - d->bottommargin));
6808
6809 }
6810
6811
6812
6813 /*!
6814   \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6815
6816   This signal is emitted when the widget's \l contextMenuPolicy is
6817   Qt::CustomContextMenu, and the user has requested a context menu on
6818   the widget. The position \a pos is the position of the context menu
6819   event that the widget receives. Normally this is in widget
6820   coordinates. The exception to this rule is QAbstractScrollArea and
6821   its subclasses that map the context menu event to coordinates of the
6822   \l{QAbstractScrollArea::viewport()}{viewport()}.
6823
6824
6825   \sa mapToGlobal(), QMenu, contextMenuPolicy
6826 */
6827
6828
6829 /*!
6830     \property QWidget::contextMenuPolicy
6831     \brief how the widget shows a context menu
6832
6833     The default value of this property is Qt::DefaultContextMenu,
6834     which means the contextMenuEvent() handler is called. Other values
6835     are Qt::NoContextMenu, Qt::PreventContextMenu,
6836     Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6837     Qt::CustomContextMenu, the signal customContextMenuRequested() is
6838     emitted.
6839
6840     \sa contextMenuEvent(), customContextMenuRequested(), actions()
6841 */
6842
6843 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6844 {
6845     return (Qt::ContextMenuPolicy)data->context_menu_policy;
6846 }
6847
6848 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6849 {
6850     data->context_menu_policy = (uint) policy;
6851 }
6852
6853 /*!
6854     \property QWidget::focusPolicy
6855     \brief the way the widget accepts keyboard focus
6856
6857     The policy is Qt::TabFocus if the widget accepts keyboard
6858     focus by tabbing, Qt::ClickFocus if the widget accepts
6859     focus by clicking, Qt::StrongFocus if it accepts both, and
6860     Qt::NoFocus (the default) if it does not accept focus at
6861     all.
6862
6863     You must enable keyboard focus for a widget if it processes
6864     keyboard events. This is normally done from the widget's
6865     constructor. For instance, the QLineEdit constructor calls
6866     setFocusPolicy(Qt::StrongFocus).
6867
6868     If the widget has a focus proxy, then the focus policy will
6869     be propagated to it.
6870
6871     \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6872 */
6873
6874
6875 Qt::FocusPolicy QWidget::focusPolicy() const
6876 {
6877     return (Qt::FocusPolicy)data->focus_policy;
6878 }
6879
6880 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6881 {
6882     data->focus_policy = (uint) policy;
6883     Q_D(QWidget);
6884     if (d->extra && d->extra->focus_proxy)
6885         d->extra->focus_proxy->setFocusPolicy(policy);
6886 }
6887
6888 /*!
6889     \property QWidget::updatesEnabled
6890     \brief whether updates are enabled
6891
6892     An updates enabled widget receives paint events and has a system
6893     background; a disabled widget does not. This also implies that
6894     calling update() and repaint() has no effect if updates are
6895     disabled.
6896
6897     By default, this property is true.
6898
6899     setUpdatesEnabled() is normally used to disable updates for a
6900     short period of time, for instance to avoid screen flicker during
6901     large changes. In Qt, widgets normally do not generate screen
6902     flicker, but on X11 the server might erase regions on the screen
6903     when widgets get hidden before they can be replaced by other
6904     widgets. Disabling updates solves this.
6905
6906     Example:
6907     \snippet code/src_gui_kernel_qwidget.cpp 13
6908
6909     Disabling a widget implicitly disables all its children. Enabling a widget
6910     enables all child widgets \e except top-level widgets or those that
6911     have been explicitly disabled. Re-enabling updates implicitly calls
6912     update() on the widget.
6913
6914     \sa paintEvent()
6915 */
6916 void QWidget::setUpdatesEnabled(bool enable)
6917 {
6918     Q_D(QWidget);
6919     setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6920     d->setUpdatesEnabled_helper(enable);
6921 }
6922
6923 /*!
6924     Shows the widget and its child widgets. This function is
6925     equivalent to setVisible(true) in the normal case, and equivalent
6926     to showFullScreen() if the QStyleHints::showIsFullScreen() hint
6927     is true.
6928
6929     \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6930     showNormal(), isVisible()
6931 */
6932 void QWidget::show()
6933 {
6934     if (isWindow() && qApp->styleHints()->showIsFullScreen())
6935         showFullScreen();
6936     else
6937         setVisible(true);
6938 }
6939
6940 /*! \internal
6941
6942    Makes the widget visible in the isVisible() meaning of the word.
6943    It is only called for toplevels or widgets with visible parents.
6944  */
6945 void QWidgetPrivate::show_recursive()
6946 {
6947     Q_Q(QWidget);
6948     // polish if necessary
6949
6950     if (!q->testAttribute(Qt::WA_WState_Created))
6951         createRecursively();
6952     q->ensurePolished();
6953
6954     if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6955         q->parentWidget()->d_func()->layout->activate();
6956     // activate our layout before we and our children become visible
6957     if (layout)
6958         layout->activate();
6959
6960     show_helper();
6961 }
6962
6963 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6964 {
6965     Q_Q(QWidget);
6966
6967     disableUpdates = disableUpdates && q->updatesEnabled();
6968     if (disableUpdates)
6969         q->setAttribute(Qt::WA_UpdatesDisabled);
6970
6971     if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6972         QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6973         QApplication::sendEvent(q, &e);
6974         q->setAttribute(Qt::WA_PendingMoveEvent, false);
6975     }
6976
6977     if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6978         QResizeEvent e(data.crect.size(), QSize());
6979         QApplication::sendEvent(q, &e);
6980         q->setAttribute(Qt::WA_PendingResizeEvent, false);
6981     }
6982
6983     if (disableUpdates)
6984         q->setAttribute(Qt::WA_UpdatesDisabled, false);
6985
6986     if (!recursive)
6987         return;
6988
6989     for (int i = 0; i < children.size(); ++i) {
6990         if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6991             child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
6992     }
6993 }
6994
6995 void QWidgetPrivate::activateChildLayoutsRecursively()
6996 {
6997     sendPendingMoveAndResizeEvents(false, true);
6998
6999     for (int i = 0; i < children.size(); ++i) {
7000         QWidget *child = qobject_cast<QWidget *>(children.at(i));
7001         if (!child || child->isHidden() || child->isWindow())
7002             continue;
7003
7004         child->ensurePolished();
7005
7006         // Activate child's layout
7007         QWidgetPrivate *childPrivate = child->d_func();
7008         if (childPrivate->layout)
7009             childPrivate->layout->activate();
7010
7011         // Pretend we're visible.
7012         const bool wasVisible = child->isVisible();
7013         if (!wasVisible)
7014             child->setAttribute(Qt::WA_WState_Visible);
7015
7016         // Do the same for all my children.
7017         childPrivate->activateChildLayoutsRecursively();
7018
7019         // We're not cheating anymore.
7020         if (!wasVisible)
7021             child->setAttribute(Qt::WA_WState_Visible, false);
7022     }
7023 }
7024
7025 void QWidgetPrivate::show_helper()
7026 {
7027     Q_Q(QWidget);
7028     data.in_show = true; // qws optimization
7029     // make sure we receive pending move and resize events
7030     sendPendingMoveAndResizeEvents();
7031
7032     // become visible before showing all children
7033     q->setAttribute(Qt::WA_WState_Visible);
7034
7035     // finally show all children recursively
7036     showChildren(false);
7037
7038
7039
7040     // popup handling: new popups and tools need to be raised, and
7041     // existing popups must be closed. Also propagate the current
7042     // windows's KeyboardFocusChange status.
7043     if (q->isWindow()) {
7044         if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7045             q->raise();
7046             if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7047                 q->setAttribute(Qt::WA_KeyboardFocusChange);
7048         } else {
7049             while (QApplication::activePopupWidget()) {
7050                 if (!QApplication::activePopupWidget()->close())
7051                     break;
7052             }
7053         }
7054     }
7055
7056     // Automatic embedding of child windows of widgets already embedded into
7057     // QGraphicsProxyWidget when they are shown the first time.
7058     bool isEmbedded = false;
7059 #ifndef QT_NO_GRAPHICSVIEW
7060     if (q->isWindow()) {
7061         isEmbedded = q->graphicsProxyWidget() ? true : false;
7062         if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7063             QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7064             if (ancestorProxy) {
7065                 isEmbedded = true;
7066                 ancestorProxy->d_func()->embedSubWindow(q);
7067             }
7068         }
7069     }
7070 #else
7071     Q_UNUSED(isEmbedded);
7072 #endif
7073
7074     // On Windows, show the popup now so that our own focus handling
7075     // stores the correct old focus widget even if it's stolen in the
7076     // showevent
7077 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
7078     if (!isEmbedded && q->windowType() == Qt::Popup)
7079         qApp->d_func()->openPopup(q);
7080 #endif
7081
7082     // send the show event before showing the window
7083     QShowEvent showEvent;
7084     QApplication::sendEvent(q, &showEvent);
7085
7086     show_sys();
7087
7088     if (!isEmbedded && q->windowType() == Qt::Popup)
7089         qApp->d_func()->openPopup(q);
7090
7091 #ifndef QT_NO_ACCESSIBILITY
7092     if (q->windowType() != Qt::ToolTip) {    // Tooltips are read aloud twice in MS narrator.
7093         QAccessibleEvent event(q, QAccessible::ObjectShow);
7094         QAccessible::updateAccessibility(&event);
7095     }
7096 #endif
7097
7098     if (QApplicationPrivate::hidden_focus_widget == q) {
7099         QApplicationPrivate::hidden_focus_widget = 0;
7100         q->setFocus(Qt::OtherFocusReason);
7101     }
7102
7103     // Process events when showing a Qt::SplashScreen widget before the event loop
7104     // is spinnning; otherwise it might not show up on particular platforms.
7105     // This makes QSplashScreen behave the same on all platforms.
7106     if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7107         QApplication::processEvents();
7108
7109     data.in_show = false;  // reset qws optimization
7110 }
7111
7112 /*!
7113     Hides the widget. This function is equivalent to
7114     setVisible(false).
7115
7116
7117     \note If you are working with QDialog or its subclasses and you invoke
7118     the show() function after this function, the dialog will be displayed in
7119     its original position.
7120
7121     \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7122 */
7123 void QWidget::hide()
7124 {
7125     setVisible(false);
7126 }
7127
7128 /*!\internal
7129  */
7130 void QWidgetPrivate::hide_helper()
7131 {
7132     Q_Q(QWidget);
7133
7134     bool isEmbedded = false;
7135 #if !defined QT_NO_GRAPHICSVIEW
7136     isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7137 #else
7138     Q_UNUSED(isEmbedded);
7139 #endif
7140
7141     if (!isEmbedded && (q->windowType() == Qt::Popup))
7142         qApp->d_func()->closePopup(q);
7143
7144 #if defined(Q_WS_WIN)
7145     if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7146         && !q->parentWidget()->isHidden() && q->isActiveWindow())
7147         q->parentWidget()->activateWindow();        // Activate parent
7148 #endif
7149
7150     q->setAttribute(Qt::WA_Mapped, false);
7151     hide_sys();
7152
7153     bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7154
7155     if (wasVisible) {
7156         q->setAttribute(Qt::WA_WState_Visible, false);
7157
7158     }
7159
7160     QHideEvent hideEvent;
7161     QApplication::sendEvent(q, &hideEvent);
7162     hideChildren(false);
7163
7164     // next bit tries to move the focus if the focus widget is now
7165     // hidden.
7166     if (wasVisible) {
7167         qApp->d_func()->sendSyntheticEnterLeave(q);
7168         QWidget *fw = QApplication::focusWidget();
7169         while (fw &&  !fw->isWindow()) {
7170             if (fw == q) {
7171                 q->focusNextPrevChild(true);
7172                 break;
7173             }
7174             fw = fw->parentWidget();
7175         }
7176     }
7177
7178     if (QWidgetBackingStore *bs = maybeBackingStore())
7179         bs->removeDirtyWidget(q);
7180
7181 #ifndef QT_NO_ACCESSIBILITY
7182     if (wasVisible) {
7183         QAccessibleEvent event(q, QAccessible::ObjectHide);
7184         QAccessible::updateAccessibility(&event);
7185     }
7186 #endif
7187 }
7188
7189 /*!
7190     \fn bool QWidget::isHidden() const
7191
7192     Returns true if the widget is hidden, otherwise returns false.
7193
7194     A hidden widget will only become visible when show() is called on
7195     it. It will not be automatically shown when the parent is shown.
7196
7197     To check visibility, use !isVisible() instead (notice the exclamation mark).
7198
7199     isHidden() implies !isVisible(), but a widget can be not visible
7200     and not hidden at the same time. This is the case for widgets that are children of
7201     widgets that are not visible.
7202
7203
7204     Widgets are hidden if:
7205     \list
7206         \li they were created as independent windows,
7207         \li they were created as children of visible widgets,
7208         \li hide() or setVisible(false) was called.
7209     \endlist
7210 */
7211
7212
7213 void QWidget::setVisible(bool visible)
7214 {
7215     if (visible) { // show
7216         if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7217             return;
7218
7219         Q_D(QWidget);
7220
7221         // Designer uses a trick to make grabWidget work without showing
7222         if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7223             && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7224             parentWidget()->window()->d_func()->createRecursively();
7225
7226         //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7227         //but not children of non-visible parents
7228         QWidget *pw = parentWidget();
7229         if (!testAttribute(Qt::WA_WState_Created)
7230             && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7231             create();
7232         }
7233
7234 #if defined(Q_WS_X11)
7235         if (windowType() == Qt::Window)
7236             QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7237 #endif
7238
7239         bool wasResized = testAttribute(Qt::WA_Resized);
7240         Qt::WindowStates initialWindowState = windowState();
7241
7242         // polish if necessary
7243         ensurePolished();
7244
7245         // remember that show was called explicitly
7246         setAttribute(Qt::WA_WState_ExplicitShowHide);
7247         // whether we need to inform the parent widget immediately
7248         bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7249         // we are no longer hidden
7250         setAttribute(Qt::WA_WState_Hidden, false);
7251
7252         if (needUpdateGeometry)
7253             d->updateGeometry_helper(true);
7254
7255         // activate our layout before we and our children become visible
7256         if (d->layout)
7257             d->layout->activate();
7258
7259         if (!isWindow()) {
7260             QWidget *parent = parentWidget();
7261             while (parent && parent->isVisible() && parent->d_func()->layout  && !parent->data->in_show) {
7262                 parent->d_func()->layout->activate();
7263                 if (parent->isWindow())
7264                     break;
7265                 parent = parent->parentWidget();
7266             }
7267             if (parent)
7268                 parent->d_func()->setDirtyOpaqueRegion();
7269         }
7270
7271         // adjust size if necessary
7272         if (!wasResized
7273             && (isWindow() || !parentWidget()->d_func()->layout))  {
7274             if (isWindow()) {
7275                 adjustSize();
7276                 if (windowState() != initialWindowState)
7277                     setWindowState(initialWindowState);
7278             } else {
7279                 adjustSize();
7280             }
7281             setAttribute(Qt::WA_Resized, false);
7282         }
7283
7284         setAttribute(Qt::WA_KeyboardFocusChange, false);
7285
7286         if (isWindow() || parentWidget()->isVisible()) {
7287             d->show_helper();
7288
7289             qApp->d_func()->sendSyntheticEnterLeave(this);
7290         }
7291
7292         QEvent showToParentEvent(QEvent::ShowToParent);
7293         QApplication::sendEvent(this, &showToParentEvent);
7294     } else { // hide
7295         if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7296             return;
7297 #if defined(Q_WS_WIN)
7298         // reset WS_DISABLED style in a Blocked window
7299         if(isWindow() && testAttribute(Qt::WA_WState_Created)
7300            && QApplicationPrivate::isBlockedByModal(this))
7301         {
7302             LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7303             dwStyle &= ~WS_DISABLED;
7304             SetWindowLong(winId(), GWL_STYLE, dwStyle);
7305         }
7306 #endif
7307         if (QApplicationPrivate::hidden_focus_widget == this)
7308             QApplicationPrivate::hidden_focus_widget = 0;
7309
7310         Q_D(QWidget);
7311
7312         // hw: The test on getOpaqueRegion() needs to be more intelligent
7313         // currently it doesn't work if the widget is hidden (the region will
7314         // be clipped). The real check should be testing the cached region
7315         // (and dirty flag) directly.
7316         if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7317             parentWidget()->d_func()->setDirtyOpaqueRegion();
7318
7319         setAttribute(Qt::WA_WState_Hidden);
7320         setAttribute(Qt::WA_WState_ExplicitShowHide);
7321         if (testAttribute(Qt::WA_WState_Created))
7322             d->hide_helper();
7323
7324         // invalidate layout similar to updateGeometry()
7325         if (!isWindow() && parentWidget()) {
7326             if (parentWidget()->d_func()->layout)
7327                 parentWidget()->d_func()->layout->invalidate();
7328             else if (parentWidget()->isVisible())
7329                 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7330         }
7331
7332         QEvent hideToParentEvent(QEvent::HideToParent);
7333         QApplication::sendEvent(this, &hideToParentEvent);
7334     }
7335 }
7336
7337 /*!
7338     Convenience function, equivalent to setVisible(!\a hidden).
7339 */
7340 void QWidget::setHidden(bool hidden)
7341 {
7342     setVisible(!hidden);
7343 }
7344
7345 void QWidgetPrivate::_q_showIfNotHidden()
7346 {
7347     Q_Q(QWidget);
7348     if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7349         q->setVisible(true);
7350 }
7351
7352 void QWidgetPrivate::showChildren(bool spontaneous)
7353 {
7354     QList<QObject*> childList = children;
7355     for (int i = 0; i < childList.size(); ++i) {
7356         QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7357         if (!widget
7358             || widget->isWindow()
7359             || widget->testAttribute(Qt::WA_WState_Hidden))
7360             continue;
7361         if (spontaneous) {
7362             widget->setAttribute(Qt::WA_Mapped);
7363             widget->d_func()->showChildren(true);
7364             QShowEvent e;
7365             QApplication::sendSpontaneousEvent(widget, &e);
7366         } else {
7367             if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7368                 widget->d_func()->show_recursive();
7369             else
7370                 widget->show();
7371         }
7372     }
7373 }
7374
7375 void QWidgetPrivate::hideChildren(bool spontaneous)
7376 {
7377     QList<QObject*> childList = children;
7378     for (int i = 0; i < childList.size(); ++i) {
7379         QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7380         if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7381             continue;
7382 #ifdef Q_WS_MAC
7383         // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7384         // When hiding a widget we need to make sure that no mouse_down events are active, because
7385         // the mouse_up event will never be received by a hidden widget or one of its descendants.
7386         // The solution is simple, before going through with this we check if there are any mouse_down events in
7387         // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7388         // then we continue.
7389         // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7390         // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7391         // mouse release event. There are two ways to interpret this:
7392         // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7393         // might be waiting for a release event that will never arrive.
7394         // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7395         // supposed to trigger because it is not visible.
7396         if(widget == qt_button_down)
7397             qt_button_down = 0;
7398 #endif // Q_WS_MAC
7399         if (spontaneous)
7400             widget->setAttribute(Qt::WA_Mapped, false);
7401         else
7402             widget->setAttribute(Qt::WA_WState_Visible, false);
7403         widget->d_func()->hideChildren(spontaneous);
7404         QHideEvent e;
7405         if (spontaneous) {
7406             QApplication::sendSpontaneousEvent(widget, &e);
7407         } else {
7408             QApplication::sendEvent(widget, &e);
7409             if (widget->internalWinId()
7410                 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7411                 // hide_sys() on an ancestor won't have any affect on this
7412                 // widget, so it needs an explicit hide_sys() of its own
7413                 widget->d_func()->hide_sys();
7414             }
7415         }
7416         qApp->d_func()->sendSyntheticEnterLeave(widget);
7417 #ifndef QT_NO_ACCESSIBILITY
7418         if (!spontaneous) {
7419             QAccessibleEvent event(widget, QAccessible::ObjectHide);
7420             QAccessible::updateAccessibility(&event);
7421         }
7422 #endif
7423     }
7424 }
7425
7426 bool QWidgetPrivate::close_helper(CloseMode mode)
7427 {
7428     if (data.is_closing)
7429         return true;
7430
7431     Q_Q(QWidget);
7432     data.is_closing = 1;
7433
7434     QPointer<QWidget> that = q;
7435     QPointer<QWidget> parentWidget = q->parentWidget();
7436
7437     bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7438     if (mode != CloseNoEvent) {
7439         QCloseEvent e;
7440         if (mode == CloseWithSpontaneousEvent)
7441             QApplication::sendSpontaneousEvent(q, &e);
7442         else
7443             QApplication::sendEvent(q, &e);
7444         if (!that.isNull() && !e.isAccepted()) {
7445             data.is_closing = 0;
7446             return false;
7447         }
7448     }
7449
7450     if (!that.isNull() && !q->isHidden())
7451         q->hide();
7452
7453     // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7454     quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7455
7456     if (quitOnClose) {
7457         /* if there is no non-withdrawn primary window left (except
7458            the ones without QuitOnClose), we emit the lastWindowClosed
7459            signal */
7460         QWidgetList list = QApplication::topLevelWidgets();
7461         bool lastWindowClosed = true;
7462         for (int i = 0; i < list.size(); ++i) {
7463             QWidget *w = list.at(i);
7464             if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7465                 continue;
7466             lastWindowClosed = false;
7467             break;
7468         }
7469         if (lastWindowClosed) {
7470             QGuiApplicationPrivate::emitLastWindowClosed();
7471             QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
7472             applicationPrivate->maybeQuit();
7473         }
7474     }
7475
7476
7477     if (!that.isNull()) {
7478         data.is_closing = 0;
7479         if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7480             q->setAttribute(Qt::WA_DeleteOnClose, false);
7481             q->deleteLater();
7482         }
7483     }
7484     return true;
7485 }
7486
7487
7488 /*!
7489     Closes this widget. Returns true if the widget was closed;
7490     otherwise returns false.
7491
7492     First it sends the widget a QCloseEvent. The widget is
7493     \l{hide()}{hidden} if it \l{QCloseEvent::accept()}{accepts}
7494     the close event. If it \l{QCloseEvent::ignore()}{ignores}
7495     the event, nothing happens. The default
7496     implementation of QWidget::closeEvent() accepts the close event.
7497
7498     If the widget has the Qt::WA_DeleteOnClose flag, the widget
7499     is also deleted. A close events is delivered to the widget no
7500     matter if the widget is visible or not.
7501
7502     The \l QApplication::lastWindowClosed() signal is emitted when the
7503     last visible primary window (i.e. window with no parent) with the
7504     Qt::WA_QuitOnClose attribute set is closed. By default this
7505     attribute is set for all widgets except transient windows such as
7506     splash screens, tool windows, and popup menus.
7507
7508 */
7509
7510 bool QWidget::close()
7511 {
7512     return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7513 }
7514
7515 /*!
7516     \property QWidget::visible
7517     \brief whether the widget is visible
7518
7519     Calling setVisible(true) or show() sets the widget to visible
7520     status if all its parent widgets up to the window are visible. If
7521     an ancestor is not visible, the widget won't become visible until
7522     all its ancestors are shown. If its size or position has changed,
7523     Qt guarantees that a widget gets move and resize events just
7524     before it is shown. If the widget has not been resized yet, Qt
7525     will adjust the widget's size to a useful default using
7526     adjustSize().
7527
7528     Calling setVisible(false) or hide() hides a widget explicitly. An
7529     explicitly hidden widget will never become visible, even if all
7530     its ancestors become visible, unless you show it.
7531
7532     A widget receives show and hide events when its visibility status
7533     changes. Between a hide and a show event, there is no need to
7534     waste CPU cycles preparing or displaying information to the user.
7535     A video application, for example, might simply stop generating new
7536     frames.
7537
7538     A widget that happens to be obscured by other windows on the
7539     screen is considered to be visible. The same applies to iconified
7540     windows and windows that exist on another virtual
7541     desktop (on platforms that support this concept). A widget
7542     receives spontaneous show and hide events when its mapping status
7543     is changed by the window system, e.g. a spontaneous hide event
7544     when the user minimizes the window, and a spontaneous show event
7545     when the window is restored again.
7546
7547     You almost never have to reimplement the setVisible() function. If
7548     you need to change some settings before a widget is shown, use
7549     showEvent() instead. If you need to do some delayed initialization
7550     use the Polish event delivered to the event() function.
7551
7552     \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7553     showEvent(), hideEvent()
7554 */
7555
7556
7557 /*!
7558     Returns true if this widget would become visible if \a ancestor is
7559     shown; otherwise returns false.
7560
7561     The true case occurs if neither the widget itself nor any parent
7562     up to but excluding \a ancestor has been explicitly hidden.
7563
7564     This function will still return true if the widget is obscured by
7565     other windows on the screen, but could be physically visible if it
7566     or they were to be moved.
7567
7568     isVisibleTo(0) is identical to isVisible().
7569
7570     \sa show(), hide(), isVisible()
7571 */
7572
7573 bool QWidget::isVisibleTo(const QWidget *ancestor) const
7574 {
7575     if (!ancestor)
7576         return isVisible();
7577     const QWidget * w = this;
7578     while (!w->isHidden()
7579             && !w->isWindow()
7580             && w->parentWidget()
7581             && w->parentWidget() != ancestor)
7582         w = w->parentWidget();
7583     return !w->isHidden();
7584 }
7585
7586
7587 /*!
7588     Returns the unobscured region where paint events can occur.
7589
7590     For visible widgets, this is an approximation of the area not
7591     covered by other widgets; otherwise, this is an empty region.
7592
7593     The repaint() function calls this function if necessary, so in
7594     general you do not need to call it.
7595
7596 */
7597 QRegion QWidget::visibleRegion() const
7598 {
7599     Q_D(const QWidget);
7600
7601     QRect clipRect = d->clipRect();
7602     if (clipRect.isEmpty())
7603         return QRegion();
7604     QRegion r(clipRect);
7605     d->subtractOpaqueChildren(r, clipRect);
7606     d->subtractOpaqueSiblings(r);
7607     return r;
7608 }
7609
7610
7611 QSize QWidgetPrivate::adjustedSize() const
7612 {
7613     Q_Q(const QWidget);
7614
7615     QSize s = q->sizeHint();
7616
7617     if (q->isWindow()) {
7618         Qt::Orientations exp;
7619         if (layout) {
7620             if (layout->hasHeightForWidth())
7621                 s.setHeight(layout->totalHeightForWidth(s.width()));
7622             exp = layout->expandingDirections();
7623         } else
7624         {
7625             if (q->sizePolicy().hasHeightForWidth())
7626                 s.setHeight(q->heightForWidth(s.width()));
7627             exp = q->sizePolicy().expandingDirections();
7628         }
7629         if (exp & Qt::Horizontal)
7630             s.setWidth(qMax(s.width(), 200));
7631         if (exp & Qt::Vertical)
7632             s.setHeight(qMax(s.height(), 100));
7633 #if defined(Q_WS_X11)
7634         QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7635 #else // all others
7636         QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7637 #endif
7638 #if defined (Q_OS_WINCE)
7639         s.setWidth(qMin(s.width(), screen.width()));
7640         s.setHeight(qMin(s.height(), screen.height()));
7641 #else
7642         s.setWidth(qMin(s.width(), screen.width()*2/3));
7643         s.setHeight(qMin(s.height(), screen.height()*2/3));
7644 #endif
7645         if (QTLWExtra *extra = maybeTopData())
7646             extra->sizeAdjusted = true;
7647     }
7648
7649     if (!s.isValid()) {
7650         QRect r = q->childrenRect(); // get children rectangle
7651         if (r.isNull())
7652             return s;
7653         s = r.size() + QSize(2 * r.x(), 2 * r.y());
7654     }
7655
7656     return s;
7657 }
7658
7659 /*!
7660     Adjusts the size of the widget to fit its contents.
7661
7662     This function uses sizeHint() if it is valid, i.e., the size hint's width
7663     and height are \>= 0. Otherwise, it sets the size to the children
7664     rectangle that covers all child widgets (the union of all child widget
7665     rectangles).
7666
7667     For windows, the screen size is also taken into account. If the sizeHint()
7668     is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7669     {expanding}, the window will be at least (200, 100). The maximum size of
7670     a window is 2/3 of the screen's width and height.
7671
7672     \sa sizeHint(), childrenRect()
7673 */
7674
7675 void QWidget::adjustSize()
7676 {
7677     Q_D(QWidget);
7678     ensurePolished();
7679     QSize s = d->adjustedSize();
7680
7681     if (d->layout)
7682         d->layout->activate();
7683
7684     if (s.isValid())
7685         resize(s);
7686 }
7687
7688
7689 /*!
7690     \property QWidget::sizeHint
7691     \brief the recommended size for the widget
7692
7693     If the value of this property is an invalid size, no size is
7694     recommended.
7695
7696     The default implementation of sizeHint() returns an invalid size
7697     if there is no layout for this widget, and returns the layout's
7698     preferred size otherwise.
7699
7700     \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7701     setMinimumSize(), updateGeometry()
7702 */
7703
7704 QSize QWidget::sizeHint() const
7705 {
7706     Q_D(const QWidget);
7707     if (d->layout)
7708         return d->layout->totalSizeHint();
7709     return QSize(-1, -1);
7710 }
7711
7712 /*!
7713     \property QWidget::minimumSizeHint
7714     \brief the recommended minimum size for the widget
7715
7716     If the value of this property is an invalid size, no minimum size
7717     is recommended.
7718
7719     The default implementation of minimumSizeHint() returns an invalid
7720     size if there is no layout for this widget, and returns the
7721     layout's minimum size otherwise. Most built-in widgets reimplement
7722     minimumSizeHint().
7723
7724     \l QLayout will never resize a widget to a size smaller than the
7725     minimum size hint unless minimumSize() is set or the size policy is
7726     set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7727     size hint will be ignored.
7728
7729     \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7730 */
7731 QSize QWidget::minimumSizeHint() const
7732 {
7733     Q_D(const QWidget);
7734     if (d->layout)
7735         return d->layout->totalMinimumSize();
7736     return QSize(-1, -1);
7737 }
7738
7739
7740 /*!
7741     \fn QWidget *QWidget::parentWidget() const
7742
7743     Returns the parent of this widget, or 0 if it does not have any
7744     parent widget.
7745 */
7746
7747
7748 /*!
7749     Returns true if this widget is a parent, (or grandparent and so on
7750     to any level), of the given \a child, and both widgets are within
7751     the same window; otherwise returns false.
7752 */
7753
7754 bool QWidget::isAncestorOf(const QWidget *child) const
7755 {
7756     while (child) {
7757         if (child == this)
7758             return true;
7759         if (child->isWindow())
7760             return false;
7761         child = child->parentWidget();
7762     }
7763     return false;
7764 }
7765
7766 #if defined(Q_WS_WIN)
7767 inline void setDisabledStyle(QWidget *w, bool setStyle)
7768 {
7769     // set/reset WS_DISABLED style.
7770     if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7771         LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7772         LONG newStyle = dwStyle;
7773         if (setStyle)
7774             newStyle |= WS_DISABLED;
7775         else
7776             newStyle &= ~WS_DISABLED;
7777         if (newStyle != dwStyle) {
7778             SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7779             // we might need to repaint in some situations (eg. menu)
7780             w->repaint();
7781         }
7782     }
7783 }
7784 #endif
7785
7786 /*****************************************************************************
7787   QWidget event handling
7788  *****************************************************************************/
7789
7790 /*!
7791     This is the main event handler; it handles event \a event. You can
7792     reimplement this function in a subclass, but we recommend using
7793     one of the specialized event handlers instead.
7794
7795     Key press and release events are treated differently from other
7796     events. event() checks for Tab and Shift+Tab and tries to move the
7797     focus appropriately. If there is no widget to move the focus to
7798     (or the key press is not Tab or Shift+Tab), event() calls
7799     keyPressEvent().
7800
7801     Mouse and tablet event handling is also slightly special: only
7802     when the widget is \l enabled, event() will call the specialized
7803     handlers such as mousePressEvent(); otherwise it will discard the
7804     event.
7805
7806     This function returns true if the event was recognized, otherwise
7807     it returns false.  If the recognized event was accepted (see \l
7808     QEvent::accepted), any further processing such as event
7809     propagation to the parent widget stops.
7810
7811     \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7812     keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7813     mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7814     mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7815     QObject::event(), QObject::timerEvent()
7816 */
7817
7818 bool QWidget::event(QEvent *event)
7819 {
7820     Q_D(QWidget);
7821
7822     // ignore mouse and key events when disabled
7823     if (!isEnabled()) {
7824         switch(event->type()) {
7825         case QEvent::TabletPress:
7826         case QEvent::TabletRelease:
7827         case QEvent::TabletMove:
7828         case QEvent::MouseButtonPress:
7829         case QEvent::MouseButtonRelease:
7830         case QEvent::MouseButtonDblClick:
7831         case QEvent::MouseMove:
7832         case QEvent::TouchBegin:
7833         case QEvent::TouchUpdate:
7834         case QEvent::TouchEnd:
7835         case QEvent::TouchCancel:
7836         case QEvent::ContextMenu:
7837         case QEvent::KeyPress:
7838         case QEvent::KeyRelease:
7839 #ifndef QT_NO_WHEELEVENT
7840         case QEvent::Wheel:
7841 #endif
7842             return false;
7843         default:
7844             break;
7845         }
7846     }
7847     switch (event->type()) {
7848     case QEvent::MouseMove:
7849         mouseMoveEvent((QMouseEvent*)event);
7850         break;
7851
7852     case QEvent::MouseButtonPress:
7853         mousePressEvent((QMouseEvent*)event);
7854         break;
7855
7856     case QEvent::MouseButtonRelease:
7857         mouseReleaseEvent((QMouseEvent*)event);
7858         break;
7859
7860     case QEvent::MouseButtonDblClick:
7861         mouseDoubleClickEvent((QMouseEvent*)event);
7862         break;
7863 #ifndef QT_NO_WHEELEVENT
7864     case QEvent::Wheel:
7865         wheelEvent((QWheelEvent*)event);
7866         break;
7867 #endif
7868 #ifndef QT_NO_TABLETEVENT
7869     case QEvent::TabletMove:
7870     case QEvent::TabletPress:
7871     case QEvent::TabletRelease:
7872         tabletEvent((QTabletEvent*)event);
7873         break;
7874 #endif
7875     case QEvent::KeyPress: {
7876         QKeyEvent *k = (QKeyEvent *)event;
7877         bool res = false;
7878         if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) {  //### Add MetaModifier?
7879             if (k->key() == Qt::Key_Backtab
7880                 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7881                 res = focusNextPrevChild(false);
7882             else if (k->key() == Qt::Key_Tab)
7883                 res = focusNextPrevChild(true);
7884             if (res)
7885                 break;
7886         }
7887         keyPressEvent(k);
7888 #ifdef QT_KEYPAD_NAVIGATION
7889         if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7890             && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7891             if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7892                 if (k->key() == Qt::Key_Up)
7893                     res = focusNextPrevChild(false);
7894                 else if (k->key() == Qt::Key_Down)
7895                     res = focusNextPrevChild(true);
7896             } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7897                 if (k->key() == Qt::Key_Up)
7898                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7899                 else if (k->key() == Qt::Key_Right)
7900                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7901                 else if (k->key() == Qt::Key_Down)
7902                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7903                 else if (k->key() == Qt::Key_Left)
7904                     res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7905             }
7906             if (res) {
7907                 k->accept();
7908                 break;
7909             }
7910         }
7911 #endif
7912 #ifndef QT_NO_WHATSTHIS
7913         if (!k->isAccepted()
7914             && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7915             && d->whatsThis.size()) {
7916             QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7917             k->accept();
7918         }
7919 #endif
7920     }
7921         break;
7922
7923     case QEvent::KeyRelease:
7924         keyReleaseEvent((QKeyEvent*)event);
7925         // fall through
7926     case QEvent::ShortcutOverride:
7927         break;
7928
7929     case QEvent::InputMethod:
7930         inputMethodEvent((QInputMethodEvent *) event);
7931         break;
7932
7933     case QEvent::InputMethodQuery:
7934         if (testAttribute(Qt::WA_InputMethodEnabled)) {
7935             QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7936             Qt::InputMethodQueries queries = query->queries();
7937             for (uint i = 0; i < 32; ++i) {
7938                 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7939                 if (q) {
7940                     QVariant v = inputMethodQuery(q);
7941                     if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
7942                         v = QVariant(true); // special case for Qt4 compatibility
7943                     query->setValue(q, v);
7944                 }
7945             }
7946             query->accept();
7947         }
7948         break;
7949
7950     case QEvent::PolishRequest:
7951         ensurePolished();
7952         break;
7953
7954     case QEvent::Polish: {
7955         style()->polish(this);
7956         setAttribute(Qt::WA_WState_Polished);
7957         if (!QApplication::font(this).isCopyOf(QApplication::font()))
7958             d->resolveFont();
7959         if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7960             d->resolvePalette();
7961     }
7962         break;
7963
7964     case QEvent::ApplicationWindowIconChange:
7965         if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7966             d->setWindowIcon_sys();
7967             d->setWindowIcon_helper();
7968         }
7969         break;
7970     case QEvent::FocusIn:
7971         focusInEvent((QFocusEvent*)event);
7972         d->updateWidgetTransform();
7973         break;
7974
7975     case QEvent::FocusOut:
7976         focusOutEvent((QFocusEvent*)event);
7977         break;
7978
7979     case QEvent::Enter:
7980 #ifndef QT_NO_STATUSTIP
7981         if (d->statusTip.size()) {
7982             QStatusTipEvent tip(d->statusTip);
7983             QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7984         }
7985 #endif
7986         enterEvent(event);
7987         break;
7988
7989     case QEvent::Leave:
7990 #ifndef QT_NO_STATUSTIP
7991         if (d->statusTip.size()) {
7992             QString empty;
7993             QStatusTipEvent tip(empty);
7994             QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7995         }
7996 #endif
7997         leaveEvent(event);
7998         break;
7999
8000     case QEvent::HoverEnter:
8001     case QEvent::HoverLeave:
8002         update();
8003         break;
8004
8005     case QEvent::Paint:
8006         // At this point the event has to be delivered, regardless
8007         // whether the widget isVisible() or not because it
8008         // already went through the filters
8009         paintEvent((QPaintEvent*)event);
8010         break;
8011
8012     case QEvent::Move:
8013         moveEvent((QMoveEvent*)event);
8014         d->updateWidgetTransform();
8015         break;
8016
8017     case QEvent::Resize:
8018         resizeEvent((QResizeEvent*)event);
8019         d->updateWidgetTransform();
8020         break;
8021
8022     case QEvent::Close:
8023         closeEvent((QCloseEvent *)event);
8024         break;
8025
8026 #ifndef QT_NO_CONTEXTMENU
8027     case QEvent::ContextMenu:
8028         switch (data->context_menu_policy) {
8029         case Qt::PreventContextMenu:
8030             break;
8031         case Qt::DefaultContextMenu:
8032             contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8033             break;
8034         case Qt::CustomContextMenu:
8035             emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8036             break;
8037 #ifndef QT_NO_MENU
8038         case Qt::ActionsContextMenu:
8039             if (d->actions.count()) {
8040                 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8041                             0, this);
8042                 break;
8043             }
8044             // fall through
8045 #endif
8046         default:
8047             event->ignore();
8048             break;
8049         }
8050         break;
8051 #endif // QT_NO_CONTEXTMENU
8052
8053 #ifndef QT_NO_DRAGANDDROP
8054     case QEvent::Drop:
8055         dropEvent((QDropEvent*) event);
8056         break;
8057
8058     case QEvent::DragEnter:
8059         dragEnterEvent((QDragEnterEvent*) event);
8060         break;
8061
8062     case QEvent::DragMove:
8063         dragMoveEvent((QDragMoveEvent*) event);
8064         break;
8065
8066     case QEvent::DragLeave:
8067         dragLeaveEvent((QDragLeaveEvent*) event);
8068         break;
8069 #endif
8070
8071     case QEvent::Show:
8072         showEvent((QShowEvent*) event);
8073         break;
8074
8075     case QEvent::Hide:
8076         hideEvent((QHideEvent*) event);
8077         break;
8078
8079     case QEvent::ShowWindowRequest:
8080         if (!isHidden())
8081             d->show_sys();
8082         break;
8083
8084     case QEvent::ApplicationFontChange:
8085         d->resolveFont();
8086         break;
8087     case QEvent::ApplicationPaletteChange:
8088         if (!(windowType() == Qt::Desktop))
8089             d->resolvePalette();
8090         break;
8091
8092     case QEvent::ToolBarChange:
8093     case QEvent::ActivationChange:
8094     case QEvent::EnabledChange:
8095     case QEvent::FontChange:
8096     case QEvent::StyleChange:
8097     case QEvent::PaletteChange:
8098     case QEvent::WindowTitleChange:
8099     case QEvent::IconTextChange:
8100     case QEvent::ModifiedChange:
8101     case QEvent::MouseTrackingChange:
8102     case QEvent::ParentChange:
8103     case QEvent::WindowStateChange:
8104     case QEvent::LocaleChange:
8105     case QEvent::MacSizeChange:
8106     case QEvent::ContentsRectChange:
8107     case QEvent::ThemeChange:
8108         changeEvent(event);
8109         break;
8110
8111     case QEvent::WindowActivate:
8112     case QEvent::WindowDeactivate: {
8113         if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8114             update();
8115         QList<QObject*> childList = d->children;
8116         for (int i = 0; i < childList.size(); ++i) {
8117             QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8118             if (w && w->isVisible() && !w->isWindow())
8119                 QApplication::sendEvent(w, event);
8120         }
8121         break; }
8122
8123     case QEvent::LanguageChange:
8124         changeEvent(event);
8125         {
8126             QList<QObject*> childList = d->children;
8127             for (int i = 0; i < childList.size(); ++i) {
8128                 QObject *o = childList.at(i);
8129                 if (o)
8130                     QApplication::sendEvent(o, event);
8131             }
8132         }
8133         update();
8134         break;
8135
8136     case QEvent::ApplicationLayoutDirectionChange:
8137         d->resolveLayoutDirection();
8138         break;
8139
8140     case QEvent::LayoutDirectionChange:
8141         if (d->layout)
8142             d->layout->invalidate();
8143         update();
8144         changeEvent(event);
8145         break;
8146     case QEvent::UpdateRequest:
8147         d->syncBackingStore();
8148         break;
8149     case QEvent::UpdateLater:
8150         update(static_cast<QUpdateLaterEvent*>(event)->region());
8151         break;
8152     case QEvent::StyleAnimationUpdate:
8153         update();
8154         break;
8155
8156     case QEvent::WindowBlocked:
8157     case QEvent::WindowUnblocked:
8158         if (!d->children.isEmpty()) {
8159             QWidget *modalWidget = QApplication::activeModalWidget();
8160             for (int i = 0; i < d->children.size(); ++i) {
8161                 QObject *o = d->children.at(i);
8162                 if (o && o != modalWidget && o->isWidgetType()) {
8163                     QWidget *w  = static_cast<QWidget *>(o);
8164                     // do not forward the event to child windows; QApplication does this for us
8165                     if (!w->isWindow())
8166                         QApplication::sendEvent(w, event);
8167                 }
8168             }
8169         }
8170 #if defined(Q_WS_WIN)
8171             setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8172 #endif
8173         break;
8174 #ifndef QT_NO_TOOLTIP
8175     case QEvent::ToolTip:
8176         if (!d->toolTip.isEmpty())
8177             QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8178         else
8179             event->ignore();
8180         break;
8181 #endif
8182 #ifndef QT_NO_WHATSTHIS
8183     case QEvent::WhatsThis:
8184         if (d->whatsThis.size())
8185             QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8186         else
8187             event->ignore();
8188         break;
8189     case QEvent::QueryWhatsThis:
8190         if (d->whatsThis.isEmpty())
8191             event->ignore();
8192         break;
8193 #endif
8194     case QEvent::EmbeddingControl:
8195         d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8196         data->fstrut_dirty = false;
8197 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8198         d->topData()->embedded = 1;
8199 #endif
8200         break;
8201 #ifndef QT_NO_ACTION
8202     case QEvent::ActionAdded:
8203     case QEvent::ActionRemoved:
8204     case QEvent::ActionChanged:
8205         actionEvent((QActionEvent*)event);
8206         break;
8207 #endif
8208
8209     case QEvent::KeyboardLayoutChange:
8210         {
8211             changeEvent(event);
8212
8213             // inform children of the change
8214             QList<QObject*> childList = d->children;
8215             for (int i = 0; i < childList.size(); ++i) {
8216                 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8217                 if (w && w->isVisible() && !w->isWindow())
8218                     QApplication::sendEvent(w, event);
8219             }
8220             break;
8221         }
8222 #ifdef Q_WS_MAC
8223     case QEvent::MacGLWindowChange:
8224         d->needWindowChange = false;
8225         break;
8226 #endif
8227     case QEvent::TouchBegin:
8228     case QEvent::TouchUpdate:
8229     case QEvent::TouchEnd:
8230     case QEvent::TouchCancel:
8231     {
8232         event->ignore();
8233         break;
8234     }
8235 #ifndef QT_NO_GESTURES
8236     case QEvent::Gesture:
8237         event->ignore();
8238         break;
8239 #endif
8240 #ifndef QT_NO_PROPERTIES
8241     case QEvent::DynamicPropertyChange: {
8242         const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8243         if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8244             uint value = property(propName.constData()).toUInt();
8245             if (!d->extra)
8246                 d->createExtra();
8247             const char axis = propName.at(12);
8248             if (axis == 'X')
8249                 d->extra->customDpiX = value;
8250             else if (axis == 'Y')
8251                 d->extra->customDpiY = value;
8252             d->updateFont(d->data.fnt);
8253         }
8254         // fall through
8255     }
8256 #endif
8257     default:
8258         return QObject::event(event);
8259     }
8260     return true;
8261 }
8262
8263 /*!
8264   This event handler can be reimplemented to handle state changes.
8265
8266   The state being changed in this event can be retrieved through the \a event
8267   supplied.
8268
8269   Change events include: QEvent::ToolBarChange,
8270   QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8271   QEvent::StyleChange, QEvent::PaletteChange,
8272   QEvent::WindowTitleChange, QEvent::IconTextChange,
8273   QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8274   QEvent::ParentChange, QEvent::WindowStateChange,
8275   QEvent::LanguageChange, QEvent::LocaleChange,
8276   QEvent::LayoutDirectionChange.
8277
8278 */
8279 void QWidget::changeEvent(QEvent * event)
8280 {
8281     switch(event->type()) {
8282     case QEvent::EnabledChange: {
8283         update();
8284 #ifndef QT_NO_ACCESSIBILITY
8285         QAccessible::State s;
8286         s.disabled = true;
8287         QAccessibleStateChangeEvent event(this, s);
8288         QAccessible::updateAccessibility(&event);
8289 #endif
8290         break;
8291     }
8292
8293     case QEvent::FontChange:
8294     case QEvent::StyleChange: {
8295         Q_D(QWidget);
8296         update();
8297         updateGeometry();
8298         if (d->layout)
8299             d->layout->invalidate();
8300         break;
8301     }
8302
8303     case QEvent::PaletteChange:
8304         update();
8305         break;
8306
8307     case QEvent::ThemeChange:
8308         if (QApplication::desktopSettingsAware() && windowType() != Qt::Desktop
8309             && qApp && !QApplication::closingDown()) {
8310             if (testAttribute(Qt::WA_WState_Polished))
8311                 QApplication::style()->unpolish(this);
8312             if (testAttribute(Qt::WA_WState_Polished))
8313                 QApplication::style()->polish(this);
8314             QEvent styleChangedEvent(QEvent::StyleChange);
8315             QCoreApplication::sendEvent(this, &styleChangedEvent);
8316             if (isVisible())
8317                 update();
8318         }
8319         break;
8320
8321 #ifdef Q_OS_MAC
8322     case QEvent::MacSizeChange:
8323         updateGeometry();
8324         break;
8325 #elif defined Q_WS_MAC
8326     case QEvent::ToolTipChange:
8327     case QEvent::MouseTrackingChange:
8328         qt_mac_update_mouseTracking(this);
8329         break;
8330 #endif
8331
8332     default:
8333         break;
8334     }
8335 }
8336
8337 /*!
8338     This event handler, for event \a event, can be reimplemented in a
8339     subclass to receive mouse move events for the widget.
8340
8341     If mouse tracking is switched off, mouse move events only occur if
8342     a mouse button is pressed while the mouse is being moved. If mouse
8343     tracking is switched on, mouse move events occur even if no mouse
8344     button is pressed.
8345
8346     QMouseEvent::pos() reports the position of the mouse cursor,
8347     relative to this widget. For press and release events, the
8348     position is usually the same as the position of the last mouse
8349     move event, but it might be different if the user's hand shakes.
8350     This is a feature of the underlying window system, not Qt.
8351
8352     If you want to show a tooltip immediately, while the mouse is
8353     moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8354     and show them as a tooltip), you must first enable mouse tracking
8355     as described above. Then, to ensure that the tooltip is updated
8356     immediately, you must call QToolTip::showText() instead of
8357     setToolTip() in your implementation of mouseMoveEvent().
8358
8359     \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8360     mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8361 */
8362
8363 void QWidget::mouseMoveEvent(QMouseEvent *event)
8364 {
8365     event->ignore();
8366 }
8367
8368 /*!
8369     This event handler, for event \a event, can be reimplemented in a
8370     subclass to receive mouse press events for the widget.
8371
8372     If you create new widgets in the mousePressEvent() the
8373     mouseReleaseEvent() may not end up where you expect, depending on
8374     the underlying window system (or X11 window manager), the widgets'
8375     location and maybe more.
8376
8377     The default implementation implements the closing of popup widgets
8378     when you click outside the window. For other widget types it does
8379     nothing.
8380
8381     \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8382     mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8383 */
8384
8385 void QWidget::mousePressEvent(QMouseEvent *event)
8386 {
8387     event->ignore();
8388     if ((windowType() == Qt::Popup)) {
8389         event->accept();
8390         QWidget* w;
8391         while ((w = QApplication::activePopupWidget()) && w != this){
8392             w->close();
8393             if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8394                 w->hide(); // hide at least
8395         }
8396         if (!rect().contains(event->pos())){
8397             close();
8398         }
8399     }
8400 }
8401
8402 /*!
8403     This event handler, for event \a event, can be reimplemented in a
8404     subclass to receive mouse release events for the widget.
8405
8406     \sa mousePressEvent(), mouseDoubleClickEvent(),
8407     mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8408 */
8409
8410 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8411 {
8412     event->ignore();
8413 }
8414
8415 /*!
8416     This event handler, for event \a event, can be reimplemented in a
8417     subclass to receive mouse double click events for the widget.
8418
8419     The default implementation generates a normal mouse press event.
8420
8421     \note The widget will also receive mouse press and mouse release
8422     events in addition to the double click event. It is up to the
8423     developer to ensure that the application interprets these events
8424     correctly.
8425
8426     \sa mousePressEvent(), mouseReleaseEvent(), mouseMoveEvent(),
8427     event(), QMouseEvent
8428 */
8429
8430 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8431 {
8432     Q_UNUSED(event);
8433 }
8434
8435 #ifndef QT_NO_WHEELEVENT
8436 /*!
8437     This event handler, for event \a event, can be reimplemented in a
8438     subclass to receive wheel events for the widget.
8439
8440     If you reimplement this handler, it is very important that you
8441     \l{QWheelEvent}{ignore()} the event if you do not handle
8442     it, so that the widget's parent can interpret it.
8443
8444     The default implementation ignores the event.
8445
8446     \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8447     QWheelEvent
8448 */
8449
8450 void QWidget::wheelEvent(QWheelEvent *event)
8451 {
8452     event->ignore();
8453 }
8454 #endif // QT_NO_WHEELEVENT
8455
8456 #ifndef QT_NO_TABLETEVENT
8457 /*!
8458     This event handler, for event \a event, can be reimplemented in a
8459     subclass to receive tablet events for the widget.
8460
8461     If you reimplement this handler, it is very important that you
8462     \l{QTabletEvent}{ignore()} the event if you do not handle
8463     it, so that the widget's parent can interpret it.
8464
8465     The default implementation ignores the event.
8466
8467     \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8468     QTabletEvent
8469 */
8470
8471 void QWidget::tabletEvent(QTabletEvent *event)
8472 {
8473     event->ignore();
8474 }
8475 #endif // QT_NO_TABLETEVENT
8476
8477 /*!
8478     This event handler, for event \a event, can be reimplemented in a
8479     subclass to receive key press events for the widget.
8480
8481     A widget must call setFocusPolicy() to accept focus initially and
8482     have focus in order to receive a key press event.
8483
8484     If you reimplement this handler, it is very important that you
8485     call the base class implementation if you do not act upon the key.
8486
8487     The default implementation closes popup widgets if the user
8488     presses Esc. Otherwise the event is ignored, so that the widget's
8489     parent can interpret it.
8490
8491     Note that QKeyEvent starts with isAccepted() == true, so you do not
8492     need to call QKeyEvent::accept() - just do not call the base class
8493     implementation if you act upon the key.
8494
8495     \sa keyReleaseEvent(), setFocusPolicy(),
8496     focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8497 */
8498
8499 void QWidget::keyPressEvent(QKeyEvent *event)
8500 {
8501     if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8502         event->accept();
8503         close();
8504     } else {
8505         event->ignore();
8506     }
8507 }
8508
8509 /*!
8510     This event handler, for event \a event, can be reimplemented in a
8511     subclass to receive key release events for the widget.
8512
8513     A widget must \l{setFocusPolicy()}{accept focus}
8514     initially and \l{hasFocus()}{have focus} in order to
8515     receive a key release event.
8516
8517     If you reimplement this handler, it is very important that you
8518     call the base class implementation if you do not act upon the key.
8519
8520     The default implementation ignores the event, so that the widget's
8521     parent can interpret it.
8522
8523     Note that QKeyEvent starts with isAccepted() == true, so you do not
8524     need to call QKeyEvent::accept() - just do not call the base class
8525     implementation if you act upon the key.
8526
8527     \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8528     focusInEvent(), focusOutEvent(), event(), QKeyEvent
8529 */
8530
8531 void QWidget::keyReleaseEvent(QKeyEvent *event)
8532 {
8533     event->ignore();
8534 }
8535
8536 /*!
8537     \fn void QWidget::focusInEvent(QFocusEvent *event)
8538
8539     This event handler can be reimplemented in a subclass to receive
8540     keyboard focus events (focus received) for the widget. The event
8541     is passed in the \a event parameter
8542
8543     A widget normally must setFocusPolicy() to something other than
8544     Qt::NoFocus in order to receive focus events. (Note that the
8545     application programmer can call setFocus() on any widget, even
8546     those that do not normally accept focus.)
8547
8548     The default implementation updates the widget (except for windows
8549     that do not specify a focusPolicy()).
8550
8551     \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8552     keyReleaseEvent(), event(), QFocusEvent
8553 */
8554
8555 void QWidget::focusInEvent(QFocusEvent *)
8556 {
8557     if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8558         update();
8559     }
8560 }
8561
8562 /*!
8563     \fn void QWidget::focusOutEvent(QFocusEvent *event)
8564
8565     This event handler can be reimplemented in a subclass to receive
8566     keyboard focus events (focus lost) for the widget. The events is
8567     passed in the \a event parameter.
8568
8569     A widget normally must setFocusPolicy() to something other than
8570     Qt::NoFocus in order to receive focus events. (Note that the
8571     application programmer can call setFocus() on any widget, even
8572     those that do not normally accept focus.)
8573
8574     The default implementation updates the widget (except for windows
8575     that do not specify a focusPolicy()).
8576
8577     \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8578     keyReleaseEvent(), event(), QFocusEvent
8579 */
8580
8581 void QWidget::focusOutEvent(QFocusEvent *)
8582 {
8583     if (focusPolicy() != Qt::NoFocus || !isWindow())
8584         update();
8585 }
8586
8587 /*!
8588     \fn void QWidget::enterEvent(QEvent *event)
8589
8590     This event handler can be reimplemented in a subclass to receive
8591     widget enter events which are passed in the \a event parameter.
8592
8593     An event is sent to the widget when the mouse cursor enters the
8594     widget.
8595
8596     \sa leaveEvent(), mouseMoveEvent(), event()
8597 */
8598
8599 void QWidget::enterEvent(QEvent *)
8600 {
8601 }
8602
8603 // ### Qt 6: void QWidget::enterEvent(QEnterEvent *).
8604
8605 /*!
8606     \fn void QWidget::leaveEvent(QEvent *event)
8607
8608     This event handler can be reimplemented in a subclass to receive
8609     widget leave events which are passed in the \a event parameter.
8610
8611     A leave event is sent to the widget when the mouse cursor leaves
8612     the widget.
8613
8614     \sa enterEvent(), mouseMoveEvent(), event()
8615 */
8616
8617 void QWidget::leaveEvent(QEvent *)
8618 {
8619 }
8620
8621 /*!
8622     \fn void QWidget::paintEvent(QPaintEvent *event)
8623
8624     This event handler can be reimplemented in a subclass to receive paint
8625     events passed in \a event.
8626
8627     A paint event is a request to repaint all or part of a widget. It can
8628     happen for one of the following reasons:
8629
8630     \list
8631         \li repaint() or update() was invoked,
8632         \li the widget was obscured and has now been uncovered, or
8633         \li many other reasons.
8634     \endlist
8635
8636     Many widgets can simply repaint their entire surface when asked to, but
8637     some slow widgets need to optimize by painting only the requested region:
8638     QPaintEvent::region(). This speed optimization does not change the result,
8639     as painting is clipped to that region during event processing. QListView
8640     and QTableView do this, for example.
8641
8642     Qt also tries to speed up painting by merging multiple paint events into
8643     one. When update() is called several times or the window system sends
8644     several paint events, Qt merges these events into one event with a larger
8645     region (see QRegion::united()). The repaint() function does not permit this
8646     optimization, so we suggest using update() whenever possible.
8647
8648     When the paint event occurs, the update region has normally been erased, so
8649     you are painting on the widget's background.
8650
8651     The background can be set using setBackgroundRole() and setPalette().
8652
8653     Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8654     is no need to write double-buffering code in paintEvent() to avoid flicker.
8655
8656     \b{Note for the X11 platform}: It is possible to toggle global double
8657     buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8658
8659     \snippet code/src_gui_kernel_qwidget.cpp 14
8660
8661     \note Generally, you should refrain from calling update() or repaint()
8662     \b{inside} a paintEvent(). For example, calling update() or repaint() on
8663     children inside a paintevent() results in undefined behavior; the child may
8664     or may not get a paint event.
8665
8666     \warning If you are using a custom paint engine without Qt's backingstore,
8667     Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8668     never be called; the backingstore will be used instead.
8669
8670     \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8671     {Analog Clock Example}
8672 */
8673
8674 void QWidget::paintEvent(QPaintEvent *)
8675 {
8676 }
8677
8678
8679 /*!
8680     \fn void QWidget::moveEvent(QMoveEvent *event)
8681
8682     This event handler can be reimplemented in a subclass to receive
8683     widget move events which are passed in the \a event parameter.
8684     When the widget receives this event, it is already at the new
8685     position.
8686
8687     The old position is accessible through QMoveEvent::oldPos().
8688
8689     \sa resizeEvent(), event(), move(), QMoveEvent
8690 */
8691
8692 void QWidget::moveEvent(QMoveEvent *)
8693 {
8694 }
8695
8696
8697 /*!
8698     This event handler can be reimplemented in a subclass to receive
8699     widget resize events which are passed in the \a event parameter.
8700     When resizeEvent() is called, the widget already has its new
8701     geometry. The old size is accessible through
8702     QResizeEvent::oldSize().
8703
8704     The widget will be erased and receive a paint event immediately
8705     after processing the resize event. No drawing need be (or should
8706     be) done inside this handler.
8707
8708
8709     \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8710         {Scribble Example}
8711 */
8712
8713 void QWidget::resizeEvent(QResizeEvent * /* event */)
8714 {
8715 }
8716
8717 #ifndef QT_NO_ACTION
8718 /*!
8719     \fn void QWidget::actionEvent(QActionEvent *event)
8720
8721     This event handler is called with the given \a event whenever the
8722     widget's actions are changed.
8723
8724     \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8725 */
8726 void QWidget::actionEvent(QActionEvent *)
8727 {
8728
8729 }
8730 #endif
8731
8732 /*!
8733     This event handler is called with the given \a event when Qt receives a window
8734     close request for a top-level widget from the window system.
8735
8736     By default, the event is accepted and the widget is closed. You can reimplement
8737     this function to change the way the widget responds to window close requests.
8738     For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8739     on all events.
8740
8741     Main window applications typically use reimplementations of this function to check
8742     whether the user's work has been saved and ask for permission before closing.
8743     For example, the \l{Application Example} uses a helper function to determine whether
8744     or not to close the window:
8745
8746     \snippet mainwindows/application/mainwindow.cpp 3
8747     \snippet mainwindows/application/mainwindow.cpp 4
8748
8749     \sa event(), hide(), close(), QCloseEvent, {Application Example}
8750 */
8751
8752 void QWidget::closeEvent(QCloseEvent *event)
8753 {
8754     event->accept();
8755 }
8756
8757 #ifndef QT_NO_CONTEXTMENU
8758 /*!
8759     This event handler, for event \a event, can be reimplemented in a
8760     subclass to receive widget context menu events.
8761
8762     The handler is called when the widget's \l contextMenuPolicy is
8763     Qt::DefaultContextMenu.
8764
8765     The default implementation ignores the context event.
8766     See the \l QContextMenuEvent documentation for more details.
8767
8768     \sa event(), QContextMenuEvent, customContextMenuRequested()
8769 */
8770
8771 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8772 {
8773     event->ignore();
8774 }
8775 #endif // QT_NO_CONTEXTMENU
8776
8777
8778 /*!
8779     This event handler, for event \a event, can be reimplemented in a
8780     subclass to receive Input Method composition events. This handler
8781     is called when the state of the input method changes.
8782
8783     Note that when creating custom text editing widgets, the
8784     Qt::WA_InputMethodEnabled window attribute must be set explicitly
8785     (using the setAttribute() function) in order to receive input
8786     method events.
8787
8788     The default implementation calls event->ignore(), which rejects the
8789     Input Method event. See the \l QInputMethodEvent documentation for more
8790     details.
8791
8792     \sa event(), QInputMethodEvent
8793 */
8794 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8795 {
8796     event->ignore();
8797 }
8798
8799 /*!
8800     This method is only relevant for input widgets. It is used by the
8801     input method to query a set of properties of the widget to be
8802     able to support complex input method operations as support for
8803     surrounding text and reconversions.
8804
8805     \a query specifies which property is queried.
8806
8807     \sa inputMethodEvent(), QInputMethodEven, inputMethodHints
8808 */
8809 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8810 {
8811     switch(query) {
8812     case Qt::ImCursorRectangle:
8813         return QRect(width()/2, 0, 1, height());
8814     case Qt::ImFont:
8815         return font();
8816     case Qt::ImAnchorPosition:
8817         // Fallback.
8818         return inputMethodQuery(Qt::ImCursorPosition);
8819     case Qt::ImHints:
8820         return (int)inputMethodHints();
8821     default:
8822         return QVariant();
8823     }
8824 }
8825
8826 /*!
8827     \property QWidget::inputMethodHints
8828     \brief What input method specific hints the widget has.
8829
8830     This is only relevant for input widgets. It is used by
8831     the input method to retrieve hints as to how the input method
8832     should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8833     is set, the input method may change its visual components to reflect
8834     that only numbers can be entered.
8835
8836     \note The flags are only hints, so the particular input method
8837           implementation is free to ignore them. If you want to be
8838           sure that a certain type of characters are entered,
8839           you should also set a QValidator on the widget.
8840
8841     The default value is Qt::ImhNone.
8842
8843     \since 4.6
8844
8845     \sa inputMethodQuery()
8846 */
8847 Qt::InputMethodHints QWidget::inputMethodHints() const
8848 {
8849 #ifndef QT_NO_IM
8850     const QWidgetPrivate *priv = d_func();
8851     while (priv->inheritsInputMethodHints) {
8852         priv = priv->q_func()->parentWidget()->d_func();
8853         Q_ASSERT(priv);
8854     }
8855     return priv->imHints;
8856 #else //QT_NO_IM
8857     return 0;
8858 #endif //QT_NO_IM
8859 }
8860
8861 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8862 {
8863 #ifndef QT_NO_IM
8864     Q_D(QWidget);
8865     d->imHints = hints;
8866     qApp->inputMethod()->update(Qt::ImHints);
8867 #endif //QT_NO_IM
8868 }
8869
8870
8871 #ifndef QT_NO_DRAGANDDROP
8872
8873 /*!
8874     \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8875
8876     This event handler is called when a drag is in progress and the
8877     mouse enters this widget. The event is passed in the \a event parameter.
8878
8879     If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8880     move events}.
8881
8882     See the \l{dnd.html}{Drag-and-drop documentation} for an
8883     overview of how to provide drag-and-drop in your application.
8884
8885     \sa QDrag, QDragEnterEvent
8886 */
8887 void QWidget::dragEnterEvent(QDragEnterEvent *)
8888 {
8889 }
8890
8891 /*!
8892     \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8893
8894     This event handler is called if a drag is in progress, and when
8895     any of the following conditions occur: the cursor enters this widget,
8896     the cursor moves within this widget, or a modifier key is pressed on
8897     the keyboard while this widget has the focus. The event is passed
8898     in the \a event parameter.
8899
8900     See the \l{dnd.html}{Drag-and-drop documentation} for an
8901     overview of how to provide drag-and-drop in your application.
8902
8903     \sa QDrag, QDragMoveEvent
8904 */
8905 void QWidget::dragMoveEvent(QDragMoveEvent *)
8906 {
8907 }
8908
8909 /*!
8910     \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8911
8912     This event handler is called when a drag is in progress and the
8913     mouse leaves this widget. The event is passed in the \a event
8914     parameter.
8915
8916     See the \l{dnd.html}{Drag-and-drop documentation} for an
8917     overview of how to provide drag-and-drop in your application.
8918
8919     \sa QDrag, QDragLeaveEvent
8920 */
8921 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8922 {
8923 }
8924
8925 /*!
8926     \fn void QWidget::dropEvent(QDropEvent *event)
8927
8928     This event handler is called when the drag is dropped on this
8929     widget. The event is passed in the \a event parameter.
8930
8931     See the \l{dnd.html}{Drag-and-drop documentation} for an
8932     overview of how to provide drag-and-drop in your application.
8933
8934     \sa QDrag, QDropEvent
8935 */
8936 void QWidget::dropEvent(QDropEvent *)
8937 {
8938 }
8939
8940 #endif // QT_NO_DRAGANDDROP
8941
8942 /*!
8943     \fn void QWidget::showEvent(QShowEvent *event)
8944
8945     This event handler can be reimplemented in a subclass to receive
8946     widget show events which are passed in the \a event parameter.
8947
8948     Non-spontaneous show events are sent to widgets immediately
8949     before they are shown. The spontaneous show events of windows are
8950     delivered afterwards.
8951
8952     Note: A widget receives spontaneous show and hide events when its
8953     mapping status is changed by the window system, e.g. a spontaneous
8954     hide event when the user minimizes the window, and a spontaneous
8955     show event when the window is restored again. After receiving a
8956     spontaneous hide event, a widget is still considered visible in
8957     the sense of isVisible().
8958
8959     \sa visible, event(), QShowEvent
8960 */
8961 void QWidget::showEvent(QShowEvent *)
8962 {
8963 }
8964
8965 /*!
8966     \fn void QWidget::hideEvent(QHideEvent *event)
8967
8968     This event handler can be reimplemented in a subclass to receive
8969     widget hide events. The event is passed in the \a event parameter.
8970
8971     Hide events are sent to widgets immediately after they have been
8972     hidden.
8973
8974     Note: A widget receives spontaneous show and hide events when its
8975     mapping status is changed by the window system, e.g. a spontaneous
8976     hide event when the user minimizes the window, and a spontaneous
8977     show event when the window is restored again. After receiving a
8978     spontaneous hide event, a widget is still considered visible in
8979     the sense of isVisible().
8980
8981     \sa visible, event(), QHideEvent
8982 */
8983 void QWidget::hideEvent(QHideEvent *)
8984 {
8985 }
8986
8987 /*!
8988     This special event handler can be reimplemented in a subclass to
8989     receive native platform events identified by \a eventType
8990     which are passed in the \a message parameter.
8991
8992     In your reimplementation of this function, if you want to stop the
8993     event being handled by Qt, return true and set \a result.
8994     If you return false, this native event is passed back to Qt,
8995     which translates the event into a Qt event and sends it to the widget.
8996
8997     \note Events are only delivered to this event handler if the widget is
8998     has a native Window handle.
8999
9000     \note This function superseedes the event filter functions
9001     x11Event(), winEvent() and macEvent() of Qt 4.
9002
9003     \table
9004     \header \li Platform \li Event Type Identifier \li Message Type \li Result Type
9005     \row \li Windows \li "windows_generic_MSG" \li MSG * \li LRESULT
9006     \endtable
9007 */
9008
9009 bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
9010 {
9011     Q_UNUSED(eventType);
9012     Q_UNUSED(message);
9013     Q_UNUSED(result);
9014     return false;
9015 }
9016
9017 /*!
9018     Ensures that the widget has been polished by QStyle (i.e., has a
9019     proper font and palette).
9020
9021     QWidget calls this function after it has been fully constructed
9022     but before it is shown the very first time. You can call this
9023     function if you want to ensure that the widget is polished before
9024     doing an operation, e.g., the correct font size might be needed in
9025     the widget's sizeHint() reimplementation. Note that this function
9026     \e is called from the default implementation of sizeHint().
9027
9028     Polishing is useful for final initialization that must happen after
9029     all constructors (from base classes as well as from subclasses)
9030     have been called.
9031
9032     If you need to change some settings when a widget is polished,
9033     reimplement event() and handle the QEvent::Polish event type.
9034
9035     \b{Note:} The function is declared const so that it can be called from
9036     other const functions (e.g., sizeHint()).
9037
9038     \sa event()
9039 */
9040 void QWidget::ensurePolished() const
9041 {
9042     Q_D(const QWidget);
9043
9044     const QMetaObject *m = metaObject();
9045     if (m == d->polished)
9046         return;
9047     d->polished = m;
9048
9049     QEvent e(QEvent::Polish);
9050     QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9051
9052     // polish children after 'this'
9053     QList<QObject*> children = d->children;
9054     for (int i = 0; i < children.size(); ++i) {
9055         QObject *o = children.at(i);
9056         if(!o->isWidgetType())
9057             continue;
9058         if (QWidget *w = qobject_cast<QWidget *>(o))
9059             w->ensurePolished();
9060     }
9061
9062     if (d->parent && d->sendChildEvents) {
9063         QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9064         QCoreApplication::sendEvent(d->parent, &e);
9065     }
9066 }
9067
9068 /*!
9069     Returns the mask currently set on a widget. If no mask is set the
9070     return value will be an empty region.
9071
9072     \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9073 */
9074 QRegion QWidget::mask() const
9075 {
9076     Q_D(const QWidget);
9077     return d->extra ? d->extra->mask : QRegion();
9078 }
9079
9080 /*!
9081     Returns the layout manager that is installed on this widget, or 0
9082     if no layout manager is installed.
9083
9084     The layout manager sets the geometry of the widget's children
9085     that have been added to the layout.
9086
9087     \sa setLayout(), sizePolicy(), {Layout Management}
9088 */
9089 QLayout *QWidget::layout() const
9090 {
9091     return d_func()->layout;
9092 }
9093
9094
9095 /*!
9096     \fn void QWidget::setLayout(QLayout *layout)
9097
9098     Sets the layout manager for this widget to \a layout.
9099
9100     If there already is a layout manager installed on this widget,
9101     QWidget won't let you install another. You must first delete the
9102     existing layout manager (returned by layout()) before you can
9103     call setLayout() with the new layout.
9104
9105     If \a layout is the layout manger on a different widget, setLayout()
9106     will reparent the layout and make it the layout manager for this widget.
9107
9108     Example:
9109
9110     \snippet layouts/layouts.cpp 24
9111
9112     An alternative to calling this function is to pass this widget to
9113     the layout's constructor.
9114
9115     The QWidget will take ownership of \a layout.
9116
9117     \sa layout(), {Layout Management}
9118 */
9119
9120 void QWidget::setLayout(QLayout *l)
9121 {
9122     if (!l) {
9123         qWarning("QWidget::setLayout: Cannot set layout to 0");
9124         return;
9125     }
9126     if (layout()) {
9127         if (layout() != l)
9128             qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9129                      " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9130                      objectName().toLocal8Bit().data());
9131         return;
9132     }
9133
9134     QObject *oldParent = l->parent();
9135     if (oldParent && oldParent != this) {
9136         if (oldParent->isWidgetType()) {
9137             // Steal the layout off a widget parent. Takes effect when
9138             // morphing laid-out container widgets in Designer.
9139             QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9140             oldParentWidget->takeLayout();
9141         } else {
9142             qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9143                      l->objectName().toLocal8Bit().data(), metaObject()->className(),
9144                      objectName().toLocal8Bit().data());
9145             return;
9146         }
9147     }
9148
9149     Q_D(QWidget);
9150     l->d_func()->topLevel = true;
9151     d->layout = l;
9152     if (oldParent != this) {
9153         l->setParent(this);
9154         l->d_func()->reparentChildWidgets(this);
9155         l->invalidate();
9156     }
9157
9158     if (isWindow() && d->maybeTopData())
9159         d->topData()->sizeAdjusted = false;
9160 }
9161
9162 /*!
9163     \fn QLayout *QWidget::takeLayout()
9164
9165     Remove the layout from the widget.
9166     \since 4.5
9167 */
9168
9169 QLayout *QWidget::takeLayout()
9170 {
9171     Q_D(QWidget);
9172     QLayout *l =  layout();
9173     if (!l)
9174         return 0;
9175     d->layout = 0;
9176     l->setParent(0);
9177     return l;
9178 }
9179
9180 /*!
9181     \property QWidget::sizePolicy
9182     \brief the default layout behavior of the widget
9183
9184     If there is a QLayout that manages this widget's children, the
9185     size policy specified by that layout is used. If there is no such
9186     QLayout, the result of this function is used.
9187
9188     The default policy is Preferred/Preferred, which means that the
9189     widget can be freely resized, but prefers to be the size
9190     sizeHint() returns. Button-like widgets set the size policy to
9191     specify that they may stretch horizontally, but are fixed
9192     vertically. The same applies to lineedit controls (such as
9193     QLineEdit, QSpinBox or an editable QComboBox) and other
9194     horizontally orientated widgets (such as QProgressBar).
9195     QToolButton's are normally square, so they allow growth in both
9196     directions. Widgets that support different directions (such as
9197     QSlider, QScrollBar or QHeader) specify stretching in the
9198     respective direction only. Widgets that can provide scroll bars
9199     (usually subclasses of QScrollArea) tend to specify that they can
9200     use additional space, and that they can make do with less than
9201     sizeHint().
9202
9203     \sa sizeHint(), QLayout, QSizePolicy, updateGeometry()
9204 */
9205 QSizePolicy QWidget::sizePolicy() const
9206 {
9207     Q_D(const QWidget);
9208     return d->size_policy;
9209 }
9210
9211 void QWidget::setSizePolicy(QSizePolicy policy)
9212 {
9213     Q_D(QWidget);
9214     setAttribute(Qt::WA_WState_OwnSizePolicy);
9215     if (policy == d->size_policy)
9216         return;
9217     d->size_policy = policy;
9218
9219 #ifndef QT_NO_GRAPHICSVIEW
9220     if (QWExtra *extra = d->extra) {
9221         if (extra->proxyWidget)
9222             extra->proxyWidget->setSizePolicy(policy);
9223     }
9224 #endif
9225
9226     updateGeometry();
9227
9228     if (isWindow() && d->maybeTopData())
9229         d->topData()->sizeAdjusted = false;
9230 }
9231
9232 /*!
9233     \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9234     \overload
9235
9236     Sets the size policy of the widget to \a horizontal and \a
9237     vertical, with standard stretch and no height-for-width.
9238
9239     \sa QSizePolicy::QSizePolicy()
9240 */
9241
9242 /*!
9243     Returns the preferred height for this widget, given the width \a w.
9244
9245     If this widget has a layout, the default implementation returns
9246     the layout's preferred height.  if there is no layout, the default
9247     implementation returns -1 indicating that the preferred height
9248     does not depend on the width.
9249 */
9250
9251 int QWidget::heightForWidth(int w) const
9252 {
9253     if (layout() && layout()->hasHeightForWidth())
9254         return layout()->totalHeightForWidth(w);
9255     return -1;
9256 }
9257
9258
9259 /*!
9260     \since 5.0
9261
9262     Returns true if the widget's preferred height depends on its width; otherwise returns false.
9263 */ 
9264 bool QWidget::hasHeightForWidth() const
9265 {
9266     Q_D(const QWidget);
9267     return d->layout ? d->layout->hasHeightForWidth() : d->size_policy.hasHeightForWidth();
9268 }
9269
9270 /*!
9271     \fn QWidget *QWidget::childAt(int x, int y) const
9272
9273     Returns the visible child widget at the position (\a{x}, \a{y})
9274     in the widget's coordinate system. If there is no visible child
9275     widget at the specified position, the function returns 0.
9276 */
9277
9278 /*!
9279     \overload
9280
9281     Returns the visible child widget at point \a p in the widget's own
9282     coordinate system.
9283 */
9284
9285 QWidget *QWidget::childAt(const QPoint &p) const
9286 {
9287     return d_func()->childAt_helper(p, false);
9288 }
9289
9290 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9291 {
9292     if (children.isEmpty())
9293         return 0;
9294
9295 #ifdef Q_WS_MAC
9296     Q_Q(const QWidget);
9297     // Unified tool bars on the Mac require special handling since they live outside
9298     // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9299     bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9300                         && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9301     if (includeFrame)
9302         return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9303 #endif
9304
9305     if (!pointInsideRectAndMask(p))
9306         return 0;
9307     return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9308 }
9309
9310 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9311 {
9312 #ifndef Q_WS_MAC
9313     Q_UNUSED(includeFrame);
9314 #endif
9315     for (int i = children.size() - 1; i >= 0; --i) {
9316         QWidget *child = qobject_cast<QWidget *>(children.at(i));
9317         if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9318             || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9319             continue;
9320         }
9321
9322         // Map the point 'p' from parent coordinates to child coordinates.
9323         QPoint childPoint = p;
9324 #ifdef Q_WS_MAC
9325         // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9326         // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9327         // QWidget::mapFromParent won't do the trick.
9328         if (includeFrame && qobject_cast<QToolBar *>(child))
9329             childPoint = qt_mac_nativeMapFromParent(child, p);
9330         else
9331 #endif
9332         childPoint -= child->data->crect.topLeft();
9333
9334         // Check if the point hits the child.
9335         if (!child->d_func()->pointInsideRectAndMask(childPoint))
9336             continue;
9337
9338         // Do the same for the child's descendants.
9339         if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9340             return w;
9341
9342         // We have found our target; namely the child at position 'p'.
9343         return child;
9344     }
9345     return 0;
9346 }
9347
9348 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9349 {
9350     Q_Q(QWidget);
9351     if (widgetItem)
9352         widgetItem->invalidateSizeCache();
9353     QWidget *parent;
9354     if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9355         if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9356             if (parent->d_func()->layout)
9357                 parent->d_func()->layout->invalidate();
9358             else if (parent->isVisible())
9359                 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9360         }
9361     }
9362 }
9363
9364 /*!
9365     Notifies the layout system that this widget has changed and may
9366     need to change geometry.
9367
9368     Call this function if the sizeHint() or sizePolicy() have changed.
9369
9370     For explicitly hidden widgets, updateGeometry() is a no-op. The
9371     layout system will be notified as soon as the widget is shown.
9372 */
9373
9374 void QWidget::updateGeometry()
9375 {
9376     Q_D(QWidget);
9377     d->updateGeometry_helper(false);
9378 }
9379
9380 /*! \property QWidget::windowFlags
9381
9382     Window flags are a combination of a type (e.g. Qt::Dialog) and
9383     zero or more hints to the window system (e.g.
9384     Qt::FramelessWindowHint).
9385
9386     If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9387     window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9388     0) on the desktop. If the widget is a window and becomes a
9389     Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9390     relative to its parent widget.
9391
9392     \note This function calls setParent() when changing the flags for
9393     a window, causing the widget to be hidden. You must call show() to make
9394     the widget visible again..
9395
9396     \sa windowType(), {Window Flags Example}
9397 */
9398 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9399 {
9400     if (data->window_flags == flags)
9401         return;
9402
9403     Q_D(QWidget);
9404
9405     if ((data->window_flags | flags) & Qt::Window) {
9406         // the old type was a window and/or the new type is a window
9407         QPoint oldPos = pos();
9408         bool visible = isVisible();
9409         setParent(parentWidget(), flags);
9410
9411         // if both types are windows or neither of them are, we restore
9412         // the old position
9413         if (!((data->window_flags ^ flags) & Qt::Window)
9414             && (visible || testAttribute(Qt::WA_Moved))) {
9415             move(oldPos);
9416         }
9417         // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9418         d->adjustQuitOnCloseAttribute();
9419     } else {
9420         data->window_flags = flags;
9421     }
9422 }
9423
9424 /*!
9425     Sets the window flags for the widget to \a flags,
9426     \e without telling the window system.
9427
9428     \warning Do not call this function unless you really know what
9429     you're doing.
9430
9431     \sa setWindowFlags()
9432 */
9433 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9434 {
9435     data->window_flags = flags;
9436 }
9437
9438 /*!
9439     \fn Qt::WindowType QWidget::windowType() const
9440
9441     Returns the window type of this widget. This is identical to
9442     windowFlags() & Qt::WindowType_Mask.
9443
9444     \sa windowFlags
9445 */
9446
9447 /*!
9448     Sets the parent of the widget to \a parent, and resets the window
9449     flags. The widget is moved to position (0, 0) in its new parent.
9450
9451     If the new parent widget is in a different window, the
9452     reparented widget and its children are appended to the end of the
9453     \l{setFocusPolicy()}{tab chain} of the new parent
9454     widget, in the same internal order as before. If one of the moved
9455     widgets had keyboard focus, setParent() calls clearFocus() for that
9456     widget.
9457
9458     If the new parent widget is in the same window as the
9459     old parent, setting the parent doesn't change the tab order or
9460     keyboard focus.
9461
9462     If the "new" parent widget is the old parent widget, this function
9463     does nothing.
9464
9465     \note The widget becomes invisible as part of changing its parent,
9466     even if it was previously visible. You must call show() to make the
9467     widget visible again.
9468
9469     \warning It is very unlikely that you will ever need this
9470     function. If you have a widget that changes its content
9471     dynamically, it is far easier to use \l QStackedWidget.
9472
9473     \sa setWindowFlags()
9474 */
9475 void QWidget::setParent(QWidget *parent)
9476 {
9477     if (parent == parentWidget())
9478         return;
9479     setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9480 }
9481
9482 /*!
9483     \overload
9484
9485     This function also takes widget flags, \a f as an argument.
9486 */
9487
9488 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9489 {
9490     Q_D(QWidget);
9491     bool resized = testAttribute(Qt::WA_Resized);
9492     bool wasCreated = testAttribute(Qt::WA_WState_Created);
9493     QWidget *oldtlw = window();
9494
9495     QWidget *desktopWidget = 0;
9496     if (parent && parent->windowType() == Qt::Desktop)
9497         desktopWidget = parent;
9498     bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9499
9500     if (newParent && parent && !desktopWidget) {
9501         if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9502 #ifdef Q_WS_MAC
9503             // On Mac, toolbars inside the unified title bar will never overlap with
9504             // siblings in the content view. So we skip enforce native siblings in that case
9505             && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9506 #endif // Q_WS_MAC
9507         )
9508             parent->d_func()->enforceNativeChildren();
9509         else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9510             setAttribute(Qt::WA_NativeWindow);
9511     }
9512
9513     if (wasCreated) {
9514         if (!testAttribute(Qt::WA_WState_Hidden)) {
9515             hide();
9516             setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9517         }
9518         if (newParent) {
9519             QEvent e(QEvent::ParentAboutToChange);
9520             QApplication::sendEvent(this, &e);
9521         }
9522     }
9523     if (newParent && isAncestorOf(focusWidget()))
9524         focusWidget()->clearFocus();
9525
9526     QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9527     QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9528
9529     d->setParent_sys(parent, f);
9530
9531     QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9532     QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9533     if (oldBsTracker && oldBsTracker != bsTracker)
9534         oldBsTracker->unregisterWidgetSubtree(this);
9535
9536     if (desktopWidget)
9537         parent = 0;
9538
9539     if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9540         if (newParent)
9541             oldBs->removeDirtyWidget(this);
9542         // Move the widget and all its static children from
9543         // the old backing store to the new one.
9544         oldBs->moveStaticWidgets(this);
9545     }
9546
9547     if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
9548         create();
9549
9550     d->reparentFocusWidgets(oldtlw);
9551     setAttribute(Qt::WA_Resized, resized);
9552     if (!testAttribute(Qt::WA_StyleSheet)
9553         && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9554         d->resolveFont();
9555         d->resolvePalette();
9556     }
9557     d->resolveLayoutDirection();
9558     d->resolveLocale();
9559
9560     // Note: GL widgets under WGL or EGL will always need a ParentChange
9561     // event to handle recreation/rebinding of the GL context, hence the
9562     // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9563     // platforms).
9564     if (newParent
9565 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9566         || (f & Qt::MSWindowsOwnDC)
9567 #endif
9568         ) {
9569         // propagate enabled updates enabled state to non-windows
9570         if (!isWindow()) {
9571             if (!testAttribute(Qt::WA_ForceDisabled))
9572                 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9573             if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9574                 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9575         }
9576         d->inheritStyle();
9577
9578         // send and post remaining QObject events
9579         if (parent && d->sendChildEvents) {
9580             QChildEvent e(QEvent::ChildAdded, this);
9581             QApplication::sendEvent(parent, &e);
9582         }
9583
9584 //### already hidden above ---> must probably do something smart on the mac
9585 // #ifdef Q_WS_MAC
9586 //             extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9587 //             if(!qt_mac_is_macdrawer(q)) //special case
9588 //                 q->setAttribute(Qt::WA_WState_Hidden);
9589 // #else
9590 //             q->setAttribute(Qt::WA_WState_Hidden);
9591 //#endif
9592
9593         if (parent && d->sendChildEvents && d->polished) {
9594             QChildEvent e(QEvent::ChildPolished, this);
9595             QCoreApplication::sendEvent(parent, &e);
9596         }
9597
9598         QEvent e(QEvent::ParentChange);
9599         QApplication::sendEvent(this, &e);
9600     }
9601
9602     if (!wasCreated) {
9603         if (isWindow() || parentWidget()->isVisible())
9604             setAttribute(Qt::WA_WState_Hidden, true);
9605         else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9606             setAttribute(Qt::WA_WState_Hidden, false);
9607     }
9608
9609     d->updateIsOpaque();
9610
9611 #ifndef QT_NO_GRAPHICSVIEW
9612     // Embed the widget into a proxy if the parent is embedded.
9613     // ### Doesn't handle reparenting out of an embedded widget.
9614     if (oldtlw->graphicsProxyWidget()) {
9615         if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9616             ancestorProxy->d_func()->unembedSubWindow(this);
9617     }
9618     if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9619         if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9620             ancestorProxy->d_func()->embedSubWindow(this);
9621     }
9622 #endif
9623 }
9624
9625 /*!
9626     Scrolls the widget including its children \a dx pixels to the
9627     right and \a dy downward. Both \a dx and \a dy may be negative.
9628
9629     After scrolling, the widgets will receive paint events for
9630     the areas that need to be repainted. For widgets that Qt knows to
9631     be opaque, this is only the newly exposed parts.
9632     For example, if an opaque widget is scrolled 8 pixels to the left,
9633     only an 8-pixel wide stripe at the right edge needs updating.
9634
9635     Since widgets propagate the contents of their parents by default,
9636     you need to set the \l autoFillBackground property, or use
9637     setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9638     a widget opaque.
9639
9640     For widgets that use contents propagation, a scroll will cause an
9641     update of the entire scroll area.
9642
9643     \sa {Transparency and Double Buffering}
9644 */
9645
9646 void QWidget::scroll(int dx, int dy)
9647 {
9648     if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9649         return;
9650     if (dx == 0 && dy == 0)
9651         return;
9652     Q_D(QWidget);
9653 #ifndef QT_NO_GRAPHICSVIEW
9654     if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9655         // Graphics View maintains its own dirty region as a list of rects;
9656         // until we can connect item updates directly to the view, we must
9657         // separately add a translated dirty region.
9658         if (!d->dirty.isEmpty()) {
9659             foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9660                 proxy->update(rect);
9661         }
9662         proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9663         return;
9664     }
9665 #endif
9666     d->setDirtyOpaqueRegion();
9667     d->scroll_sys(dx, dy);
9668 }
9669
9670 /*!
9671     \overload
9672
9673     This version only scrolls \a r and does not move the children of
9674     the widget.
9675
9676     If \a r is empty or invalid, the result is undefined.
9677
9678     \sa QScrollArea
9679 */
9680 void QWidget::scroll(int dx, int dy, const QRect &r)
9681 {
9682
9683     if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9684         return;
9685     if (dx == 0 && dy == 0)
9686         return;
9687     Q_D(QWidget);
9688 #ifndef QT_NO_GRAPHICSVIEW
9689     if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9690         // Graphics View maintains its own dirty region as a list of rects;
9691         // until we can connect item updates directly to the view, we must
9692         // separately add a translated dirty region.
9693         if (!d->dirty.isEmpty()) {
9694             foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9695                 proxy->update(rect);
9696         }
9697         proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9698         return;
9699     }
9700 #endif
9701     d->scroll_sys(dx, dy, r);
9702 }
9703
9704 /*!
9705     Repaints the widget directly by calling paintEvent() immediately,
9706     unless updates are disabled or the widget is hidden.
9707
9708     We suggest only using repaint() if you need an immediate repaint,
9709     for example during animation. In almost all circumstances update()
9710     is better, as it permits Qt to optimize for speed and minimize
9711     flicker.
9712
9713     \warning If you call repaint() in a function which may itself be
9714     called from paintEvent(), you may get infinite recursion. The
9715     update() function never causes recursion.
9716
9717     \sa update(), paintEvent(), setUpdatesEnabled()
9718 */
9719
9720 void QWidget::repaint()
9721 {
9722     repaint(rect());
9723 }
9724
9725 /*! \overload
9726
9727     This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9728     the widget.
9729
9730     If \a w is negative, it is replaced with \c{width() - x}, and if
9731     \a h is negative, it is replaced width \c{height() - y}.
9732 */
9733 void QWidget::repaint(int x, int y, int w, int h)
9734 {
9735     if (x > data->crect.width() || y > data->crect.height())
9736         return;
9737
9738     if (w < 0)
9739         w = data->crect.width()  - x;
9740     if (h < 0)
9741         h = data->crect.height() - y;
9742
9743     repaint(QRect(x, y, w, h));
9744 }
9745
9746 /*! \overload
9747
9748     This version repaints a rectangle \a rect inside the widget.
9749 */
9750 void QWidget::repaint(const QRect &rect)
9751 {
9752     Q_D(QWidget);
9753
9754     if (testAttribute(Qt::WA_WState_ConfigPending)) {
9755         update(rect);
9756         return;
9757     }
9758
9759     if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9760         return;
9761
9762     if (hasBackingStoreSupport()) {
9763 #ifdef Q_WS_MAC
9764         if (qt_widget_private(this)->isInUnifiedToolbar) {
9765             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9766             return;
9767         }
9768 #endif // Q_WS_MAC
9769         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9770         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9771             tlwExtra->inRepaint = true;
9772             tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9773             tlwExtra->inRepaint = false;
9774         }
9775     } else {
9776         d->repaint_sys(rect);
9777     }
9778 }
9779
9780 /*!
9781     \overload
9782
9783     This version repaints a region \a rgn inside the widget.
9784 */
9785 void QWidget::repaint(const QRegion &rgn)
9786 {
9787     Q_D(QWidget);
9788
9789     if (testAttribute(Qt::WA_WState_ConfigPending)) {
9790         update(rgn);
9791         return;
9792     }
9793
9794     if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9795         return;
9796
9797     if (hasBackingStoreSupport()) {
9798 #ifdef Q_WS_MAC
9799         if (qt_widget_private(this)->isInUnifiedToolbar) {
9800             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9801             return;
9802         }
9803 #endif // Q_WS_MAC
9804         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9805         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9806             tlwExtra->inRepaint = true;
9807             tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
9808             tlwExtra->inRepaint = false;
9809         }
9810     } else {
9811         d->repaint_sys(rgn);
9812     }
9813 }
9814
9815 /*!
9816     Updates the widget unless updates are disabled or the widget is
9817     hidden.
9818
9819     This function does not cause an immediate repaint; instead it
9820     schedules a paint event for processing when Qt returns to the main
9821     event loop. This permits Qt to optimize for more speed and less
9822     flicker than a call to repaint() does.
9823
9824     Calling update() several times normally results in just one
9825     paintEvent() call.
9826
9827     Qt normally erases the widget's area before the paintEvent() call.
9828     If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9829     responsible for painting all its pixels with an opaque color.
9830
9831     \sa repaint(), paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9832 */
9833 void QWidget::update()
9834 {
9835     update(rect());
9836 }
9837
9838 /*! \fn void QWidget::update(int x, int y, int w, int h)
9839     \overload
9840
9841     This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9842     the widget.
9843 */
9844
9845 /*!
9846     \overload
9847
9848     This version updates a rectangle \a rect inside the widget.
9849 */
9850 void QWidget::update(const QRect &rect)
9851 {
9852     if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9853         return;
9854
9855     if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9856         QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9857         return;
9858     }
9859
9860     if (hasBackingStoreSupport()) {
9861 #ifdef Q_WS_MAC
9862         if (qt_widget_private(this)->isInUnifiedToolbar) {
9863             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9864             return;
9865         }
9866 #endif // Q_WS_MAC
9867         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9868         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9869             tlwExtra->backingStoreTracker->markDirty(rect, this);
9870     } else {
9871         d_func()->repaint_sys(rect);
9872     }
9873 }
9874
9875 /*!
9876     \overload
9877
9878     This version repaints a region \a rgn inside the widget.
9879 */
9880 void QWidget::update(const QRegion &rgn)
9881 {
9882     if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9883         return;
9884
9885     if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9886         QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9887         return;
9888     }
9889
9890     if (hasBackingStoreSupport()) {
9891 #ifdef Q_WS_MAC
9892         if (qt_widget_private(this)->isInUnifiedToolbar) {
9893             qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9894             return;
9895         }
9896 #endif // Q_WS_MAC
9897         QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9898         if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9899             tlwExtra->backingStoreTracker->markDirty(rgn, this);
9900     } else {
9901         d_func()->repaint_sys(rgn);
9902     }
9903 }
9904
9905
9906  /*!
9907   \internal
9908
9909   This just sets the corresponding attribute bit to 1 or 0
9910  */
9911 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
9912                                   QWidgetPrivate *d)
9913 {
9914     if (attribute < int(8*sizeof(uint))) {
9915         if (on)
9916             data->widget_attributes |= (1<<attribute);
9917         else
9918             data->widget_attributes &= ~(1<<attribute);
9919     } else {
9920         const int x = attribute - 8*sizeof(uint);
9921         const int int_off = x / (8*sizeof(uint));
9922         if (on)
9923             d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
9924         else
9925             d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
9926     }
9927 }
9928
9929 #ifdef Q_OS_MAC
9930 void QWidgetPrivate::macUpdateSizeAttribute()
9931 {
9932     Q_Q(QWidget);
9933     QEvent event(QEvent::MacSizeChange);
9934     QApplication::sendEvent(q, &event);
9935     for (int i = 0; i < children.size(); ++i) {
9936         QWidget *w = qobject_cast<QWidget *>(children.at(i));
9937         if (w && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
9938               && !q->testAttribute(Qt::WA_MacMiniSize) // no attribute set? inherit from parent
9939               && !w->testAttribute(Qt::WA_MacSmallSize)
9940               && !w->testAttribute(Qt::WA_MacNormalSize))
9941             w->d_func()->macUpdateSizeAttribute();
9942     }
9943     resolveFont();
9944 }
9945 #endif
9946
9947 /*!
9948     Sets the attribute \a attribute on this widget if \a on is true;
9949     otherwise clears the attribute.
9950
9951     \sa testAttribute()
9952 */
9953 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
9954 {
9955     if (testAttribute(attribute) == on)
9956         return;
9957
9958     Q_D(QWidget);
9959     Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
9960                "QWidget::setAttribute(WidgetAttribute, bool)",
9961                "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
9962 #ifdef Q_OS_WIN
9963     // ### Don't use PaintOnScreen+paintEngine() to do native painting in some future release
9964     if (attribute == Qt::WA_PaintOnScreen && on && windowType() != Qt::Desktop && !inherits("QGLWidget")) {
9965         // see qwidget_qpa.cpp, ::paintEngine for details
9966         paintEngine();
9967         if (d->noPaintOnScreen)
9968             return;
9969     }
9970 #endif
9971
9972     setAttribute_internal(attribute, on, data, d);
9973
9974     switch (attribute) {
9975
9976 #ifndef QT_NO_DRAGANDDROP
9977     case Qt::WA_AcceptDrops:  {
9978         if (on && !testAttribute(Qt::WA_DropSiteRegistered))
9979             setAttribute(Qt::WA_DropSiteRegistered, true);
9980         else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
9981             setAttribute(Qt::WA_DropSiteRegistered, false);
9982         QEvent e(QEvent::AcceptDropsChange);
9983         QApplication::sendEvent(this, &e);
9984         break;
9985     }
9986     case Qt::WA_DropSiteRegistered:  {
9987         d->registerDropSite(on);
9988         for (int i = 0; i < d->children.size(); ++i) {
9989             QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
9990             if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
9991                 w->setAttribute(Qt::WA_DropSiteRegistered, on);
9992         }
9993         break;
9994     }
9995 #endif
9996
9997     case Qt::WA_NoChildEventsForParent:
9998         d->sendChildEvents = !on;
9999         break;
10000     case Qt::WA_NoChildEventsFromChildren:
10001         d->receiveChildEvents = !on;
10002         break;
10003     case Qt::WA_MacBrushedMetal:
10004 #ifdef Q_WS_MAC
10005         d->setStyle_helper(style(), false, true);  // Make sure things get unpolished/polished correctly.
10006         // fall through since changing the metal attribute affects the opaque size grip.
10007     case Qt::WA_MacOpaqueSizeGrip:
10008         d->macUpdateOpaqueSizeGrip();
10009         break;
10010     case Qt::WA_MacShowFocusRect:
10011         if (hasFocus()) {
10012             clearFocus();
10013             setFocus();
10014         }
10015         break;
10016     case Qt::WA_Hover:
10017         qt_mac_update_mouseTracking(this);
10018         break;
10019 #endif
10020     case Qt::WA_MacAlwaysShowToolWindow:
10021 #ifdef Q_WS_MAC
10022         d->macUpdateHideOnSuspend();
10023 #endif
10024         break;
10025     case Qt::WA_MacNormalSize:
10026     case Qt::WA_MacSmallSize:
10027     case Qt::WA_MacMiniSize:
10028 #ifdef Q_OS_MAC
10029         {
10030             // We can only have one of these set at a time
10031             const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10032                                                      Qt::WA_MacMiniSize };
10033             for (int i = 0; i < 3; ++i) {
10034                 if (MacSizes[i] != attribute)
10035                     setAttribute_internal(MacSizes[i], false, data, d);
10036             }
10037             d->macUpdateSizeAttribute();
10038         }
10039 #endif
10040         break;
10041     case Qt::WA_ShowModal:
10042         if (!on) {
10043             // reset modality type to NonModal when clearing WA_ShowModal
10044             data->window_modality = Qt::NonModal;
10045         } else if (data->window_modality == Qt::NonModal) {
10046             // determine the modality type if it hasn't been set prior
10047             // to setting WA_ShowModal. set the default to WindowModal
10048             // if we are the child of a group leader; otherwise use
10049             // ApplicationModal.
10050             QWidget *w = parentWidget();
10051             if (w)
10052                 w = w->window();
10053             while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10054                 w = w->parentWidget();
10055                 if (w)
10056                     w = w->window();
10057             }
10058             data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10059                                     ? Qt::WindowModal
10060                                     : Qt::ApplicationModal;
10061             // Some window managers do not allow us to enter modality after the
10062             // window is visible.The window must be hidden before changing the
10063             // windowModality property and then reshown.
10064         }
10065         if (testAttribute(Qt::WA_WState_Created)) {
10066             // don't call setModal_sys() before create_sys()
10067             d->setModal_sys();
10068         }
10069         break;
10070     case Qt::WA_MouseTracking: {
10071         QEvent e(QEvent::MouseTrackingChange);
10072         QApplication::sendEvent(this, &e);
10073         break; }
10074     case Qt::WA_NativeWindow: {
10075         d->createTLExtra();
10076 #ifndef QT_NO_IM
10077         QWidget *focusWidget = d->effectiveFocusWidget();
10078         if (on && !internalWinId() && hasFocus()
10079             && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10080             qApp->inputMethod()->commit();
10081             qApp->inputMethod()->update(Qt::ImEnabled);
10082         }
10083         if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10084 #ifdef Q_WS_MAC
10085             // On Mac, toolbars inside the unified title bar will never overlap with
10086             // siblings in the content view. So we skip enforce native siblings in that case
10087             && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10088 #endif // Q_WS_MAC
10089         )
10090             parentWidget()->d_func()->enforceNativeChildren();
10091         if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10092             d->createWinId();
10093         if (isEnabled() && focusWidget->isEnabled()
10094             && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10095             qApp->inputMethod()->update(Qt::ImEnabled);
10096         }
10097 #endif //QT_NO_IM
10098         break;
10099     }
10100     case Qt::WA_PaintOnScreen:
10101         d->updateIsOpaque();
10102 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
10103         // Recreate the widget if it's already created as an alien widget and
10104         // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10105         // So must their children.
10106         if (on) {
10107             setAttribute(Qt::WA_NativeWindow);
10108             d->enforceNativeChildren();
10109         }
10110 #endif
10111         // fall through
10112     case Qt::WA_OpaquePaintEvent:
10113         d->updateIsOpaque();
10114         break;
10115     case Qt::WA_NoSystemBackground:
10116         d->updateIsOpaque();
10117         // fall through...
10118     case Qt::WA_UpdatesDisabled:
10119         d->updateSystemBackground();
10120         break;
10121     case Qt::WA_TransparentForMouseEvents:
10122 #ifdef Q_WS_MAC
10123         d->macUpdateIgnoreMouseEvents();
10124 #endif
10125         break;
10126     case Qt::WA_InputMethodEnabled: {
10127 #ifndef QT_NO_IM
10128         if (qApp->focusObject() == this) {
10129             if (!on)
10130                 qApp->inputMethod()->commit();
10131             qApp->inputMethod()->update(Qt::ImEnabled);
10132         }
10133 #endif //QT_NO_IM
10134         break;
10135     }
10136     case Qt::WA_WindowPropagation:
10137         d->resolvePalette();
10138         d->resolveFont();
10139         d->resolveLocale();
10140         break;
10141 #ifdef Q_WS_X11
10142     case Qt::WA_NoX11EventCompression:
10143         if (!d->extra)
10144             d->createExtra();
10145         d->extra->compress_events = on;
10146         break;
10147     case Qt::WA_X11OpenGLOverlay:
10148         d->updateIsOpaque();
10149         break;
10150     case Qt::WA_X11DoNotAcceptFocus:
10151         if (testAttribute(Qt::WA_WState_Created))
10152             d->updateX11AcceptFocus();
10153         break;
10154 #endif
10155     case Qt::WA_DontShowOnScreen: {
10156         if (on && isVisible()) {
10157             // Make sure we keep the current state and only hide the widget
10158             // from the desktop. show_sys will only update platform specific
10159             // attributes at this point.
10160             d->hide_sys();
10161             d->show_sys();
10162         }
10163         break;
10164     }
10165
10166 #ifdef Q_WS_X11
10167     case Qt::WA_X11NetWmWindowTypeDesktop:
10168     case Qt::WA_X11NetWmWindowTypeDock:
10169     case Qt::WA_X11NetWmWindowTypeToolBar:
10170     case Qt::WA_X11NetWmWindowTypeMenu:
10171     case Qt::WA_X11NetWmWindowTypeUtility:
10172     case Qt::WA_X11NetWmWindowTypeSplash:
10173     case Qt::WA_X11NetWmWindowTypeDialog:
10174     case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10175     case Qt::WA_X11NetWmWindowTypePopupMenu:
10176     case Qt::WA_X11NetWmWindowTypeToolTip:
10177     case Qt::WA_X11NetWmWindowTypeNotification:
10178     case Qt::WA_X11NetWmWindowTypeCombo:
10179     case Qt::WA_X11NetWmWindowTypeDND:
10180         if (testAttribute(Qt::WA_WState_Created))
10181             d->setNetWmWindowTypes();
10182         break;
10183 #endif
10184
10185     case Qt::WA_StaticContents:
10186         if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10187             if (on)
10188                 bs->addStaticWidget(this);
10189             else
10190                 bs->removeStaticWidget(this);
10191         }
10192         break;
10193     case Qt::WA_TranslucentBackground:
10194         if (on) {
10195             setAttribute(Qt::WA_NoSystemBackground);
10196             d->updateIsTranslucent();
10197         }
10198
10199         break;
10200     case Qt::WA_AcceptTouchEvents:
10201 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10202         if (on)
10203             d->registerTouchWindow();
10204 #endif
10205         break;
10206     default:
10207         break;
10208     }
10209 }
10210
10211 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10212
10213   Returns true if attribute \a attribute is set on this widget;
10214   otherwise returns false.
10215
10216   \sa setAttribute()
10217  */
10218 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10219 {
10220     Q_D(const QWidget);
10221     const int x = attribute - 8*sizeof(uint);
10222     const int int_off = x / (8*sizeof(uint));
10223     return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10224 }
10225
10226 /*!
10227   \property QWidget::windowOpacity
10228
10229   \brief The level of opacity for the window.
10230
10231   The valid range of opacity is from 1.0 (completely opaque) to
10232   0.0 (completely transparent).
10233
10234   By default the value of this property is 1.0.
10235
10236   This feature is available on Embedded Linux, Mac OS X, Windows,
10237   and X11 platforms that support the Composite extension.
10238
10239   This feature is not available on Windows CE.
10240
10241   Note that under X11 you need to have a composite manager running,
10242   and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10243   supported by the window manager you are using.
10244
10245   \warning Changing this property from opaque to transparent might issue a
10246   paint event that needs to be processed before the window is displayed
10247   correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10248   that semi-transparent windows update and resize significantly slower than
10249   opaque windows.
10250
10251   \sa setMask()
10252 */
10253 qreal QWidget::windowOpacity() const
10254 {
10255     Q_D(const QWidget);
10256     return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10257 }
10258
10259 void QWidget::setWindowOpacity(qreal opacity)
10260 {
10261     Q_D(QWidget);
10262     if (!isWindow())
10263         return;
10264
10265     opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10266     QTLWExtra *extra = d->topData();
10267     extra->opacity = uint(opacity * 255);
10268     setAttribute(Qt::WA_WState_WindowOpacitySet);
10269
10270     if (!testAttribute(Qt::WA_WState_Created))
10271         return;
10272
10273 #ifndef QT_NO_GRAPHICSVIEW
10274     if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10275         // Avoid invalidating the cache if set.
10276         if (proxy->cacheMode() == QGraphicsItem::NoCache)
10277             proxy->update();
10278         else if (QGraphicsScene *scene = proxy->scene())
10279             scene->update(proxy->sceneBoundingRect());
10280         return;
10281     }
10282 #endif
10283
10284     d->setWindowOpacity_sys(opacity);
10285 }
10286
10287 /*!
10288     \property QWidget::windowModified
10289     \brief whether the document shown in the window has unsaved changes
10290
10291     A modified window is a window whose content has changed but has
10292     not been saved to disk. This flag will have different effects
10293     varied by the platform. On Mac OS X the close button will have a
10294     modified look; on other platforms, the window title will have an
10295     '*' (asterisk).
10296
10297     The window title must contain a "[*]" placeholder, which
10298     indicates where the '*' should appear. Normally, it should appear
10299     right after the file name (e.g., "document1.txt[*] - Text
10300     Editor"). If the window isn't modified, the placeholder is simply
10301     removed.
10302
10303     Note that if a widget is set as modified, all its ancestors will
10304     also be set as modified. However, if you call \c
10305     {setWindowModified(false)} on a widget, this will not propagate to
10306     its parent because other children of the parent might have been
10307     modified.
10308
10309     \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10310 */
10311 bool QWidget::isWindowModified() const
10312 {
10313     return testAttribute(Qt::WA_WindowModified);
10314 }
10315
10316 void QWidget::setWindowModified(bool mod)
10317 {
10318     Q_D(QWidget);
10319     setAttribute(Qt::WA_WindowModified, mod);
10320
10321     d->setWindowModified_helper();
10322
10323     QEvent e(QEvent::ModifiedChange);
10324     QApplication::sendEvent(this, &e);
10325 }
10326
10327 void QWidgetPrivate::setWindowModified_helper()
10328 {
10329     Q_Q(QWidget);
10330     QWindow *window = q->windowHandle();
10331     if (!window)
10332         return;
10333     QPlatformWindow *platformWindow = window->handle();
10334     if (!platformWindow)
10335         return;
10336     bool on = q->testAttribute(Qt::WA_WindowModified);
10337     if (!platformWindow->setWindowModified(on)) {
10338         if (!q->windowTitle().contains(QLatin1String("[*]")) && on)
10339             qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10340         setWindowTitle_helper(q->windowTitle());
10341         setWindowIconText_helper(q->windowIconText());
10342     }
10343 }
10344
10345 #ifndef QT_NO_TOOLTIP
10346 /*!
10347   \property QWidget::toolTip
10348
10349   \brief the widget's tooltip
10350
10351   Note that by default tooltips are only shown for widgets that are
10352   children of the active window. You can change this behavior by
10353   setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10354   not on the widget with the tooltip.
10355
10356   If you want to control a tooltip's behavior, you can intercept the
10357   event() function and catch the QEvent::ToolTip event (e.g., if you
10358   want to customize the area for which the tooltip should be shown).
10359
10360   By default, this property contains an empty string.
10361
10362   \sa QToolTip, statusTip, whatsThis
10363 */
10364 void QWidget::setToolTip(const QString &s)
10365 {
10366     Q_D(QWidget);
10367     d->toolTip = s;
10368
10369     QEvent event(QEvent::ToolTipChange);
10370     QApplication::sendEvent(this, &event);
10371 }
10372
10373 QString QWidget::toolTip() const
10374 {
10375     Q_D(const QWidget);
10376     return d->toolTip;
10377 }
10378 #endif // QT_NO_TOOLTIP
10379
10380
10381 #ifndef QT_NO_STATUSTIP
10382 /*!
10383   \property QWidget::statusTip
10384   \brief the widget's status tip
10385
10386   By default, this property contains an empty string.
10387
10388   \sa toolTip, whatsThis
10389 */
10390 void QWidget::setStatusTip(const QString &s)
10391 {
10392     Q_D(QWidget);
10393     d->statusTip = s;
10394 }
10395
10396 QString QWidget::statusTip() const
10397 {
10398     Q_D(const QWidget);
10399     return d->statusTip;
10400 }
10401 #endif // QT_NO_STATUSTIP
10402
10403 #ifndef QT_NO_WHATSTHIS
10404 /*!
10405   \property QWidget::whatsThis
10406
10407   \brief the widget's What's This help text.
10408
10409   By default, this property contains an empty string.
10410
10411   \sa QWhatsThis, QWidget::toolTip, QWidget::statusTip
10412 */
10413 void QWidget::setWhatsThis(const QString &s)
10414 {
10415     Q_D(QWidget);
10416     d->whatsThis = s;
10417 }
10418
10419 QString QWidget::whatsThis() const
10420 {
10421     Q_D(const QWidget);
10422     return d->whatsThis;
10423 }
10424 #endif // QT_NO_WHATSTHIS
10425
10426 #ifndef QT_NO_ACCESSIBILITY
10427 /*!
10428   \property QWidget::accessibleName
10429
10430   \brief the widget's name as seen by assistive technologies
10431
10432   This property is used by accessible clients to identify, find, or announce
10433   the widget for accessible clients.
10434
10435   By default, this property contains an empty string.
10436
10437   \sa QAccessibleInterface::text()
10438 */
10439 void QWidget::setAccessibleName(const QString &name)
10440 {
10441     Q_D(QWidget);
10442     d->accessibleName = name;
10443     QAccessibleEvent event(this, QAccessible::NameChanged);
10444     QAccessible::updateAccessibility(&event);
10445 }
10446
10447 QString QWidget::accessibleName() const
10448 {
10449     Q_D(const QWidget);
10450     return d->accessibleName;
10451 }
10452
10453 /*!
10454   \property QWidget::accessibleDescription
10455
10456   \brief the widget's description as seen by assistive technologies
10457
10458   By default, this property contains an empty string.
10459
10460   \sa QAccessibleInterface::text()
10461 */
10462 void QWidget::setAccessibleDescription(const QString &description)
10463 {
10464     Q_D(QWidget);
10465     d->accessibleDescription = description;
10466     QAccessibleEvent event(this, QAccessible::DescriptionChanged);
10467     QAccessible::updateAccessibility(&event);
10468 }
10469
10470 QString QWidget::accessibleDescription() const
10471 {
10472     Q_D(const QWidget);
10473     return d->accessibleDescription;
10474 }
10475 #endif // QT_NO_ACCESSIBILITY
10476
10477 #ifndef QT_NO_SHORTCUT
10478 /*!
10479     Adds a shortcut to Qt's shortcut system that watches for the given
10480     \a key sequence in the given \a context. If the \a context is
10481     Qt::ApplicationShortcut, the shortcut applies to the application as a
10482     whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10483     or to the window itself, Qt::WindowShortcut.
10484
10485     If the same \a key sequence has been grabbed by several widgets,
10486     when the \a key sequence occurs a QEvent::Shortcut event is sent
10487     to all the widgets to which it applies in a non-deterministic
10488     order, but with the ``ambiguous'' flag set to true.
10489
10490     \warning You should not normally need to use this function;
10491     instead create \l{QAction}s with the shortcut key sequences you
10492     require (if you also want equivalent menu options and toolbar
10493     buttons), or create \l{QShortcut}s if you just need key sequences.
10494     Both QAction and QShortcut handle all the event filtering for you,
10495     and provide signals which are triggered when the user triggers the
10496     key sequence, so are much easier to use than this low-level
10497     function.
10498
10499     \sa releaseShortcut(), setShortcutEnabled()
10500 */
10501 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10502 {
10503     Q_ASSERT(qApp);
10504     if (key.isEmpty())
10505         return 0;
10506     setAttribute(Qt::WA_GrabbedShortcut);
10507     return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10508 }
10509
10510 /*!
10511     Removes the shortcut with the given \a id from Qt's shortcut
10512     system. The widget will no longer receive QEvent::Shortcut events
10513     for the shortcut's key sequence (unless it has other shortcuts
10514     with the same key sequence).
10515
10516     \warning You should not normally need to use this function since
10517     Qt's shortcut system removes shortcuts automatically when their
10518     parent widget is destroyed. It is best to use QAction or
10519     QShortcut to handle shortcuts, since they are easier to use than
10520     this low-level function. Note also that this is an expensive
10521     operation.
10522
10523     \sa grabShortcut(), setShortcutEnabled()
10524 */
10525 void QWidget::releaseShortcut(int id)
10526 {
10527     Q_ASSERT(qApp);
10528     if (id)
10529         qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10530 }
10531
10532 /*!
10533     If \a enable is true, the shortcut with the given \a id is
10534     enabled; otherwise the shortcut is disabled.
10535
10536     \warning You should not normally need to use this function since
10537     Qt's shortcut system enables/disables shortcuts automatically as
10538     widgets become hidden/visible and gain or lose focus. It is best
10539     to use QAction or QShortcut to handle shortcuts, since they are
10540     easier to use than this low-level function.
10541
10542     \sa grabShortcut(), releaseShortcut()
10543 */
10544 void QWidget::setShortcutEnabled(int id, bool enable)
10545 {
10546     Q_ASSERT(qApp);
10547     if (id)
10548         qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10549 }
10550
10551 /*!
10552     \since 4.2
10553
10554     If \a enable is true, auto repeat of the shortcut with the
10555     given \a id is enabled; otherwise it is disabled.
10556
10557     \sa grabShortcut(), releaseShortcut()
10558 */
10559 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10560 {
10561     Q_ASSERT(qApp);
10562     if (id)
10563         qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10564 }
10565 #endif // QT_NO_SHORTCUT
10566
10567 /*!
10568     Updates the widget's micro focus.
10569 */
10570 void QWidget::updateMicroFocus()
10571 {
10572     // updating everything since this is currently called for any kind of state change
10573     qApp->inputMethod()->update(Qt::ImQueryAll);
10574 }
10575
10576 /*!
10577     Raises this widget to the top of the parent widget's stack.
10578
10579     After this call the widget will be visually in front of any
10580     overlapping sibling widgets.
10581
10582     \note When using activateWindow(), you can call this function to
10583     ensure that the window is stacked on top.
10584
10585     \sa lower(), stackUnder()
10586 */
10587
10588 void QWidget::raise()
10589 {
10590     Q_D(QWidget);
10591     if (!isWindow()) {
10592         QWidget *p = parentWidget();
10593         const int parentChildCount = p->d_func()->children.size();
10594         if (parentChildCount < 2)
10595             return;
10596         const int from = p->d_func()->children.indexOf(this);
10597         Q_ASSERT(from >= 0);
10598         // Do nothing if the widget is already in correct stacking order _and_ created.
10599         if (from != parentChildCount -1)
10600             p->d_func()->children.move(from, parentChildCount - 1);
10601         if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10602             create();
10603         else if (from == parentChildCount - 1)
10604             return;
10605
10606         QRegion region(rect());
10607         d->subtractOpaqueSiblings(region);
10608         d->invalidateBuffer(region);
10609     }
10610     if (testAttribute(Qt::WA_WState_Created))
10611         d->raise_sys();
10612
10613     QEvent e(QEvent::ZOrderChange);
10614     QApplication::sendEvent(this, &e);
10615 }
10616
10617 /*!
10618     Lowers the widget to the bottom of the parent widget's stack.
10619
10620     After this call the widget will be visually behind (and therefore
10621     obscured by) any overlapping sibling widgets.
10622
10623     \sa raise(), stackUnder()
10624 */
10625
10626 void QWidget::lower()
10627 {
10628     Q_D(QWidget);
10629     if (!isWindow()) {
10630         QWidget *p = parentWidget();
10631         const int parentChildCount = p->d_func()->children.size();
10632         if (parentChildCount < 2)
10633             return;
10634         const int from = p->d_func()->children.indexOf(this);
10635         Q_ASSERT(from >= 0);
10636         // Do nothing if the widget is already in correct stacking order _and_ created.
10637         if (from != 0)
10638             p->d_func()->children.move(from, 0);
10639         if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10640             create();
10641         else if (from == 0)
10642             return;
10643     }
10644     if (testAttribute(Qt::WA_WState_Created))
10645         d->lower_sys();
10646
10647     QEvent e(QEvent::ZOrderChange);
10648     QApplication::sendEvent(this, &e);
10649 }
10650
10651
10652 /*!
10653     Places the widget under \a w in the parent widget's stack.
10654
10655     To make this work, the widget itself and \a w must be siblings.
10656
10657     \sa raise(), lower()
10658 */
10659 void QWidget::stackUnder(QWidget* w)
10660 {
10661     Q_D(QWidget);
10662     QWidget *p = parentWidget();
10663     if (!w || isWindow() || p != w->parentWidget() || this == w)
10664         return;
10665     if (p) {
10666         int from = p->d_func()->children.indexOf(this);
10667         int to = p->d_func()->children.indexOf(w);
10668         Q_ASSERT(from >= 0);
10669         Q_ASSERT(to >= 0);
10670         if (from < to)
10671             --to;
10672         // Do nothing if the widget is already in correct stacking order _and_ created.
10673         if (from != to)
10674             p->d_func()->children.move(from, to);
10675         if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10676             create();
10677         else if (from == to)
10678             return;
10679     }
10680     if (testAttribute(Qt::WA_WState_Created))
10681         d->stackUnder_sys(w);
10682
10683     QEvent e(QEvent::ZOrderChange);
10684     QApplication::sendEvent(this, &e);
10685 }
10686
10687
10688 /*!
10689     \fn bool QWidget::isTopLevel() const
10690     \obsolete
10691
10692     Use isWindow() instead.
10693 */
10694
10695 /*!
10696     \fn bool QWidget::isRightToLeft() const
10697     \internal
10698 */
10699
10700 /*!
10701     \fn bool QWidget::isLeftToRight() const
10702     \internal
10703 */
10704
10705 /*!
10706      \macro QWIDGETSIZE_MAX
10707      \relates QWidget
10708
10709      Defines the maximum size for a QWidget object.
10710
10711      The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
10712      QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
10713
10714      \sa QWidget::setMaximumSize()
10715 */
10716
10717 /*!
10718     \fn QWidget::setupUi(QWidget *widget)
10719
10720     Sets up the user interface for the specified \a widget.
10721
10722     \note This function is available with widgets that derive from user
10723     interface descriptions created using \l{uic}.
10724
10725     \sa {Using a Designer UI File in Your Application}
10726 */
10727
10728 QRect QWidgetPrivate::frameStrut() const
10729 {
10730     Q_Q(const QWidget);
10731     if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
10732         // x2 = x1 + w - 1, so w/h = 1
10733         return QRect(0, 0, 1, 1);
10734     }
10735
10736     if (data.fstrut_dirty
10737 #ifndef Q_WS_WIN
10738         // ### Fix properly for 4.3
10739         && q->isVisible()
10740 #endif
10741         && q->testAttribute(Qt::WA_WState_Created))
10742         const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
10743
10744     return maybeTopData() ? maybeTopData()->frameStrut : QRect();
10745 }
10746
10747 #ifdef QT_KEYPAD_NAVIGATION
10748 /*!
10749     \internal
10750
10751     Changes the focus  from the current focusWidget to a widget in
10752     the \a direction.
10753
10754     Returns true, if there was a widget in that direction
10755 */
10756 bool QWidgetPrivate::navigateToDirection(Direction direction)
10757 {
10758     QWidget *targetWidget = widgetInNavigationDirection(direction);
10759     if (targetWidget)
10760         targetWidget->setFocus();
10761     return (targetWidget != 0);
10762 }
10763
10764 /*!
10765     \internal
10766
10767     Searches for a widget that is positioned in the \a direction, starting
10768     from the current focusWidget.
10769
10770     Returns the pointer to a found widget or 0, if there was no widget in
10771     that direction.
10772 */
10773 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
10774 {
10775     const QWidget *sourceWidget = QApplication::focusWidget();
10776     if (!sourceWidget)
10777         return 0;
10778     const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
10779     const int sourceX =
10780             (direction == DirectionNorth || direction == DirectionSouth) ?
10781                 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
10782                 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
10783     const int sourceY =
10784             (direction == DirectionEast || direction == DirectionWest) ?
10785                 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
10786                 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
10787     const QPoint sourcePoint(sourceX, sourceY);
10788     const QPoint sourceCenter = sourceRect.center();
10789     const QWidget *sourceWindow = sourceWidget->window();
10790
10791     QWidget *targetWidget = 0;
10792     int shortestDistance = INT_MAX;
10793     foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
10794
10795         const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
10796
10797         // For focus proxies, the child widget handling the focus can have keypad navigation focus,
10798         // but the owner of the proxy cannot.
10799         // Additionally, empty widgets should be ignored.
10800         if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
10801             continue;
10802
10803         // Only navigate to a target widget that...
10804         if (       targetCandidate != sourceWidget
10805                    // ...takes the focus,
10806                 && targetCandidate->focusPolicy() & Qt::TabFocus
10807                    // ...is above if DirectionNorth,
10808                 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
10809                    // ...is on the right if DirectionEast,
10810                 && !(direction == DirectionEast  && targetCandidateRect.left()   < sourceRect.right())
10811                    // ...is below if DirectionSouth,
10812                 && !(direction == DirectionSouth && targetCandidateRect.top()    < sourceRect.bottom())
10813                    // ...is on the left if DirectionWest,
10814                 && !(direction == DirectionWest  && targetCandidateRect.right()  > sourceRect.left())
10815                    // ...is enabled,
10816                 && targetCandidate->isEnabled()
10817                    // ...is visible,
10818                 && targetCandidate->isVisible()
10819                    // ...is in the same window,
10820                 && targetCandidate->window() == sourceWindow) {
10821             const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
10822             if (targetCandidateDistance < shortestDistance) {
10823                 shortestDistance = targetCandidateDistance;
10824                 targetWidget = targetCandidate;
10825             }
10826         }
10827     }
10828     return targetWidget;
10829 }
10830
10831 /*!
10832     \internal
10833
10834     Tells us if it there is currently a reachable widget by keypad navigation in
10835     a certain \a orientation.
10836     If no navigation is possible, occurring key events in that \a orientation may
10837     be used to interact with the value in the focused widget, even though it
10838     currently has not the editFocus.
10839
10840     \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
10841 */
10842 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
10843 {
10844     return orientation == Qt::Horizontal?
10845             (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
10846                     || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
10847             :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
10848                     || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
10849 }
10850 /*!
10851     \internal
10852
10853     Checks, if the \a widget is inside a QTabWidget. If is is inside
10854     one, left/right key events will be used to switch between tabs in keypad
10855     navigation. If there is no QTabWidget, the horizontal key events can be used
10856 to
10857     interact with the value in the focused widget, even though it currently has
10858     not the editFocus.
10859
10860     \sa QWidget::hasEditFocus()
10861 */
10862 bool QWidgetPrivate::inTabWidget(QWidget *widget)
10863 {
10864     for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
10865         if (qobject_cast<const QTabWidget*>(tabWidget))
10866             return true;
10867     return false;
10868 }
10869 #endif
10870
10871 /*!
10872     \since 5.0
10873     \internal
10874
10875     Sets the backing store to be the \a store specified.
10876     The QWidget will take ownership of the \a store.
10877 */
10878 void QWidget::setBackingStore(QBackingStore *store)
10879 {
10880     // ### createWinId() ??
10881
10882     if (!isTopLevel())
10883         return;
10884
10885     Q_D(QWidget);
10886
10887     QTLWExtra *topData = d->topData();
10888     if (topData->backingStore == store)
10889         return;
10890
10891     QBackingStore *oldStore = topData->backingStore;
10892     delete topData->backingStore;
10893     topData->backingStore = store;
10894
10895     QWidgetBackingStore *bs = d->maybeBackingStore();
10896     if (!bs)
10897         return;
10898
10899     if (isTopLevel()) {
10900         if (bs->store != oldStore && bs->store != store)
10901             delete bs->store;
10902         bs->store = store;
10903     }
10904 }
10905
10906 /*!
10907     \since 5.0
10908
10909     Returns the QBackingStore this widget will be drawn into.
10910 */
10911 QBackingStore *QWidget::backingStore() const
10912 {
10913     Q_D(const QWidget);
10914     QTLWExtra *extra = d->maybeTopData();
10915     if (extra && extra->backingStore)
10916         return extra->backingStore;
10917
10918     QWidgetBackingStore *bs = d->maybeBackingStore();
10919
10920     return bs ? bs->store : 0;
10921 }
10922
10923 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
10924 {
10925     if (left)
10926         *left = (int)leftLayoutItemMargin;
10927     if (top)
10928         *top = (int)topLayoutItemMargin;
10929     if (right)
10930         *right = (int)rightLayoutItemMargin;
10931     if (bottom)
10932         *bottom = (int)bottomLayoutItemMargin;
10933 }
10934
10935 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
10936 {
10937     if (leftLayoutItemMargin == left
10938         && topLayoutItemMargin == top
10939         && rightLayoutItemMargin == right
10940         && bottomLayoutItemMargin == bottom)
10941         return;
10942
10943     Q_Q(QWidget);
10944     leftLayoutItemMargin = (signed char)left;
10945     topLayoutItemMargin = (signed char)top;
10946     rightLayoutItemMargin = (signed char)right;
10947     bottomLayoutItemMargin = (signed char)bottom;
10948     q->updateGeometry();
10949 }
10950
10951 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
10952 {
10953     Q_Q(QWidget);
10954     QStyleOption myOpt;
10955     if (!opt) {
10956         myOpt.initFrom(q);
10957         myOpt.rect.setRect(0, 0, 32768, 32768);     // arbitrary
10958         opt = &myOpt;
10959     }
10960
10961     QRect liRect = q->style()->subElementRect(element, opt, q);
10962     if (liRect.isValid()) {
10963         leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
10964         topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
10965         rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
10966         bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
10967     } else {
10968         leftLayoutItemMargin = 0;
10969         topLayoutItemMargin = 0;
10970         rightLayoutItemMargin = 0;
10971         bottomLayoutItemMargin = 0;
10972     }
10973 }
10974 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
10975 void QWidgetPrivate::adjustQuitOnCloseAttribute()
10976 {
10977     Q_Q(QWidget);
10978
10979     if (!q->parentWidget()) {
10980         Qt::WindowType type = q->windowType();
10981         if (type == Qt::Widget || type == Qt::SubWindow)
10982             type = Qt::Window;
10983         if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
10984             q->setAttribute(Qt::WA_QuitOnClose, false);
10985     }
10986 }
10987
10988
10989
10990 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
10991 {
10992     return widget->data;
10993 }
10994
10995 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
10996 {
10997     return widget->d_func();
10998 }
10999
11000
11001 #ifndef QT_NO_GRAPHICSVIEW
11002 /*!
11003    \since 4.5
11004
11005    Returns the proxy widget for the corresponding embedded widget in a graphics
11006    view; otherwise returns 0.
11007
11008    \sa QGraphicsProxyWidget::createProxyForChildWidget(),
11009        QGraphicsScene::addWidget()
11010  */
11011 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
11012 {
11013     Q_D(const QWidget);
11014     if (d->extra) {
11015         return d->extra->proxyWidget;
11016     }
11017     return 0;
11018 }
11019 #endif
11020
11021 #ifndef QT_NO_GESTURES
11022 /*!
11023     Subscribes the widget to a given \a gesture with specific \a flags.
11024
11025     \sa ungrabGesture(), QGestureEvent
11026     \since 4.6
11027 */
11028 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11029 {
11030     Q_D(QWidget);
11031     d->gestureContext.insert(gesture, flags);
11032     (void)QGestureManager::instance(); // create a gesture manager
11033 }
11034
11035 /*!
11036     Unsubscribes the widget from a given \a gesture type
11037
11038     \sa grabGesture(), QGestureEvent
11039     \since 4.6
11040 */
11041 void QWidget::ungrabGesture(Qt::GestureType gesture)
11042 {
11043     Q_D(QWidget);
11044     if (d->gestureContext.remove(gesture)) {
11045         if (QGestureManager *manager = QGestureManager::instance())
11046             manager->cleanupCachedGestures(this, gesture);
11047     }
11048 }
11049 #endif // QT_NO_GESTURES
11050
11051 /*!
11052     \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11053
11054     Frees up window system resources. Destroys the widget window if \a
11055     destroyWindow is true.
11056
11057     destroy() calls itself recursively for all the child widgets,
11058     passing \a destroySubWindows for the \a destroyWindow parameter.
11059     To have more control over destruction of subwidgets, destroy
11060     subwidgets selectively first.
11061
11062     This function is usually called from the QWidget destructor.
11063 */
11064
11065 /*!
11066     \fn QPaintEngine *QWidget::paintEngine() const
11067
11068     Returns the widget's paint engine.
11069
11070     Note that this function should not be called explicitly by the
11071     user, since it's meant for reimplementation purposes only. The
11072     function is called by Qt internally, and the default
11073     implementation may not always return a valid pointer.
11074 */
11075
11076 /*!
11077     \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11078
11079     Translates the widget coordinate \a pos to global screen
11080     coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11081     the global coordinates of the top-left pixel of the widget.
11082
11083     \sa mapFromGlobal(), mapTo(), mapToParent()
11084 */
11085
11086 /*!
11087     \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11088
11089     Translates the global screen coordinate \a pos to widget
11090     coordinates.
11091
11092     \sa mapToGlobal(), mapFrom(), mapFromParent()
11093 */
11094
11095 /*!
11096     \fn void QWidget::grabMouse()
11097
11098     Grabs the mouse input.
11099
11100     This widget receives all mouse events until releaseMouse() is
11101     called; other widgets get no mouse events at all. Keyboard
11102     events are not affected. Use grabKeyboard() if you want to grab
11103     that.
11104
11105     \warning Bugs in mouse-grabbing applications very often lock the
11106     terminal. Use this function with extreme caution, and consider
11107     using the \c -nograb command line option while debugging.
11108
11109     It is almost never necessary to grab the mouse when using Qt, as
11110     Qt grabs and releases it sensibly. In particular, Qt grabs the
11111     mouse when a mouse button is pressed and keeps it until the last
11112     button is released.
11113
11114     \note Only visible widgets can grab mouse input. If isVisible()
11115     returns false for a widget, that widget cannot call grabMouse().
11116
11117     \note \b{(Mac OS X developers)} For \e Cocoa, calling
11118     grabMouse() on a widget only works when the mouse is inside the
11119     frame of that widget.  For \e Carbon, it works outside the widget's
11120     frame as well, like for Windows and X11.
11121
11122     \sa releaseMouse(), grabKeyboard(), releaseKeyboard()
11123 */
11124
11125 /*!
11126     \fn void QWidget::grabMouse(const QCursor &cursor)
11127     \overload grabMouse()
11128
11129     Grabs the mouse input and changes the cursor shape.
11130
11131     The cursor will assume shape \a cursor (for as long as the mouse
11132     focus is grabbed) and this widget will be the only one to receive
11133     mouse events until releaseMouse() is called().
11134
11135     \warning Grabbing the mouse might lock the terminal.
11136
11137     \note \b{(Mac OS X developers)} See the note in QWidget::grabMouse().
11138
11139     \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11140 */
11141
11142 /*!
11143     \fn void QWidget::releaseMouse()
11144
11145     Releases the mouse grab.
11146
11147     \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11148 */
11149
11150 /*!
11151     \fn void QWidget::grabKeyboard()
11152
11153     Grabs the keyboard input.
11154
11155     This widget receives all keyboard events until releaseKeyboard()
11156     is called; other widgets get no keyboard events at all. Mouse
11157     events are not affected. Use grabMouse() if you want to grab that.
11158
11159     The focus widget is not affected, except that it doesn't receive
11160     any keyboard events. setFocus() moves the focus as usual, but the
11161     new focus widget receives keyboard events only after
11162     releaseKeyboard() is called.
11163
11164     If a different widget is currently grabbing keyboard input, that
11165     widget's grab is released first.
11166
11167     \sa releaseKeyboard(), grabMouse(), releaseMouse(), focusWidget()
11168 */
11169
11170 /*!
11171     \fn void QWidget::releaseKeyboard()
11172
11173     Releases the keyboard grab.
11174
11175     \sa grabKeyboard(), grabMouse(), releaseMouse()
11176 */
11177
11178 /*!
11179     \fn QWidget *QWidget::mouseGrabber()
11180
11181     Returns the widget that is currently grabbing the mouse input.
11182
11183     If no widget in this application is currently grabbing the mouse,
11184     0 is returned.
11185
11186     \sa grabMouse(), keyboardGrabber()
11187 */
11188
11189 /*!
11190     \fn QWidget *QWidget::keyboardGrabber()
11191
11192     Returns the widget that is currently grabbing the keyboard input.
11193
11194     If no widget in this application is currently grabbing the
11195     keyboard, 0 is returned.
11196
11197     \sa grabMouse(), mouseGrabber()
11198 */
11199
11200 /*!
11201     \fn void QWidget::activateWindow()
11202
11203     Sets the top-level widget containing this widget to be the active
11204     window.
11205
11206     An active window is a visible top-level window that has the
11207     keyboard input focus.
11208
11209     This function performs the same operation as clicking the mouse on
11210     the title bar of a top-level window. On X11, the result depends on
11211     the Window Manager. If you want to ensure that the window is
11212     stacked on top as well you should also call raise(). Note that the
11213     window must be visible, otherwise activateWindow() has no effect.
11214
11215     On Windows, if you are calling this when the application is not
11216     currently the active one then it will not make it the active
11217     window.  It will change the color of the taskbar entry to indicate
11218     that the window has changed in some way. This is because Microsoft
11219     does not allow an application to interrupt what the user is currently
11220     doing in another application.
11221
11222     \sa isActiveWindow(), window(), show()
11223 */
11224
11225 /*!
11226     \fn int QWidget::metric(PaintDeviceMetric m) const
11227
11228     Internal implementation of the virtual QPaintDevice::metric()
11229     function.
11230
11231     \a m is the metric to get.
11232 */
11233
11234 /*!
11235     Initializes the \a painter pen, background and font to the same as
11236     the given widget's. This function is called automatically when the
11237     painter is opened on a QWidget.
11238 */
11239 void QWidget::initPainter(QPainter *painter) const
11240 {
11241     const QPalette &pal = palette();
11242     painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 1);
11243     painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11244     QFont f(font(), const_cast<QWidget *>(this));
11245     painter->d_func()->state->deviceFont = f;
11246     painter->d_func()->state->font = f;
11247 }
11248
11249 QPaintDevice *QWidget::redirected(QPoint *offset) const
11250 {
11251     return d_func()->redirected(offset);
11252 }
11253
11254 QPainter *QWidget::sharedPainter() const
11255 {
11256     // Someone sent a paint event directly to the widget
11257     if (!d_func()->redirectDev)
11258         return 0;
11259
11260     QPainter *sp = d_func()->sharedPainter();
11261     if (!sp || !sp->isActive())
11262         return 0;
11263
11264     if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11265         return 0;
11266
11267     return sp;
11268 }
11269
11270 /*!
11271     \fn void QWidget::setMask(const QRegion &region)
11272     \overload
11273
11274     Causes only the parts of the widget which overlap \a region to be
11275     visible. If the region includes pixels outside the rect() of the
11276     widget, window system controls in that area may or may not be
11277     visible, depending on the platform.
11278
11279     Note that this effect can be slow if the region is particularly
11280     complex.
11281
11282     \sa windowOpacity
11283 */
11284 void QWidget::setMask(const QRegion &newMask)
11285 {
11286     Q_D(QWidget);
11287
11288     d->createExtra();
11289     if (newMask == d->extra->mask)
11290         return;
11291
11292 #ifndef QT_NO_BACKINGSTORE
11293     const QRegion oldMask(d->extra->mask);
11294 #endif
11295
11296     d->extra->mask = newMask;
11297     d->extra->hasMask = !newMask.isEmpty();
11298
11299 #ifndef Q_WS_MAC
11300     if (!testAttribute(Qt::WA_WState_Created))
11301         return;
11302 #endif
11303
11304     d->setMask_sys(newMask);
11305
11306 #ifndef QT_NO_BACKINGSTORE
11307     if (!isVisible())
11308         return;
11309
11310     if (!d->extra->hasMask) {
11311         // Mask was cleared; update newly exposed area.
11312         QRegion expose(rect());
11313         expose -= oldMask;
11314         if (!expose.isEmpty()) {
11315             d->setDirtyOpaqueRegion();
11316             update(expose);
11317         }
11318         return;
11319     }
11320
11321     if (!isWindow()) {
11322         // Update newly exposed area on the parent widget.
11323         QRegion parentExpose(rect());
11324         parentExpose -= newMask;
11325         if (!parentExpose.isEmpty()) {
11326             d->setDirtyOpaqueRegion();
11327             parentExpose.translate(data->crect.topLeft());
11328             parentWidget()->update(parentExpose);
11329         }
11330
11331         // Update newly exposed area on this widget
11332         if (!oldMask.isEmpty())
11333             update(newMask - oldMask);
11334     }
11335 #endif
11336 }
11337
11338 /*!
11339     \fn void QWidget::setMask(const QBitmap &bitmap)
11340
11341     Causes only the pixels of the widget for which \a bitmap has a
11342     corresponding 1 bit to be visible. If the region includes pixels
11343     outside the rect() of the widget, window system controls in that
11344     area may or may not be visible, depending on the platform.
11345
11346     Note that this effect can be slow if the region is particularly
11347     complex.
11348
11349     The following code shows how an image with an alpha channel can be
11350     used to generate a mask for a widget:
11351
11352     \snippet widget-mask/main.cpp 0
11353
11354     The label shown by this code is masked using the image it contains,
11355     giving the appearance that an irregularly-shaped image is being drawn
11356     directly onto the screen.
11357
11358     Masked widgets receive mouse events only on their visible
11359     portions.
11360
11361     \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11362 */
11363 void QWidget::setMask(const QBitmap &bitmap)
11364 {
11365     setMask(QRegion(bitmap));
11366 }
11367
11368 /*!
11369     \fn void QWidget::clearMask()
11370
11371     Removes any mask set by setMask().
11372
11373     \sa setMask()
11374 */
11375 void QWidget::clearMask()
11376 {
11377     setMask(QRegion());
11378 }
11379
11380 #ifdef Q_WS_MAC
11381 void QWidgetPrivate::syncUnifiedMode() {
11382     // The whole purpose of this method is to keep the unifiedToolbar in sync.
11383     // That means making sure we either exchange the drawing methods or we let
11384     // the toolbar know that it does not require to draw the baseline.
11385     Q_Q(QWidget);
11386     // This function makes sense only if this is a top level
11387     if(!q->isWindow())
11388         return;
11389     OSWindowRef window = qt_mac_window_for(q);
11390     if(changeMethods) {
11391         // Ok, we are in documentMode.
11392         if(originalDrawMethod)
11393             qt_mac_replaceDrawRect(window, this);
11394     } else {
11395         if(!originalDrawMethod)
11396             qt_mac_replaceDrawRectOriginal(window, this);
11397     }
11398 }
11399
11400 #endif // Q_WS_MAC
11401
11402 QT_END_NAMESPACE
11403
11404 #include "moc_qwidget.cpp"
11405