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