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