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