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