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