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