1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qapplication.h"
43 #include "qapplication_p.h"
46 #include "qdesktopwidget.h"
51 #include "qmetaobject.h"
56 #include "qstylefactory.h"
59 #include "qstyleoption.h"
60 #ifndef QT_NO_ACCESSIBILITY
61 # include "qaccessible.h"
64 # include "qt_mac_p.h"
65 # include "qt_cocoa_helpers_mac_p.h"
66 # include "qmainwindow.h"
67 # include "qtoolbar.h"
68 # include <private/qmainwindowlayout_p.h>
70 #include "qplatformwindow_qpa.h"
71 #include "private/qwidgetwindow_qpa_p.h"
74 #include "qwhatsthis.h"
76 #include "private/qstylesheetstyle_p.h"
77 #include "private/qstyle_p.h"
78 #include "qfileinfo.h"
79 #include "private/qsoftkeymanager_p.h"
80 #include <QtGui/qinputmethod.h>
82 #include <private/qgraphicseffect_p.h>
83 #include <qbackingstore.h>
84 #include <private/qwidgetbackingstore_p.h>
86 # include <private/qpaintengine_mac_p.h>
88 #include <private/qpaintengine_raster_p.h>
90 #include "qwidget_p.h"
91 #include <QtGui/private/qwindow_p.h>
92 #include "qaction_p.h"
93 #include "qlayout_p.h"
94 #include "QtWidgets/qgraphicsproxywidget.h"
95 #include "QtWidgets/qgraphicsscene.h"
96 #include "private/qgraphicsproxywidget_p.h"
97 #include "QtWidgets/qabstractscrollarea.h"
98 #include "private/qabstractscrollarea_p.h"
99 #include "private/qevent_p.h"
101 #include "private/qgesturemanager_p.h"
103 #ifdef QT_KEYPAD_NAVIGATION
104 #include "qtabwidget.h" // Needed in inTabWidget()
105 #endif // QT_KEYPAD_NAVIGATION
108 // widget/widget data creation count
109 //#define QWIDGET_EXTRA_DEBUG
110 //#define ALIEN_DEBUG
114 static bool qt_enable_backingstore = true;
116 // for compatibility with Qt 4.0
117 Q_WIDGETS_EXPORT void qt_x11_set_global_double_buffer(bool enable)
119 qt_enable_backingstore = enable;
124 bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
127 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
129 return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
130 qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
133 static inline bool hasBackingStoreSupport()
139 # define QT_NO_PAINT_DEBUG
142 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
143 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
147 \class QWidgetBackingStoreTracker
148 \brief Class which allows tracking of which widgets are using a given backing store
150 QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
151 which maintains a list of the QWidgets which are currently using the backing
152 store. This list is modified via the registerWidget and unregisterWidget functions.
155 QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
161 QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
168 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
169 widgets using the backing store, then create a new QWidgetBackingStore, providing
172 void QWidgetBackingStoreTracker::create(QWidget *widget)
175 m_ptr = new QWidgetBackingStore(widget);
180 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
181 widgets using the backing store.
183 void QWidgetBackingStoreTracker::destroy()
192 Add the widget to the list of widgets currently using the backing store.
193 If the widget was already in the list, this function is a no-op.
195 void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
198 Q_ASSERT(w->internalWinId());
199 Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
205 Remove the widget from the list of widgets currently using the backing store.
206 If the widget was in the list, and removing it causes the list to be empty,
207 the backing store is deleted.
208 If the widget was not in the list, this function is a no-op.
210 void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
212 if (m_widgets.remove(w) && m_widgets.isEmpty()) {
220 Recursively remove widget and all of its descendents.
222 void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
224 unregisterWidget(widget);
225 foreach (QObject *child, widget->children())
226 if (QWidget *childWidget = qobject_cast<QWidget *>(child))
227 unregisterWidgetSubtree(childWidget);
230 QWidgetPrivate::QWidgetPrivate(int version)
231 : QObjectPrivate(version)
240 , extraPaintEngine(0)
243 #if !defined(QT_NO_IM)
244 , imHints(Qt::ImhNone)
246 , inheritedFontResolveMask(0)
247 , inheritedPaletteResolveMask(0)
252 , leftLayoutItemMargin(0)
253 , topLayoutItemMargin(0)
254 , rightLayoutItemMargin(0)
255 , bottomLayoutItemMargin(0)
257 , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
258 , fg_role(QPalette::NoRole)
259 , bg_role(QPalette::NoRole)
260 , dirtyOpaqueChildren(1)
266 , usesDoubleBufferedGLContext(0)
268 , inheritsInputMethodHints(0)
271 #if defined(Q_WS_X11)
273 #elif defined(Q_WS_WIN)
275 #ifndef QT_NO_GESTURES
276 , nativeGesturePanEnabled(0)
278 #elif defined(Q_WS_MAC)
279 , needWindowChange(0)
285 qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
289 if (version != QObjectPrivateVersion)
290 qFatal("Cannot mix incompatible Qt libraries");
293 memset(high_attributes, 0, sizeof(high_attributes));
295 drawRectOriginalAdded = false;
296 originalDrawMethod = true;
297 changeMethods = false;
298 isInUnifiedToolbar = false;
300 toolbar_ancestor = 0;
301 flushRequested = false;
302 touchEventsEnabled = false;
304 #ifdef QWIDGET_EXTRA_DEBUG
305 static int count = 0;
306 qDebug() << "widgets" << ++count;
311 QWidgetPrivate::~QWidgetPrivate()
319 #ifndef QT_NO_GRAPHICSEFFECT
320 delete graphicsEffect;
321 #endif //QT_NO_GRAPHICSEFFECT
327 void QWidgetPrivate::scrollChildren(int dx, int dy)
330 if (q->children().size() > 0) { // scroll children
332 QObjectList childObjects = q->children();
333 for (int i = 0; i < childObjects.size(); ++i) { // move all children
334 QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
335 if (w && !w->isWindow()) {
336 QPoint oldp = w->pos();
337 QRect r(w->pos() + pd, w->size());
339 if (w->testAttribute(Qt::WA_WState_Created))
340 w->d_func()->setWSGeometry();
341 w->d_func()->setDirtyOpaqueRegion();
342 QMoveEvent e(r.topLeft(), oldp);
343 QApplication::sendEvent(w, &e);
349 void QWidgetPrivate::updateWidgetTransform()
352 if (q == qGuiApp->focusObject()) {
354 QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
355 t.translate(p.x(), p.y());
356 qApp->inputMethod()->setInputItemTransform(t);
360 #ifdef QT_KEYPAD_NAVIGATION
361 QPointer<QWidget> QWidgetPrivate::editingWidget;
364 Returns true if this widget currently has edit focus; otherwise false.
366 This feature is only available in Qt for Embedded Linux.
368 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
370 bool QWidget::hasEditFocus() const
372 const QWidget* w = this;
373 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
374 w = w->d_func()->extra->focus_proxy;
375 return QWidgetPrivate::editingWidget == w;
379 \fn void QWidget::setEditFocus(bool enable)
381 If \a enable is true, make this widget have edit focus, in which
382 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
383 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
386 This feature is only available in Qt for Embedded Linux.
388 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
390 void QWidget::setEditFocus(bool on)
393 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
394 f = f->d_func()->extra->focus_proxy;
396 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
397 QWidgetPrivate::editingWidget->setEditFocus(false);
399 if (on && !f->hasFocus())
402 if ((!on && !QWidgetPrivate::editingWidget)
403 || (on && QWidgetPrivate::editingWidget == f)) {
407 if (!on && QWidgetPrivate::editingWidget == f) {
408 QWidgetPrivate::editingWidget = 0;
409 QEvent event(QEvent::LeaveEditFocus);
410 QApplication::sendEvent(f, &event);
411 QApplication::sendEvent(f->style(), &event);
413 QWidgetPrivate::editingWidget = f;
414 QEvent event(QEvent::EnterEditFocus);
415 QApplication::sendEvent(f, &event);
416 QApplication::sendEvent(f->style(), &event);
422 \property QWidget::autoFillBackground
423 \brief whether the widget background is filled automatically
426 If enabled, this property will cause Qt to fill the background of the
427 widget before invoking the paint event. The color used is defined by the
428 QPalette::Window color role from the widget's \l{QPalette}{palette}.
430 In addition, Windows are always filled with QPalette::Window, unless the
431 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
433 This property cannot be turned off (i.e., set to false) if a widget's
434 parent has a static gradient for its background.
436 \warning Use this property with caution in conjunction with
437 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
438 background or a border-image, this property is automatically disabled.
440 By default, this property is false.
442 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
443 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
445 bool QWidget::autoFillBackground() const
448 return d->extra && d->extra->autoFillBackground;
451 void QWidget::setAutoFillBackground(bool enabled)
456 if (d->extra->autoFillBackground == enabled)
459 d->extra->autoFillBackground = enabled;
467 \brief The QWidget class is the base class of all user interface objects.
469 \ingroup basicwidgets
472 The widget is the atom of the user interface: it receives mouse, keyboard
473 and other events from the window system, and paints a representation of
474 itself on the screen. Every widget is rectangular, and they are sorted in a
475 Z-order. A widget is clipped by its parent and by the widgets in front of
478 A widget that is not embedded in a parent widget is called a window.
479 Usually, windows have a frame and a title bar, although it is also possible
480 to create windows without such decoration using suitable
481 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
482 subclasses of QDialog are the most common window types.
484 Every widget's constructor accepts one or two standard arguments:
487 \li \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
488 (the default), the new widget will be a window. If not, it will be
489 a child of \e parent, and be constrained by \e parent's geometry
490 (unless you specify Qt::Window as window flag).
491 \li \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
492 the default is suitable for almost all widgets, but to get, for
493 example, a window without a window system frame, you must use
497 QWidget has many member functions, but some of them have little direct
498 functionality; for example, QWidget has a font property, but never uses
499 this itself. There are many subclasses which provide real functionality,
500 such as QLabel, QPushButton, QListWidget, and QTabWidget.
503 \section1 Top-Level and Child Widgets
505 A widget without a parent widget is always an independent window (top-level
506 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
507 title bar and icon respectively.
509 Non-window widgets are child widgets, displayed within their parent
510 widgets. Most widgets in Qt are mainly useful as child widgets. For
511 example, it is possible to display a button as a top-level window, but most
512 people prefer to put their buttons inside other widgets, such as QDialog.
514 \image parent-child-widgets.png A parent widget containing various child widgets.
516 The diagram above shows a QGroupBox widget being used to hold various child
517 widgets in a layout provided by QGridLayout. The QLabel child widgets have
518 been outlined to indicate their full sizes.
520 If you want to use a QWidget to hold child widgets you will usually want to
521 add a layout to the parent QWidget. See \l{Layout Management} for more
525 \section1 Composite Widgets
527 When a widget is used as a container to group a number of child widgets, it
528 is known as a composite widget. These can be created by constructing a
529 widget with the required visual properties - a QFrame, for example - and
530 adding child widgets to it, usually managed by a layout. The above diagram
531 shows such a composite widget that was created using \l{Qt Designer}.
533 Composite widgets can also be created by subclassing a standard widget,
534 such as QWidget or QFrame, and adding the necessary layout and child
535 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
536 {examples provided with Qt} use this approach, and it is also covered in
537 the Qt \l{Tutorials}.
540 \section1 Custom Widgets and Painting
542 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
543 display custom content that is composed using a series of painting
544 operations with an instance of the QPainter class. This approach contrasts
545 with the canvas-style approach used by the \l{Graphics View}
546 {Graphics View Framework} where items are added to a scene by the
547 application and are rendered by the framework itself.
549 Each widget performs all painting operations from within its paintEvent()
550 function. This is called whenever the widget needs to be redrawn, either
551 as a result of some external change or when requested by the application.
553 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
554 can handle paint events.
557 \section1 Size Hints and Size Policies
559 When implementing a new widget, it is almost always useful to reimplement
560 sizeHint() to provide a reasonable default size for the widget and to set
561 the correct size policy with setSizePolicy().
563 By default, composite widgets which do not provide a size hint will be
564 sized according to the space requirements of their child widgets.
566 The size policy lets you supply good default behavior for the layout
567 management system, so that other widgets can contain and manage yours
568 easily. The default size policy indicates that the size hint represents
569 the preferred size of the widget, and this is often good enough for many
572 \note The size of top-level widgets are constrained to 2/3 of the desktop's
573 height and width. You can resize() the widget manually if these bounds are
579 Widgets respond to events that are typically caused by user actions. Qt
580 delivers events to widgets by calling specific event handler functions with
581 instances of QEvent subclasses containing information about each event.
583 If your widget only contains child widgets, you probably do not need to
584 implement any event handlers. If you want to detect a mouse click in a
585 child widget call the child's underMouse() function inside the widget's
588 The \l{widgets/scribble}{Scribble example} implements a wider set of
589 events to handle mouse movement, button presses, and window resizing.
591 You will need to supply the behavior and content for your own widgets, but
592 here is a brief overview of the events that are relevant to QWidget,
593 starting with the most common ones:
596 \li paintEvent() is called whenever the widget needs to be repainted.
597 Every widget displaying custom content must implement it. Painting
598 using a QPainter can only take place in a paintEvent() or a
599 function called by a paintEvent().
600 \li resizeEvent() is called when the widget has been resized.
601 \li mousePressEvent() is called when a mouse button is pressed while
602 the mouse cursor is inside the widget, or when the widget has
603 grabbed the mouse using grabMouse(). Pressing the mouse without
604 releasing it is effectively the same as calling grabMouse().
605 \li mouseReleaseEvent() is called when a mouse button is released. A
606 widget receives mouse release events when it has received the
607 corresponding mouse press event. This means that if the user
608 presses the mouse inside \e your widget, then drags the mouse
609 somewhere else before releasing the mouse button, \e your widget
610 receives the release event. There is one exception: if a popup menu
611 appears while the mouse button is held down, this popup immediately
612 steals the mouse events.
613 \li mouseDoubleClickEvent() is called when the user double-clicks in
614 the widget. If the user double-clicks, the widget receives a mouse
615 press event, a mouse release event, (a mouse click event,) a second
616 mouse press, this event and finally a second mouse release event.
617 (Some mouse move events may also be
618 received if the mouse is not held steady during this operation.) It
619 is \e{not possible} to distinguish a click from a double-click
620 until the second click arrives. (This is one reason why most GUI
621 books recommend that double-clicks be an extension of
622 single-clicks, rather than trigger a different action.)
625 Widgets that accept keyboard input need to reimplement a few more event
629 \li keyPressEvent() is called whenever a key is pressed, and again when
630 a key has been held down long enough for it to auto-repeat. The
631 \key Tab and \key Shift+Tab keys are only passed to the widget if
632 they are not used by the focus-change mechanisms. To force those
633 keys to be processed by your widget, you must reimplement
635 \li focusInEvent() is called when the widget gains keyboard focus
636 (assuming you have called setFocusPolicy()). Well-behaved widgets
637 indicate that they own the keyboard focus in a clear but discreet
639 \li focusOutEvent() is called when the widget loses keyboard focus.
642 You may be required to also reimplement some of the less common event
646 \li mouseMoveEvent() is called whenever the mouse moves while a mouse
647 button is held down. This can be useful during drag and drop
648 operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
649 you get mouse move events even when no buttons are held down.
650 (See also the \l{Drag and Drop} guide.)
651 \li keyReleaseEvent() is called whenever a key is released and while it
652 is held down (if the key is auto-repeating). In that case, the
653 widget will receive a pair of key release and key press event for
654 every repeat. The \key Tab and \key Shift+Tab keys are only passed
655 to the widget if they are not used by the focus-change mechanisms.
656 To force those keys to be processed by your widget, you must
657 reimplement QWidget::event().
658 \li wheelEvent() is called whenever the user turns the mouse wheel
659 while the widget has the focus.
660 \li enterEvent() is called when the mouse enters the widget's screen
661 space. (This excludes screen space owned by any of the widget's
663 \li leaveEvent() is called when the mouse leaves the widget's screen
664 space. If the mouse enters a child widget it will not cause a
666 \li moveEvent() is called when the widget has been moved relative to
668 \li closeEvent() is called when the user closes the widget (or when
672 There are also some rather obscure events described in the documentation
673 for QEvent::Type. To handle these events, you need to reimplement event()
676 The default implementation of event() handles \key Tab and \key Shift+Tab
677 (to move the keyboard focus), and passes on most of the other events to
678 one of the more specialized handlers above.
680 Events and the mechanism used to deliver them are covered in
681 \l{The Event System}.
683 \section1 Groups of Functions and Properties
686 \header \li Context \li Functions and Properties
688 \row \li Window functions \li
695 \row \li Top-level windows \li
696 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
697 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
698 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
701 \row \li Window contents \li
706 \row \li Geometry \li
707 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
708 \l sizePolicy, sizeHint(), minimumSizeHint(),
709 updateGeometry(), layout(),
710 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
712 mapFromGlobal(), mapToGlobal(),
713 mapFromParent(), mapToParent(),
714 \l maximumSize, \l minimumSize, \l sizeIncrement,
715 \l baseSize, setFixedSize()
718 \l visible, isVisibleTo(),
719 \l enabled, isEnabledTo(),
726 \row \li Look and feel \li
733 backgroundRole(), setBackgroundRole(),
734 fontInfo(), fontMetrics().
736 \row \li Keyboard focus functions \li
737 \l focus, \l focusPolicy,
738 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
739 focusNextChild(), focusPreviousChild().
741 \row \li Mouse and keyboard grabbing \li
742 grabMouse(), releaseMouse(),
743 grabKeyboard(), releaseKeyboard(),
744 mouseGrabber(), keyboardGrabber().
746 \row \li Event handlers \li
750 mouseDoubleClickEvent(),
773 \row \li System functions \li
774 parentWidget(), window(), setParent(), winId(),
777 \row \li Interactive help \li
778 setToolTip(), setWhatsThis()
783 \section1 Widget Style Sheets
785 In addition to the standard widget styles for each platform, widgets can
786 also be styled according to rules specified in a \l{styleSheet}
787 {style sheet}. This feature enables you to customize the appearance of
788 specific widgets to provide visual cues to users about their purpose. For
789 example, a button could be styled in a particular way to indicate that it
790 performs a destructive action.
792 The use of widget style sheets is described in more detail in the
793 \l{Qt Style Sheets} document.
796 \section1 Transparency and Double Buffering
798 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
799 is no need to write double-buffering code in paintEvent() to avoid
802 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
803 deprecated. Instead, the contents of parent widgets are propagated by
804 default to each of their children as long as Qt::WA_PaintOnScreen is not
805 set. Custom widgets can be written to take advantage of this feature by
806 updating irregular regions (to create non-rectangular child widgets), or
807 painting with colors that have less than full alpha component. The
808 following diagram shows how attributes and properties of a custom widget
809 can be fine-tuned to achieve different effects.
811 \image propagation-custom.png
813 In the above diagram, a semi-transparent rectangular child widget with an
814 area removed is constructed and added to a parent widget (a QLabel showing
815 a pixmap). Then, different properties and widget attributes are set to
816 achieve different effects:
819 \li The left widget has no additional properties or widget attributes
820 set. This default state suits most custom widgets using
821 transparency, are irregularly-shaped, or do not paint over their
822 entire area with an opaque brush.
823 \li The center widget has the \l autoFillBackground property set. This
824 property is used with custom widgets that rely on the widget to
825 supply a default background, and do not paint over their entire
826 area with an opaque brush.
827 \li The right widget has the Qt::WA_OpaquePaintEvent widget attribute
828 set. This indicates that the widget will paint over its entire area
829 with opaque colors. The widget's area will initially be
830 \e{uninitialized}, represented in the diagram with a red diagonal
831 grid pattern that shines through the overpainted area. The
832 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
833 paint their own specialized contents quickly and do not need a
834 default filled background.
837 To rapidly update custom widgets with simple background colors, such as
838 real-time plotting or graphing widgets, it is better to define a suitable
839 background color (using setBackgroundRole() with the
840 QPalette::Window role), set the \l autoFillBackground property, and only
841 implement the necessary drawing functionality in the widget's paintEvent().
843 To rapidly update custom widgets that constantly paint over their entire
844 areas with opaque content, e.g., video streaming widgets, it is better to
845 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
846 associated with repainting the widget's background.
848 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
849 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
850 attribute takes precedence. Depending on your requirements, you should
851 choose either one of them.
853 Since Qt 4.1, the contents of parent widgets are also propagated to
854 standard Qt widgets. This can lead to some unexpected results if the
855 parent widget is decorated in a non-standard way, as shown in the diagram
858 \image propagation-standard.png
860 The scope for customizing the painting behavior of standard Qt widgets,
861 without resorting to subclassing, is slightly less than that possible for
862 custom widgets. Usually, the desired appearance of a standard widget can be
863 achieved by setting its \l autoFillBackground property.
866 \section1 Creating Translucent Windows
868 Since Qt 4.5, it has been possible to create windows with translucent regions
869 on window systems that support compositing.
871 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
872 attribute with setAttribute() and ensure that its background is painted with
873 non-opaque colors in the regions you want to be partially transparent.
878 \li X11: This feature relies on the use of an X server that supports ARGB visuals
879 and a compositing window manager.
880 \li Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
881 for the translucency to work.
885 \section1 Native Widgets vs Alien Widgets
887 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
888 system. They do not have a native window handle associated with them. This
889 feature significantly speeds up widget painting, resizing, and removes flicker.
891 Should you require the old behavior with native windows, you can choose
892 one of the following options:
895 \li Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
896 \li Set the Qt::AA_NativeWindows attribute on your application. All
897 widgets will be native widgets.
898 \li Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
899 and all of its ancestors will become native (unless
900 Qt::WA_DontCreateNativeAncestors is set).
901 \li Call QWidget::winId to enforce a native window (this implies 3).
902 \li Set the Qt::WA_PaintOnScreen attribute to enforce a native window
906 \sa QEvent, QPainter, QGridLayout, QBoxLayout
910 Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
911 other visual representation on the screen that is generally located next to its
912 physical counterpart. They are most often found on mobile phone platforms. In
913 modern touch based user interfaces it is also possible to have softkeys that do
914 not correspond to any physical keys. Softkeys differ from other onscreen labels
915 in that they are contextual.
917 In Qt, contextual softkeys are added to a widget by calling addAction() and
918 passing a \c QAction with a softkey role set on it. When the widget
919 containing the softkey actions has focus, its softkeys should appear in
920 the user interface. Softkeys are discovered by traversing the widget
921 hierarchy so it is possible to define a single set of softkeys that are
922 present at all times by calling addAction() for a given top level widget.
924 On some platforms, this concept overlaps with \c QMenuBar such that if no
925 other softkeys are found and the top level widget is a QMainWindow containing
926 a QMenuBar, the menubar actions may appear on one of the softkeys.
928 Note: Currently softkeys are only supported on the Symbian Platform.
930 \sa addAction(), QAction, QMenuBar
934 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
935 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
938 /*****************************************************************************
939 QWidget utility functions
940 *****************************************************************************/
942 QRegion qt_dirtyRegion(QWidget *widget)
947 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
951 return bs->dirtyRegion(widget);
954 /*****************************************************************************
955 QWidget member functions
956 *****************************************************************************/
961 \li Qt::WA_WState_Created The widget has a valid winId().
962 \li Qt::WA_WState_Visible The widget is currently visible.
963 \li Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
964 become visible unless you call show() on it. Qt::WA_WState_Hidden
965 implies !Qt::WA_WState_Visible.
966 \li Qt::WA_WState_CompressKeys Compress keyboard events.
967 \li Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
968 \li Qt::WA_WState_InPaintEvent Currently processing a paint event.
969 \li Qt::WA_WState_Reparented The widget has been reparented.
970 \li Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
971 \li Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
975 struct QWidgetExceptionCleaner
977 /* this cleans up when the constructor throws an exception */
978 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
980 #ifdef QT_NO_EXCEPTIONS
984 QWidgetPrivate::allWidgets->remove(that);
985 if (d->focus_next != that) {
987 d->focus_next->d_func()->focus_prev = d->focus_prev;
989 d->focus_prev->d_func()->focus_next = d->focus_next;
996 Constructs a widget which is a child of \a parent, with widget
999 If \a parent is 0, the new widget becomes a window. If
1000 \a parent is another widget, this widget becomes a child window
1001 inside \a parent. The new widget is deleted when its \a parent is
1004 The widget flags argument, \a f, is normally 0, but it can be set
1005 to customize the frame of a window (i.e. \a
1006 parent must be 0). To customize the frame, use a value composed
1007 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1009 If you add a child widget to an already visible widget you must
1010 explicitly show the child to make it visible.
1012 Note that the X11 version of Qt may not be able to deliver all
1013 combinations of style flags on all systems. This is because on
1014 X11, Qt can only ask the window manager, and the window manager
1015 can override the application's settings. On Windows, Qt can set
1016 whatever flags you want.
1020 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1021 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1024 d_func()->init(parent, f);
1026 QWidgetExceptionCleaner::cleanup(this, d_func());
1034 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1035 : QObject(dd, 0), QPaintDevice()
1041 QWidgetExceptionCleaner::cleanup(this, d_func());
1049 int QWidget::devType() const
1051 return QInternal::Widget;
1055 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1056 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1058 bool customize = (flags & (Qt::CustomizeWindowHint
1059 | Qt::FramelessWindowHint
1060 | Qt::WindowTitleHint
1061 | Qt::WindowSystemMenuHint
1062 | Qt::WindowMinimizeButtonHint
1063 | Qt::WindowMaximizeButtonHint
1064 | Qt::WindowCloseButtonHint
1065 | Qt::WindowContextHelpButtonHint));
1067 uint type = (flags & Qt::WindowType_Mask);
1069 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1071 flags |= Qt::Window;
1074 if (flags & Qt::CustomizeWindowHint) {
1075 // modify window flags to make them consistent.
1076 // Only enable this on non-Mac platforms. Since the old way of doing this would
1077 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1078 // we can't just add this in.
1080 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1081 flags |= Qt::WindowSystemMenuHint;
1083 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1084 | Qt::WindowSystemMenuHint)) {
1086 flags |= Qt::WindowTitleHint;
1087 flags &= ~Qt::FramelessWindowHint;
1089 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1090 // if any of the window hints that affect the titlebar are set
1091 // and the window is supposed to have frame, we add a titlebar
1092 // and system menu by default.
1093 flags |= Qt::WindowSystemMenuHint;
1094 flags |= Qt::WindowTitleHint;
1097 ; // don't modify window flags if the user explicitly set them.
1098 else if (type == Qt::Dialog || type == Qt::Sheet)
1100 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1102 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1104 else if (type == Qt::Tool)
1105 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1107 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1112 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1115 if (QApplication::type() == QApplication::Tty)
1116 qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1118 Q_ASSERT(allWidgets);
1120 allWidgets->insert(q);
1122 QWidget *desktopWidget = 0;
1123 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1124 desktopWidget = parentWidget;
1130 #ifndef QT_NO_THREAD
1132 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1133 "Widgets must be created in the GUI thread.");
1137 #if defined(Q_WS_X11)
1138 if (desktopWidget) {
1139 // make sure the widget is created on the same screen as the
1140 // programmer specified desktop widget
1141 xinfo = desktopWidget->d_func()->xinfo;
1144 if (desktopWidget) {
1145 const int screen = desktopWidget->d_func()->topData()->screenIndex;
1146 if (QWindow *window = q->windowHandle())
1147 window->setScreen(QGuiApplication::screens().value(screen, 0));
1150 data.fstrut_dirty = true;
1153 data.widget_attributes = 0;
1154 data.window_flags = f;
1155 data.window_state = 0;
1156 data.focus_policy = 0;
1157 data.context_menu_policy = Qt::DefaultContextMenu;
1158 data.window_modality = Qt::NonModal;
1160 data.sizehint_forced = 0;
1161 data.is_closing = 0;
1163 data.in_set_window_state = 0;
1164 data.in_destructor = false;
1166 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1167 if (f & Qt::MSWindowsOwnDC)
1168 q->setAttribute(Qt::WA_NativeWindow);
1171 // q->setAttribute(Qt::WA_NativeWindow);
1174 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1175 adjustQuitOnCloseAttribute();
1177 q->setAttribute(Qt::WA_WState_Hidden);
1179 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1180 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1181 focus_next = focus_prev = q;
1183 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1185 else if (parentWidget)
1186 q->setParent(parentWidget, data.window_flags);
1188 adjustFlags(data.window_flags, q);
1189 resolveLayoutDirection();
1190 // opaque system background?
1191 const QBrush &background = q->palette().brush(QPalette::Window);
1192 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1194 data.fnt = QFont(data.fnt, q);
1195 #if defined(Q_WS_X11)
1196 data.fnt.x11SetScreen(xinfo.screen());
1199 q->setAttribute(Qt::WA_PendingMoveEvent);
1200 q->setAttribute(Qt::WA_PendingResizeEvent);
1202 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1203 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1205 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1208 QEvent e(QEvent::Create);
1209 QApplication::sendEvent(q, &e);
1210 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1212 extraPaintEngine = 0;
1215 // If we add a child to the unified toolbar, we have to redirect the painting.
1216 if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1217 if (parentWidget->d_func()->unifiedSurface) {
1218 QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1219 parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1227 void QWidgetPrivate::createRecursively()
1230 q->create(0, true, true);
1231 for (int i = 0; i < children.size(); ++i) {
1232 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1233 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1234 child->d_func()->createRecursively();
1242 Creates a new widget window if \a window is 0, otherwise sets the
1243 widget's window to \a window.
1245 Initializes the window (sets the geometry etc.) if \a
1246 initializeWindow is true. If \a initializeWindow is false, no
1247 initialization is performed. This parameter only makes sense if \a
1248 window is a valid window.
1250 Destroys the old window if \a destroyOldWindow is true. If \a
1251 destroyOldWindow is false, you are responsible for destroying the
1252 window yourself (using platform native code).
1254 The QWidget constructor calls create(0,true,true) to create a
1255 window for this widget.
1258 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1261 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1264 if (d->data.in_destructor)
1267 Qt::WindowType type = windowType();
1268 Qt::WindowFlags &flags = data->window_flags;
1270 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1272 flags |= Qt::Window;
1275 if (QWidget *parent = parentWidget()) {
1276 if (type & Qt::Window) {
1277 if (!parent->testAttribute(Qt::WA_WState_Created))
1278 parent->createWinId();
1279 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1280 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1281 // We're about to create a native child widget that doesn't have a native parent;
1282 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1283 // attribute is set.
1284 d->createWinId(window);
1285 // Nothing more to do.
1286 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1287 Q_ASSERT(internalWinId());
1293 static int paintOnScreenEnv = -1;
1294 if (paintOnScreenEnv == -1)
1295 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1296 if (paintOnScreenEnv == 1)
1297 setAttribute(Qt::WA_PaintOnScreen);
1299 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1300 setAttribute(Qt::WA_NativeWindow);
1303 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1304 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1307 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1308 // Unregister the dropsite (if already registered) before we
1309 // re-create the widget with a native window.
1310 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1311 && d->extra && d->extra->dropTarget) {
1312 d->registerDropSite(false);
1314 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1316 d->updateIsOpaque();
1318 setAttribute(Qt::WA_WState_Created); // set created flag
1319 d->create_sys(window, initializeWindow, destroyOldWindow);
1321 // a real toplevel window needs a backing store
1322 if (isWindow() && windowType() != Qt::Desktop) {
1323 d->topData()->backingStoreTracker.destroy();
1324 if (hasBackingStoreSupport())
1325 d->topData()->backingStoreTracker.create(this);
1330 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1331 setAttribute(Qt::WA_DropSiteRegistered, true);
1334 extern void qt_eval_init_widget(QWidget *w);
1335 qt_eval_init_widget(this);
1338 // need to force the resting of the icon after changing parents
1339 if (testAttribute(Qt::WA_SetWindowIcon))
1340 d->setWindowIcon_sys(true);
1341 if (isWindow() && !d->topData()->iconText.isEmpty())
1342 d->setWindowIconText_helper(d->topData()->iconText);
1343 if (isWindow() && !d->topData()->caption.isEmpty())
1344 d->setWindowTitle_helper(d->topData()->caption);
1345 if (windowType() != Qt::Desktop) {
1346 d->updateSystemBackground();
1348 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1349 d->setWindowIcon_sys();
1354 Destroys the widget.
1356 All this widget's children are deleted first. The application
1357 exits if this widget is the main widget.
1363 d->data.in_destructor = true;
1365 #if defined (QT_CHECK_STATE)
1366 if (paintingActive())
1367 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1370 #ifndef QT_NO_GESTURES
1371 foreach (Qt::GestureType type, d->gestureContext.keys())
1372 ungrabGesture(type);
1375 // force acceptDrops false before winId is destroyed.
1376 d->registerDropSite(false);
1378 #ifndef QT_NO_ACTION
1379 // remove all actions from this widget
1380 for (int i = 0; i < d->actions.size(); ++i) {
1381 QActionPrivate *apriv = d->actions.at(i)->d_func();
1382 apriv->widgets.removeAll(this);
1387 #ifndef QT_NO_SHORTCUT
1388 // Remove all shortcuts grabbed by this
1389 // widget, unless application is closing
1390 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1391 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1394 // delete layout while we still are a valid widget
1397 // Remove myself from focus list
1399 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1400 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1402 if (d->focus_next != this) {
1403 d->focus_next->d_func()->focus_prev = d->focus_prev;
1404 d->focus_prev->d_func()->focus_next = d->focus_next;
1405 d->focus_next = d->focus_prev = 0;
1412 // swallow this problem because we are in a destructor
1415 d->setDirtyOpaqueRegion();
1417 if (isWindow() && isVisible() && internalWinId()) {
1419 d->close_helper(QWidgetPrivate::CloseNoEvent);
1421 // if we're out of memory, at least hide the window.
1425 // and if that also doesn't work, then give up
1430 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1431 else if (!internalWinId() && isVisible()) {
1432 qApp->d_func()->sendSyntheticEnterLeave(this);
1435 else if (isVisible()) {
1436 qApp->d_func()->sendSyntheticEnterLeave(this);
1439 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1440 bs->removeDirtyWidget(this);
1441 if (testAttribute(Qt::WA_StaticContents))
1442 bs->removeStaticWidget(this);
1445 delete d->needsFlush;
1448 if (d->declarativeData) {
1449 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1450 d->declarativeData = 0; // don't activate again in ~QObject
1454 // QCocoaView holds a pointer back to this widget. Clear it now
1455 // to make sure it's not followed later on. The lifetime of the
1456 // QCocoaView might exceed the lifetime of this widget in cases
1457 // where Cocoa itself holds references to it.
1458 extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1459 qt_mac_clearCocoaViewQWidgetPointers(this);
1462 if (!d->children.isEmpty())
1463 d->deleteChildren();
1465 QApplication::removePostedEvents(this);
1468 destroy(); // platform-dependent cleanup
1470 // if this fails we can't do anything about it but at least we are not allowed to throw.
1472 --QWidgetPrivate::instanceCounter;
1474 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1475 QWidgetPrivate::allWidgets->remove(this);
1478 QEvent e(QEvent::Destroy);
1479 QCoreApplication::sendEvent(this, &e);
1480 } QT_CATCH(const std::exception&) {
1481 // if this fails we can't do anything about it but at least we are not allowed to throw.
1485 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1486 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1488 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1491 // the user might create a widget with Qt::Desktop window
1492 // attribute (or create another QDesktopWidget instance), which
1493 // will have the same windowid (the root window id) as the
1494 // qt_desktopWidget. We should not add the second desktop widget
1496 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1497 if (mapper && data.winid && !userDesktopWidget) {
1498 mapper->remove(data.winid);
1501 const WId oldWinId = data.winid;
1504 #if defined(Q_WS_X11)
1505 hd = id; // X11: hd == ident
1507 if (mapper && id && !userDesktopWidget) {
1508 mapper->insert(data.winid, q);
1511 if(oldWinId != id) {
1512 QEvent e(QEvent::WinIdChange);
1513 QCoreApplication::sendEvent(q, &e);
1517 void QWidgetPrivate::createTLExtra()
1521 if (!extra->topextra) {
1522 QTLWExtra* x = extra->topextra = new QTLWExtra;
1525 x->backingStore = 0;
1526 x->sharedPainter = 0;
1527 x->incw = x->inch = 0;
1528 x->basew = x->baseh = 0;
1529 x->frameStrut.setCoords(0, 0, 0, 0);
1530 x->normalGeometry = QRect(0,0,-1,-1);
1533 x->posFromMove = false;
1534 x->sizeAdjusted = false;
1535 x->inTopLevelResize = false;
1536 x->inRepaint = false;
1539 x->wasMaximized = false;
1542 #ifdef QWIDGET_EXTRA_DEBUG
1543 static int count = 0;
1544 qDebug() << "tlextra" << ++count;
1551 Creates the widget extra data.
1554 void QWidgetPrivate::createExtra()
1556 if (!extra) { // if not exists
1557 extra = new QWExtra;
1558 extra->glContext = 0;
1559 extra->topextra = 0;
1560 #ifndef QT_NO_GRAPHICSVIEW
1561 extra->proxyWidget = 0;
1563 #ifndef QT_NO_CURSOR
1568 extra->maxw = QWIDGETSIZE_MAX;
1569 extra->maxh = QWIDGETSIZE_MAX;
1570 extra->customDpiX = 0;
1571 extra->customDpiY = 0;
1572 extra->explicitMinSize = 0;
1573 extra->explicitMaxSize = 0;
1574 extra->autoFillBackground = 0;
1575 extra->nativeChildrenForced = 0;
1576 extra->inRenderWithPainter = 0;
1579 #ifdef QWIDGET_EXTRA_DEBUG
1580 static int count = 0;
1581 qDebug() << "extra" << ++count;
1589 Deletes the widget extra data.
1592 void QWidgetPrivate::deleteExtra()
1594 if (extra) { // if exists
1595 #ifndef QT_NO_CURSOR
1599 #ifndef QT_NO_STYLE_STYLESHEET
1600 // dereference the stylesheet style
1601 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1604 if (extra->topextra) {
1606 extra->topextra->backingStoreTracker.destroy();
1607 delete extra->topextra->icon;
1608 delete extra->topextra->iconPixmap;
1609 delete extra->topextra->backingStore;
1610 delete extra->topextra;
1613 // extra->xic destroyed in QWidget::destroy()
1619 Returns true if there are widgets above this which overlap with
1620 \a rect, which is in parent's coordinate system (same as crect).
1623 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1627 const QWidget *w = q;
1632 QWidgetPrivate *pd = w->parentWidget()->d_func();
1634 for (int i = 0; i < pd->children.size(); ++i) {
1635 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1636 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1639 above = (sibling == w);
1643 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1644 const QWExtra *siblingExtra = sibling->d_func()->extra;
1645 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1646 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1652 w = w->parentWidget();
1653 r.translate(pd->data.crect.topLeft());
1658 void QWidgetPrivate::syncBackingStore()
1660 if (paintOnScreen()) {
1663 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1668 void QWidgetPrivate::syncBackingStore(const QRegion ®ion)
1670 if (paintOnScreen())
1671 repaint_sys(region);
1672 else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1673 bs->sync(q_func(), region);
1677 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1681 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1682 return; // nothing we can do
1684 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1685 return; // nothing to do
1687 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1691 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1692 for (int i = 0; i < children.size(); ++i) {
1693 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1694 if (w && !w->isWindow() && !w->testAttribute(attribute))
1695 w->d_func()->setUpdatesEnabled_helper(enable);
1702 Propagate this widget's palette to all children, except style sheet
1703 widgets, and windows that don't enable window propagation (palettes don't
1704 normally propagate to windows).
1706 void QWidgetPrivate::propagatePaletteChange()
1709 // Propagate a new inherited mask to all children.
1710 #ifndef QT_NO_GRAPHICSVIEW
1711 if (!q->parentWidget() && extra && extra->proxyWidget) {
1712 QGraphicsProxyWidget *p = extra->proxyWidget;
1713 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1715 #endif //QT_NO_GRAPHICSVIEW
1716 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1717 inheritedPaletteResolveMask = 0;
1719 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1721 QEvent pc(QEvent::PaletteChange);
1722 QApplication::sendEvent(q, &pc);
1723 for (int i = 0; i < children.size(); ++i) {
1724 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1725 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1726 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1727 QWidgetPrivate *wd = w->d_func();
1728 wd->inheritedPaletteResolveMask = mask;
1729 wd->resolvePalette();
1735 Returns the widget's clipping rectangle.
1737 QRect QWidgetPrivate::clipRect() const
1740 const QWidget * w = q;
1741 if (!w->isVisible())
1743 QRect r = effectiveRectFor(q->rect());
1749 && w->parentWidget()) {
1752 w = w->parentWidget();
1753 r &= QRect(ox, oy, w->width(), w->height());
1759 Returns the widget's clipping region (without siblings).
1761 QRegion QWidgetPrivate::clipRegion() const
1764 if (!q->isVisible())
1766 QRegion r(q->rect());
1767 const QWidget * w = q;
1768 const QWidget *ignoreUpTo;
1774 && w->parentWidget()) {
1778 w = w->parentWidget();
1779 r &= QRegion(ox, oy, w->width(), w->height());
1782 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1784 for ( ; i < w->d_func()->children.size(); ++i) {
1785 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1786 if(sibling->isVisible() && !sibling->isWindow()) {
1787 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1788 sibling->width(), sibling->height());
1789 if (qRectIntersects(siblingRect, q->rect()))
1790 r -= QRegion(siblingRect);
1798 #ifndef QT_NO_GRAPHICSEFFECT
1799 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1804 if (w->graphicsEffect()) {
1805 QWidgetEffectSourcePrivate *sourced =
1806 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1807 if (!sourced->updateDueToGraphicsEffect)
1808 w->graphicsEffect()->source()->d_func()->invalidateCache();
1810 w = w->parentWidget();
1813 #endif //QT_NO_GRAPHICSEFFECT
1815 void QWidgetPrivate::setDirtyOpaqueRegion()
1819 dirtyOpaqueChildren = true;
1821 #ifndef QT_NO_GRAPHICSEFFECT
1822 invalidateGraphicsEffectsRecursively();
1823 #endif //QT_NO_GRAPHICSEFFECT
1828 QWidget *parent = q->parentWidget();
1832 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1833 QWidgetPrivate *pd = parent->d_func();
1834 if (!pd->dirtyOpaqueChildren)
1835 pd->setDirtyOpaqueRegion();
1838 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1840 if (!dirtyOpaqueChildren)
1841 return opaqueChildren;
1843 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1844 that->opaqueChildren = QRegion();
1846 for (int i = 0; i < children.size(); ++i) {
1847 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1848 if (!child || !child->isVisible() || child->isWindow())
1851 const QPoint offset = child->geometry().topLeft();
1852 QWidgetPrivate *childd = child->d_func();
1853 QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1854 if (childd->extra && childd->extra->hasMask)
1855 r &= childd->extra->mask;
1858 r.translate(offset);
1859 that->opaqueChildren += r;
1862 that->opaqueChildren &= q_func()->rect();
1863 that->dirtyOpaqueChildren = false;
1865 return that->opaqueChildren;
1868 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1870 if (children.isEmpty() || clipRect.isEmpty())
1873 const QRegion &r = getOpaqueChildren();
1875 source -= (r & clipRect);
1878 //subtract any relatives that are higher up than me --- this is too expensive !!!
1879 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1880 bool alsoNonOpaque) const
1883 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1884 if (disableSubtractOpaqueSiblings || q->isWindow())
1888 if (q->d_func()->isInUnifiedToolbar)
1892 QRect clipBoundingRect;
1893 bool dirtyClipBoundingRect = true;
1896 bool dirtyParentClip = true;
1898 QPoint parentOffset = data.crect.topLeft();
1900 const QWidget *w = q;
1905 QWidgetPrivate *pd = w->parentWidget()->d_func();
1906 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1907 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1908 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1909 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1910 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1913 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1914 if (!qRectIntersects(siblingGeometry, widgetGeometry))
1917 if (dirtyClipBoundingRect) {
1918 clipBoundingRect = sourceRegion.boundingRect();
1919 dirtyClipBoundingRect = false;
1922 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1925 if (dirtyParentClip) {
1926 parentClip = sourceRegion.translated(parentOffset);
1927 dirtyParentClip = false;
1930 const QPoint siblingPos(sibling->data->crect.topLeft());
1931 const QRect siblingClipRect(sibling->d_func()->clipRect());
1932 QRegion siblingDirty(parentClip);
1933 siblingDirty &= (siblingClipRect.translated(siblingPos));
1934 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
1935 && !sibling->d_func()->graphicsEffect;
1937 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
1938 if (siblingDirty.isEmpty())
1941 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
1943 siblingDirty.translate(-parentOffset);
1944 sourceRegion -= siblingDirty;
1946 sourceRegion -= siblingGeometry.translated(-parentOffset);
1949 if (hasDirtySiblingsAbove)
1950 *hasDirtySiblingsAbove = true;
1951 if (sibling->d_func()->children.isEmpty())
1953 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
1954 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
1955 sourceRegion -= opaqueSiblingChildren;
1957 if (sourceRegion.isEmpty())
1960 dirtyClipBoundingRect = true;
1961 dirtyParentClip = true;
1964 w = w->parentWidget();
1965 parentOffset += pd->data.crect.topLeft();
1966 dirtyParentClip = true;
1970 void QWidgetPrivate::clipToEffectiveMask(QRegion ®ion) const
1974 const QWidget *w = q;
1977 #ifndef QT_NO_GRAPHICSEFFECT
1978 if (graphicsEffect) {
1979 w = q->parentWidget();
1980 offset -= data.crect.topLeft();
1982 #endif //QT_NO_GRAPHICSEFFECT
1985 const QWidgetPrivate *wd = w->d_func();
1986 if (wd->extra && wd->extra->hasMask)
1987 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
1990 offset -= wd->data.crect.topLeft();
1991 w = w->parentWidget();
1995 bool QWidgetPrivate::paintOnScreen() const
1997 #if defined(QT_NO_BACKINGSTORE)
2001 if (q->testAttribute(Qt::WA_PaintOnScreen)
2002 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2006 return !qt_enable_backingstore;
2010 void QWidgetPrivate::updateIsOpaque()
2012 // hw: todo: only needed if opacity actually changed
2013 setDirtyOpaqueRegion();
2015 #ifndef QT_NO_GRAPHICSEFFECT
2016 if (graphicsEffect) {
2017 // ### We should probably add QGraphicsEffect::isOpaque at some point.
2021 #endif //QT_NO_GRAPHICSEFFECT
2025 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2031 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2036 const QPalette &pal = q->palette();
2038 if (q->autoFillBackground()) {
2039 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2040 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2046 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2047 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2048 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2056 void QWidgetPrivate::setOpaque(bool opaque)
2058 if (isOpaque == opaque)
2062 macUpdateIsOpaque();
2065 x11UpdateIsOpaque();
2068 winUpdateIsOpaque();
2072 void QWidgetPrivate::updateIsTranslucent()
2075 macUpdateIsOpaque();
2078 x11UpdateIsOpaque();
2081 winUpdateIsOpaque();
2085 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2089 if (brush.style() == Qt::TexturePattern) {
2091 // Optimize pattern filling on mac by using HITheme directly
2092 // when filling with the standard widget background.
2093 // Defined in qmacstyle_mac.cpp
2094 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2095 qt_mac_fill_background(painter, rgn, brush);
2098 const QRect rect(rgn.boundingRect());
2099 painter->setClipRegion(rgn);
2100 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2104 } else if (brush.gradient()
2105 && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2107 painter->setClipRegion(rgn);
2108 painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2111 const QVector<QRect> &rects = rgn.rects();
2112 for (int i = 0; i < rects.size(); ++i)
2113 painter->fillRect(rects.at(i), brush);
2117 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2121 #ifndef QT_NO_SCROLLAREA
2122 bool resetBrushOrigin = false;
2123 QPointF oldBrushOrigin;
2124 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2125 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2126 if (scrollArea && scrollArea->viewport() == q) {
2127 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2128 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2129 oldBrushOrigin = painter->brushOrigin();
2130 resetBrushOrigin = true;
2131 painter->setBrushOrigin(-priv->contentsOffset());
2134 #endif // QT_NO_SCROLLAREA
2136 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2138 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2139 const QBrush bg = q->palette().brush(QPalette::Window);
2140 fillRegion(painter, rgn, bg);
2143 if (q->autoFillBackground())
2144 fillRegion(painter, rgn, autoFillBrush);
2146 if (q->testAttribute(Qt::WA_StyledBackground)) {
2147 painter->setClipRegion(rgn);
2150 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2153 #ifndef QT_NO_SCROLLAREA
2154 if (resetBrushOrigin)
2155 painter->setBrushOrigin(oldBrushOrigin);
2156 #endif // QT_NO_SCROLLAREA
2161 This function is called when a widget is hidden or destroyed.
2162 It resets some application global pointers that should only refer active,
2167 extern QPointer<QWidget> qt_button_down;
2169 extern QWidget *qt_button_down;
2172 void QWidgetPrivate::deactivateWidgetCleanup()
2175 // If this was the active application window, reset it
2176 if (QApplication::activeWindow() == q)
2177 QApplication::setActiveWindow(0);
2178 // If the is the active mouse press widget, reset it
2179 if (q == qt_button_down)
2185 Returns a pointer to the widget with window identifer/handle \a
2188 The window identifier type depends on the underlying window
2189 system, see \c qwindowdefs.h for the actual definition. If there
2190 is no widget with this identifier, 0 is returned.
2193 QWidget *QWidget::find(WId id)
2195 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2201 \fn WId QWidget::internalWinId() const
2203 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2208 \fn WId QWidget::winId() const
2210 Returns the window system identifier of the widget.
2212 Portable in principle, but if you use it you are probably about to
2213 do something non-portable. Be careful.
2215 If a widget is non-native (alien) and winId() is invoked on it, that widget
2216 will be provided a native handle.
2218 On Mac OS X, the type returned depends on which framework Qt was linked
2219 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2220 is using Cocoa, {WId} is a pointer to an NSView.
2222 This value may change at run-time. An event with type QEvent::WinIdChange
2223 will be sent to the widget following a change in window system identifier.
2227 WId QWidget::winId() const
2229 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2231 qDebug() << "QWidget::winId: creating native window for" << this;
2233 QWidget *that = const_cast<QWidget*>(this);
2234 that->setAttribute(Qt::WA_NativeWindow);
2235 that->d_func()->createWinId();
2236 return that->data->winid;
2242 void QWidgetPrivate::createWinId(WId winid)
2247 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2249 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2250 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2251 if (!q->isWindow()) {
2252 QWidget *parent = q->parentWidget();
2253 QWidgetPrivate *pd = parent->d_func();
2254 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2255 parent->setAttribute(Qt::WA_NativeWindow);
2256 if (!parent->internalWinId()) {
2260 for (int i = 0; i < pd->children.size(); ++i) {
2261 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2262 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2263 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2268 // if the window has already been created, we
2269 // need to raise it to its proper stacking position
2284 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2288 void QWidget::createWinId()
2292 qDebug() << "QWidget::createWinId" << this;
2294 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2301 Returns the effective window system identifier of the widget, i.e. the
2302 native parent's window system identifier.
2304 If the widget is native, this function returns the native widget ID.
2305 Otherwise, the window ID of the first native parent widget, i.e., the
2306 top-level widget that contains this widget, is returned.
2308 \note We recommend that you do not store this value as it is likely to
2311 \sa nativeParentWidget()
2313 WId QWidget::effectiveWinId() const
2315 WId id = internalWinId();
2316 if (id || !testAttribute(Qt::WA_WState_Created))
2318 QWidget *realParent = nativeParentWidget();
2319 if (!realParent && d_func()->inSetParent) {
2320 // In transitional state. This is really just a workaround. The real problem
2321 // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2322 // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2323 // attribute to false. The correct way is to do it the other way around, and
2324 // in that case the Qt::WA_WState_Created logic above will kick in and
2325 // return 0 whenever the widget is in a transitional state. However, changing
2326 // the original logic for all platforms is far more intrusive and might
2327 // break existing applications.
2328 // Note: The widget can only be in a transitional state when changing its
2329 // parent -- everything else is an internal error -- hence explicitly checking
2330 // against 'inSetParent' rather than doing an unconditional return whenever
2331 // 'realParent' is 0 (which may cause strange artifacts and headache later).
2334 // This widget *must* have a native parent widget.
2335 Q_ASSERT(realParent);
2336 Q_ASSERT(realParent->internalWinId());
2337 return realParent->internalWinId();
2340 #ifndef QT_NO_STYLE_STYLESHEET
2343 \property QWidget::styleSheet
2344 \brief the widget's style sheet
2347 The style sheet contains a textual description of customizations to the
2348 widget's style, as described in the \l{Qt Style Sheets} document.
2350 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2352 \warning Qt style sheets are currently not supported for custom QStyle
2353 subclasses. We plan to address this in some future release.
2355 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2357 QString QWidget::styleSheet() const
2362 return d->extra->styleSheet;
2365 void QWidget::setStyleSheet(const QString& styleSheet)
2370 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2371 d->extra->styleSheet = styleSheet;
2372 if (styleSheet.isEmpty()) { // stylesheet removed
2380 if (proxy) { // style sheet update
2381 proxy->repolish(this);
2385 if (testAttribute(Qt::WA_SetStyle)) {
2386 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2388 d->setStyle_helper(new QStyleSheetStyle(0), true);
2392 #endif // QT_NO_STYLE_STYLESHEET
2395 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2398 QStyle *QWidget::style() const
2402 if (d->extra && d->extra->style)
2403 return d->extra->style;
2404 return QApplication::style();
2408 Sets the widget's GUI style to \a style. The ownership of the style
2409 object is not transferred.
2411 If no style is set, the widget uses the application's style,
2412 QApplication::style() instead.
2414 Setting a widget's style has no effect on existing or future child
2417 \warning This function is particularly useful for demonstration
2418 purposes, where you want to show Qt's styling capabilities. Real
2419 applications should avoid it and use one consistent GUI style
2422 \warning Qt style sheets are currently not supported for custom QStyle
2423 subclasses. We plan to address this in some future release.
2425 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2428 void QWidget::setStyle(QStyle *style)
2431 setAttribute(Qt::WA_SetStyle, style != 0);
2433 #ifndef QT_NO_STYLE_STYLESHEET
2434 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2435 //if for some reason someone try to set a QStyleSheetStyle, ref it
2436 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2438 d->setStyle_helper(style, false);
2439 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2440 // if we have an application stylesheet or have a proxy already, propagate
2441 d->setStyle_helper(new QStyleSheetStyle(style), true);
2444 d->setStyle_helper(style, false);
2447 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2454 QStyle *oldStyle = q->style();
2455 #ifndef QT_NO_STYLE_STYLESHEET
2456 QWeakPointer<QStyle> origStyle;
2460 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2461 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2462 // set when changing that attribute and passes the widget's CURRENT style.
2463 // therefore no need to do a reassignment.
2469 #ifndef QT_NO_STYLE_STYLESHEET
2470 origStyle = extra->style.data();
2472 extra->style = newStyle;
2476 if (q->windowType() != Qt::Desktop) {
2478 oldStyle->unpolish(q);
2481 macUpdateMetalAttribute();
2483 q->style()->polish(q);
2485 } else if (metalHack) {
2486 macUpdateMetalAttribute();
2492 for (int i = 0; i < children.size(); ++i) {
2493 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2495 c->d_func()->inheritStyle();
2499 #ifndef QT_NO_STYLE_STYLESHEET
2500 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2501 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2502 cssStyle->clearWidgetFont(q);
2507 QEvent e(QEvent::StyleChange);
2508 QApplication::sendEvent(q, &e);
2510 #ifndef QT_NO_STYLE_STYLESHEET
2511 // dereference the old stylesheet style
2512 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2517 // Inherits style from the current parent and propagates it as necessary
2518 void QWidgetPrivate::inheritStyle()
2520 #ifndef QT_NO_STYLE_STYLESHEET
2523 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2525 if (!q->styleSheet().isEmpty()) {
2531 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2532 QWidget *parent = q->parentWidget();
2533 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2534 // If we have stylesheet on app or parent has stylesheet style, we need
2535 // to be running a proxy
2536 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2537 QStyle *newStyle = parentStyle;
2538 if (q->testAttribute(Qt::WA_SetStyle))
2539 newStyle = new QStyleSheetStyle(origStyle);
2540 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2543 setStyle_helper(newStyle, true);
2547 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2548 // we just need our original style back
2549 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2552 // We could have inherited the proxy from our parent (which has a custom style)
2553 // In such a case we need to start following the application style (i.e revert
2554 // the propagation behavior of QStyleSheetStyle)
2555 if (!q->testAttribute(Qt::WA_SetStyle))
2558 setStyle_helper(origStyle, true);
2559 #endif // QT_NO_STYLE_STYLESHEET
2564 \fn bool QWidget::isWindow() const
2566 Returns true if the widget is an independent window, otherwise
2569 A window is a widget that isn't visually the child of any other
2570 widget and that usually has a frame and a
2571 \l{QWidget::setWindowTitle()}{window title}.
2573 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2574 It will then be grouped with its parent and deleted when the
2575 parent is deleted, minimized when the parent is minimized etc. If
2576 supported by the window manager, it will also have a common
2577 taskbar entry with its parent.
2579 QDialog and QMainWindow widgets are by default windows, even if a
2580 parent widget is specified in the constructor. This behavior is
2581 specified by the Qt::Window flag.
2583 \sa window(), isModal(), parentWidget()
2587 \property QWidget::modal
2588 \brief whether the widget is a modal widget
2590 This property only makes sense for windows. A modal widget
2591 prevents widgets in all other windows from getting any input.
2593 By default, this property is false.
2595 \sa isWindow(), windowModality, QDialog
2599 \property QWidget::windowModality
2600 \brief which windows are blocked by the modal widget
2603 This property only makes sense for windows. A modal widget
2604 prevents widgets in other windows from getting input. The value of
2605 this property controls which windows are blocked when the widget
2606 is visible. Changing this property while the window is visible has
2607 no effect; you must hide() the widget first, then show() it again.
2609 By default, this property is Qt::NonModal.
2611 \sa isWindow(), QWidget::modal, QDialog
2614 Qt::WindowModality QWidget::windowModality() const
2616 return static_cast<Qt::WindowModality>(data->window_modality);
2619 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2621 data->window_modality = windowModality;
2622 // setModal_sys() will be called by setAttribute()
2623 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2624 setAttribute(Qt::WA_SetWindowModality, true);
2628 \fn bool QWidget::underMouse() const
2630 Returns true if the widget is under the mouse cursor; otherwise
2633 This value is not updated properly during drag and drop
2636 \sa enterEvent(), leaveEvent()
2640 \property QWidget::minimized
2641 \brief whether this widget is minimized (iconified)
2643 This property is only relevant for windows.
2645 By default, this property is false.
2647 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2649 bool QWidget::isMinimized() const
2650 { return data->window_state & Qt::WindowMinimized; }
2653 Shows the widget minimized, as an icon.
2655 Calling this function only affects \l{isWindow()}{windows}.
2657 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2660 void QWidget::showMinimized()
2662 bool isMin = isMinimized();
2663 if (isMin && isVisible())
2669 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2674 \property QWidget::maximized
2675 \brief whether this widget is maximized
2677 This property is only relevant for windows.
2679 \note Due to limitations on some window systems, this does not always
2680 report the expected results (e.g., if the user on X11 maximizes the
2681 window via the window manager, Qt has no way of distinguishing this
2682 from any other resize). This is expected to improve as window manager
2685 By default, this property is false.
2687 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2689 bool QWidget::isMaximized() const
2690 { return data->window_state & Qt::WindowMaximized; }
2695 Returns the current window state. The window state is a OR'ed
2696 combination of Qt::WindowState: Qt::WindowMinimized,
2697 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2699 \sa Qt::WindowState setWindowState()
2701 Qt::WindowStates QWidget::windowState() const
2703 return Qt::WindowStates(data->window_state);
2708 The function sets the window state on child widgets similar to
2709 setWindowState(). The difference is that the window state changed
2710 event has the isOverride() flag set. It exists mainly to keep
2713 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2715 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2716 data->window_state = newstate;
2717 QApplication::sendEvent(this, &e);
2721 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2723 Sets the window state to \a windowState. The window state is a OR'ed
2724 combination of Qt::WindowState: Qt::WindowMinimized,
2725 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2727 If the window is not visible (i.e. isVisible() returns false), the
2728 window state will take effect when show() is called. For visible
2729 windows, the change is immediate. For example, to toggle between
2730 full-screen and normal mode, use the following code:
2732 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2734 In order to restore and activate a minimized window (while
2735 preserving its maximized and/or full-screen state), use the following:
2737 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2739 Calling this function will hide the widget. You must call show() to make
2740 the widget visible again.
2742 \note On some window systems Qt::WindowActive is not immediate, and may be
2743 ignored in certain cases.
2745 When the window state changes, the widget receives a changeEvent()
2746 of type QEvent::WindowStateChange.
2748 \sa Qt::WindowState windowState()
2752 \property QWidget::fullScreen
2753 \brief whether the widget is shown in full screen mode
2755 A widget in full screen mode occupies the whole screen area and does not
2756 display window decorations, such as a title bar.
2758 By default, this property is false.
2760 \sa windowState(), minimized, maximized
2762 bool QWidget::isFullScreen() const
2763 { return data->window_state & Qt::WindowFullScreen; }
2766 Shows the widget in full-screen mode.
2768 Calling this function only affects \l{isWindow()}{windows}.
2770 To return from full-screen mode, call showNormal().
2772 Full-screen mode works fine under Windows, but has certain
2773 problems under X. These problems are due to limitations of the
2774 ICCCM protocol that specifies the communication between X11
2775 clients and the window manager. ICCCM simply does not understand
2776 the concept of non-decorated full-screen windows. Therefore, the
2777 best we can do is to request a borderless window and place and
2778 resize it to fill the entire screen. Depending on the window
2779 manager, this may or may not work. The borderless window is
2780 requested using MOTIF hints, which are at least partially
2781 supported by virtually all modern window managers.
2783 An alternative would be to bypass the window manager entirely and
2784 create a window with the Qt::X11BypassWindowManagerHint flag. This
2785 has other severe problems though, like totally broken keyboard focus
2786 and very strange effects on desktop changes or when the user raises
2789 X11 window managers that follow modern post-ICCCM specifications
2790 support full-screen mode properly.
2792 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2794 void QWidget::showFullScreen()
2797 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2798 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2799 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2800 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2801 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2802 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2807 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2808 | Qt::WindowFullScreen);
2814 Shows the widget maximized.
2816 Calling this function only affects \l{isWindow()}{windows}.
2818 On X11, this function may not work properly with certain window
2819 managers. See the \l{Window Geometry} documentation for an explanation.
2821 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2823 void QWidget::showMaximized()
2827 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2828 | Qt::WindowMaximized);
2830 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2831 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2834 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2835 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2836 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2837 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2845 Restores the widget after it has been maximized or minimized.
2847 Calling this function only affects \l{isWindow()}{windows}.
2849 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2851 void QWidget::showNormal()
2855 setWindowState(windowState() & ~(Qt::WindowMinimized
2856 | Qt::WindowMaximized
2857 | Qt::WindowFullScreen));
2859 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2860 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2863 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2864 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2865 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2866 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2874 Returns true if this widget would become enabled if \a ancestor is
2875 enabled; otherwise returns false.
2879 This is the case if neither the widget itself nor every parent up
2880 to but excluding \a ancestor has been explicitly disabled.
2882 isEnabledTo(0) is equivalent to isEnabled().
2884 \sa setEnabled() enabled
2887 bool QWidget::isEnabledTo(const QWidget *ancestor) const
2889 const QWidget * w = this;
2890 while (!w->testAttribute(Qt::WA_ForceDisabled)
2892 && w->parentWidget()
2893 && w->parentWidget() != ancestor)
2894 w = w->parentWidget();
2895 return !w->testAttribute(Qt::WA_ForceDisabled);
2898 #ifndef QT_NO_ACTION
2900 Appends the action \a action to this widget's list of actions.
2902 All QWidgets have a list of \l{QAction}s, however they can be
2903 represented graphically in many different ways. The default use of
2904 the QAction list (as returned by actions()) is to create a context
2907 A QWidget should only have one of each action and adding an action
2908 it already has will not cause the same action to be in the widget twice.
2910 The ownership of \a action is not transferred to this QWidget.
2912 \sa removeAction(), insertAction(), actions(), QMenu
2914 void QWidget::addAction(QAction *action)
2916 insertAction(0, action);
2920 Appends the actions \a actions to this widget's list of actions.
2922 \sa removeAction(), QMenu, addAction()
2924 void QWidget::addActions(QList<QAction*> actions)
2926 for(int i = 0; i < actions.count(); i++)
2927 insertAction(0, actions.at(i));
2931 Inserts the action \a action to this widget's list of actions,
2932 before the action \a before. It appends the action if \a before is 0 or
2933 \a before is not a valid action for this widget.
2935 A QWidget should only have one of each action.
2937 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
2939 void QWidget::insertAction(QAction *before, QAction *action)
2942 qWarning("QWidget::insertAction: Attempt to insert null action");
2947 if(d->actions.contains(action))
2948 removeAction(action);
2950 int pos = d->actions.indexOf(before);
2953 pos = d->actions.size();
2955 d->actions.insert(pos, action);
2957 QActionPrivate *apriv = action->d_func();
2958 apriv->widgets.append(this);
2960 QActionEvent e(QEvent::ActionAdded, action, before);
2961 QApplication::sendEvent(this, &e);
2965 Inserts the actions \a actions to this widget's list of actions,
2966 before the action \a before. It appends the action if \a before is 0 or
2967 \a before is not a valid action for this widget.
2969 A QWidget can have at most one of each action.
2971 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
2973 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
2975 for(int i = 0; i < actions.count(); ++i)
2976 insertAction(before, actions.at(i));
2980 Removes the action \a action from this widget's list of actions.
2981 \sa insertAction(), actions(), insertAction()
2983 void QWidget::removeAction(QAction *action)
2990 QActionPrivate *apriv = action->d_func();
2991 apriv->widgets.removeAll(this);
2993 if (d->actions.removeAll(action)) {
2994 QActionEvent e(QEvent::ActionRemoved, action);
2995 QApplication::sendEvent(this, &e);
3000 Returns the (possibly empty) list of this widget's actions.
3002 \sa contextMenuPolicy, insertAction(), removeAction()
3004 QList<QAction*> QWidget::actions() const
3009 #endif // QT_NO_ACTION
3012 \fn bool QWidget::isEnabledToTLW() const
3015 This function is deprecated. It is equivalent to isEnabled()
3019 \property QWidget::enabled
3020 \brief whether the widget is enabled
3022 In general an enabled widget handles keyboard and mouse events; a disabled
3023 widget does not. An exception is made with \l{QAbstractButton}.
3025 Some widgets display themselves differently when they are
3026 disabled. For example a button might draw its label grayed out. If
3027 your widget needs to know when it becomes enabled or disabled, you
3028 can use the changeEvent() with type QEvent::EnabledChange.
3030 Disabling a widget implicitly disables all its children. Enabling
3031 respectively enables all child widgets unless they have been
3032 explicitly disabled.
3034 By default, this property is true.
3036 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3038 void QWidget::setEnabled(bool enable)
3041 setAttribute(Qt::WA_ForceDisabled, !enable);
3042 d->setEnabled_helper(enable);
3045 void QWidgetPrivate::setEnabled_helper(bool enable)
3049 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3050 return; // nothing we can do
3052 if (enable != q->testAttribute(Qt::WA_Disabled))
3053 return; // nothing to do
3055 q->setAttribute(Qt::WA_Disabled, !enable);
3056 updateSystemBackground();
3058 if (!enable && q->window()->focusWidget() == q) {
3059 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3060 if (!parentIsEnabled || !q->focusNextChild())
3064 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3065 for (int i = 0; i < children.size(); ++i) {
3066 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3067 if (w && !w->testAttribute(attribute))
3068 w->d_func()->setEnabled_helper(enable);
3070 #if defined(Q_WS_X11)
3071 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3072 // enforce the windows behavior of clearing the cursor on
3074 qt_x11_enforce_cursor(q);
3077 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3078 // enforce the windows behavior of clearing the cursor on
3080 qt_qpa_set_cursor(q, false);
3082 #if defined(Q_WS_MAC)
3083 setEnabled_helper_sys(enable);
3086 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3087 QWidget *focusWidget = effectiveFocusWidget();
3090 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3091 qApp->inputMethod()->update(Qt::ImEnabled);
3093 qApp->inputMethod()->reset();
3094 qApp->inputMethod()->update(Qt::ImEnabled);
3098 QEvent e(QEvent::EnabledChange);
3099 QApplication::sendEvent(q, &e);
3103 \property QWidget::acceptDrops
3104 \brief whether drop events are enabled for this widget
3106 Setting this property to true announces to the system that this
3107 widget \e may be able to accept drop events.
3109 If the widget is the desktop (windowType() == Qt::Desktop), this may
3110 fail if another application is using the desktop; you can call
3111 acceptDrops() to test if this occurs.
3113 \warning Do not modify this property in a drag and drop event handler.
3115 By default, this property is false.
3119 bool QWidget::acceptDrops() const
3121 return testAttribute(Qt::WA_AcceptDrops);
3124 void QWidget::setAcceptDrops(bool on)
3126 setAttribute(Qt::WA_AcceptDrops, on);
3132 Disables widget input events if \a disable is true; otherwise
3133 enables input events.
3135 See the \l enabled documentation for more information.
3137 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3139 void QWidget::setDisabled(bool disable)
3141 setEnabled(!disable);
3145 \property QWidget::frameGeometry
3146 \brief geometry of the widget relative to its parent including any
3149 See the \l{Window Geometry} documentation for an overview of geometry
3150 issues with windows.
3152 By default, this property contains a value that depends on the user's
3153 platform and screen geometry.
3155 \sa geometry() x() y() pos()
3157 QRect QWidget::frameGeometry() const
3160 if (isWindow() && ! (windowType() == Qt::Popup)) {
3161 QRect fs = d->frameStrut();
3162 return QRect(data->crect.x() - fs.left(),
3163 data->crect.y() - fs.top(),
3164 data->crect.width() + fs.left() + fs.right(),
3165 data->crect.height() + fs.top() + fs.bottom());
3171 \property QWidget::x
3173 \brief the x coordinate of the widget relative to its parent including
3176 See the \l{Window Geometry} documentation for an overview of geometry
3177 issues with windows.
3179 By default, this property has a value of 0.
3181 \sa frameGeometry, y, pos
3183 int QWidget::x() const
3186 if (isWindow() && ! (windowType() == Qt::Popup))
3187 return data->crect.x() - d->frameStrut().left();
3188 return data->crect.x();
3192 \property QWidget::y
3193 \brief the y coordinate of the widget relative to its parent and
3194 including any window frame
3196 See the \l{Window Geometry} documentation for an overview of geometry
3197 issues with windows.
3199 By default, this property has a value of 0.
3201 \sa frameGeometry, x, pos
3203 int QWidget::y() const
3206 if (isWindow() && ! (windowType() == Qt::Popup))
3207 return data->crect.y() - d->frameStrut().top();
3208 return data->crect.y();
3212 \property QWidget::pos
3213 \brief the position of the widget within its parent widget
3215 If the widget is a window, the position is that of the widget on
3216 the desktop, including its frame.
3218 When changing the position, the widget, if visible, receives a
3219 move event (moveEvent()) immediately. If the widget is not
3220 currently visible, it is guaranteed to receive an event before it
3223 By default, this property contains a position that refers to the
3226 \warning Calling move() or setGeometry() inside moveEvent() can
3227 lead to infinite recursion.
3229 See the \l{Window Geometry} documentation for an overview of geometry
3230 issues with windows.
3232 \sa frameGeometry, size x(), y()
3234 QPoint QWidget::pos() const
3237 if (isWindow() && ! (windowType() == Qt::Popup)) {
3238 QRect fs = d->frameStrut();
3239 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3241 return data->crect.topLeft();
3245 \property QWidget::geometry
3246 \brief the geometry of the widget relative to its parent and
3247 excluding the window frame
3249 When changing the geometry, the widget, if visible, receives a
3250 move event (moveEvent()) and/or a resize event (resizeEvent())
3251 immediately. If the widget is not currently visible, it is
3252 guaranteed to receive appropriate events before it is shown.
3254 The size component is adjusted if it lies outside the range
3255 defined by minimumSize() and maximumSize().
3257 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3258 can lead to infinite recursion.
3260 See the \l{Window Geometry} documentation for an overview of geometry
3261 issues with windows.
3263 By default, this property contains a value that depends on the user's
3264 platform and screen geometry.
3266 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3267 resizeEvent(), minimumSize(), maximumSize()
3271 \property QWidget::normalGeometry
3273 \brief the geometry of the widget as it will appear when shown as
3274 a normal (not maximized or full screen) top-level widget
3276 For child widgets this property always holds an empty rectangle.
3278 By default, this property contains an empty rectangle.
3280 \sa QWidget::windowState(), QWidget::geometry
3284 \property QWidget::size
3285 \brief the size of the widget excluding any window frame
3287 If the widget is visible when it is being resized, it receives a resize event
3288 (resizeEvent()) immediately. If the widget is not currently
3289 visible, it is guaranteed to receive an event before it is shown.
3291 The size is adjusted if it lies outside the range defined by
3292 minimumSize() and maximumSize().
3294 By default, this property contains a value that depends on the user's
3295 platform and screen geometry.
3297 \warning Calling resize() or setGeometry() inside resizeEvent() can
3298 lead to infinite recursion.
3300 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3301 appear on screen. This also applies to windows.
3303 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3307 \property QWidget::width
3308 \brief the width of the widget excluding any window frame
3310 See the \l{Window Geometry} documentation for an overview of geometry
3311 issues with windows.
3313 \note Do not use this function to find the width of a screen on
3314 a \l{QDesktopWidget}{multiple screen desktop}. Read
3315 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3317 By default, this property contains a value that depends on the user's
3318 platform and screen geometry.
3320 \sa geometry, height, size
3324 \property QWidget::height
3325 \brief the height of the widget excluding any window frame
3327 See the \l{Window Geometry} documentation for an overview of geometry
3328 issues with windows.
3330 \note Do not use this function to find the height of a screen
3331 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3332 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3334 By default, this property contains a value that depends on the user's
3335 platform and screen geometry.
3337 \sa geometry, width, size
3341 \property QWidget::rect
3342 \brief the internal geometry of the widget excluding any window
3345 The rect property equals QRect(0, 0, width(), height()).
3347 See the \l{Window Geometry} documentation for an overview of geometry
3348 issues with windows.
3350 By default, this property contains a value that depends on the user's
3351 platform and screen geometry.
3357 QRect QWidget::normalGeometry() const
3360 if (!d->extra || !d->extra->topextra)
3363 if (!isMaximized() && !isFullScreen())
3366 return d->topData()->normalGeometry;
3371 \property QWidget::childrenRect
3372 \brief the bounding rectangle of the widget's children
3374 Hidden children are excluded.
3376 By default, for a widget with no children, this property contains a
3377 rectangle with zero width and height located at the origin.
3379 \sa childrenRegion() geometry()
3382 QRect QWidget::childrenRect() const
3385 QRect r(0, 0, 0, 0);
3386 for (int i = 0; i < d->children.size(); ++i) {
3387 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3388 if (w && !w->isWindow() && !w->isHidden())
3395 \property QWidget::childrenRegion
3396 \brief the combined region occupied by the widget's children
3398 Hidden children are excluded.
3400 By default, for a widget with no children, this property contains an
3403 \sa childrenRect() geometry() mask()
3406 QRegion QWidget::childrenRegion() const
3410 for (int i = 0; i < d->children.size(); ++i) {
3411 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3412 if (w && !w->isWindow() && !w->isHidden()) {
3413 QRegion mask = w->mask();
3417 r |= mask.translated(w->pos());
3425 \property QWidget::minimumSize
3426 \brief the widget's minimum size
3428 The widget cannot be resized to a smaller size than the minimum
3429 widget size. The widget's size is forced to the minimum size if
3430 the current size is smaller.
3432 The minimum size set by this function will override the minimum size
3433 defined by QLayout. In order to unset the minimum size, use a
3434 value of \c{QSize(0, 0)}.
3436 By default, this property contains a size with zero width and height.
3438 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3441 QSize QWidget::minimumSize() const
3444 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3448 \property QWidget::maximumSize
3449 \brief the widget's maximum size in pixels
3451 The widget cannot be resized to a larger size than the maximum
3454 By default, this property contains a size in which both width and height
3455 have values of 16777215.
3457 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3460 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3463 QSize QWidget::maximumSize() const
3466 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3467 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3472 \property QWidget::minimumWidth
3473 \brief the widget's minimum width in pixels
3475 This property corresponds to the width held by the \l minimumSize property.
3477 By default, this property has a value of 0.
3479 \sa minimumSize, minimumHeight
3483 \property QWidget::minimumHeight
3484 \brief the widget's minimum height in pixels
3486 This property corresponds to the height held by the \l minimumSize property.
3488 By default, this property has a value of 0.
3490 \sa minimumSize, minimumWidth
3494 \property QWidget::maximumWidth
3495 \brief the widget's maximum width in pixels
3497 This property corresponds to the width held by the \l maximumSize property.
3499 By default, this property contains a value of 16777215.
3501 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3504 \sa maximumSize, maximumHeight
3508 \property QWidget::maximumHeight
3509 \brief the widget's maximum height in pixels
3511 This property corresponds to the height held by the \l maximumSize property.
3513 By default, this property contains a value of 16777215.
3515 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3518 \sa maximumSize, maximumWidth
3522 \property QWidget::sizeIncrement
3523 \brief the size increment of the widget
3525 When the user resizes the window, the size will move in steps of
3526 sizeIncrement().width() pixels horizontally and
3527 sizeIncrement.height() pixels vertically, with baseSize() as the
3528 basis. Preferred widget sizes are for non-negative integers \e i
3530 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3532 Note that while you can set the size increment for all widgets, it
3533 only affects windows.
3535 By default, this property contains a size with zero width and height.
3537 \warning The size increment has no effect under Windows, and may
3538 be disregarded by the window manager on X11.
3540 \sa size, minimumSize, maximumSize
3542 QSize QWidget::sizeIncrement() const
3545 return (d->extra && d->extra->topextra)
3546 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3551 \property QWidget::baseSize
3552 \brief the base size of the widget
3554 The base size is used to calculate a proper widget size if the
3555 widget defines sizeIncrement().
3557 By default, for a newly-created widget, this property contains a size with
3558 zero width and height.
3560 \sa setSizeIncrement()
3563 QSize QWidget::baseSize() const
3566 return (d->extra != 0 && d->extra->topextra != 0)
3567 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3571 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3575 int mw = minw, mh = minh;
3576 if (mw == QWIDGETSIZE_MAX)
3578 if (mh == QWIDGETSIZE_MAX)
3580 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3581 qWarning("QWidget::setMinimumSize: (%s/%s) "
3582 "The largest allowed size is (%d,%d)",
3583 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3585 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3586 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3588 if (minw < 0 || minh < 0) {
3589 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3591 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3592 minw = mw = qMax(minw, 0);
3593 minh = mh = qMax(minh, 0);
3596 if (extra->minw == mw && extra->minh == mh)
3600 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3607 This function corresponds to setMinimumSize(QSize(minw, minh)).
3608 Sets the minimum width to \a minw and the minimum height to \a
3612 void QWidget::setMinimumSize(int minw, int minh)
3615 if (!d->setMinimumSize_helper(minw, minh))
3619 d->setConstraints_sys();
3620 if (minw > width() || minh > height()) {
3621 bool resized = testAttribute(Qt::WA_Resized);
3622 bool maximized = isMaximized();
3623 resize(qMax(minw,width()), qMax(minh,height()));
3624 setAttribute(Qt::WA_Resized, resized); //not a user resize
3626 data->window_state = data->window_state | Qt::WindowMaximized;
3628 #ifndef QT_NO_GRAPHICSVIEW
3630 if (d->extra->proxyWidget)
3631 d->extra->proxyWidget->setMinimumSize(minw, minh);
3634 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3637 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3640 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3641 qWarning("QWidget::setMaximumSize: (%s/%s) "
3642 "The largest allowed size is (%d,%d)",
3643 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3645 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3646 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3648 if (maxw < 0 || maxh < 0) {
3649 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3651 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3652 maxw = qMax(maxw, 0);
3653 maxh = qMax(maxh, 0);
3656 if (extra->maxw == maxw && extra->maxh == maxh)
3660 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3661 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3668 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3669 maxh)). Sets the maximum width to \a maxw and the maximum height
3672 void QWidget::setMaximumSize(int maxw, int maxh)
3675 if (!d->setMaximumSize_helper(maxw, maxh))
3679 d->setConstraints_sys();
3680 if (maxw < width() || maxh < height()) {
3681 bool resized = testAttribute(Qt::WA_Resized);
3682 resize(qMin(maxw,width()), qMin(maxh,height()));
3683 setAttribute(Qt::WA_Resized, resized); //not a user resize
3686 #ifndef QT_NO_GRAPHICSVIEW
3688 if (d->extra->proxyWidget)
3689 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3693 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3699 Sets the x (width) size increment to \a w and the y (height) size
3702 void QWidget::setSizeIncrement(int w, int h)
3706 QTLWExtra* x = d->topData();
3707 if (x->incw == w && x->inch == h)
3712 d->setConstraints_sys();
3718 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3719 the widgets base size to width \a basew and height \a baseh.
3721 void QWidget::setBaseSize(int basew, int baseh)
3725 QTLWExtra* x = d->topData();
3726 if (x->basew == basew && x->baseh == baseh)
3731 d->setConstraints_sys();
3735 Sets both the minimum and maximum sizes of the widget to \a s,
3736 thereby preventing it from ever growing or shrinking.
3738 This will override the default size constraints set by QLayout.
3740 To remove constraints, set the size to QWIDGETSIZE_MAX.
3742 Alternatively, if you want the widget to have a
3743 fixed size based on its contents, you can call
3744 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3746 \sa maximumSize, minimumSize
3749 void QWidget::setFixedSize(const QSize & s)
3751 setFixedSize(s.width(), s.height());
3756 \fn void QWidget::setFixedSize(int w, int h)
3759 Sets the width of the widget to \a w and the height to \a h.
3762 void QWidget::setFixedSize(int w, int h)
3765 bool minSizeSet = d->setMinimumSize_helper(w, h);
3766 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3767 if (!minSizeSet && !maxSizeSet)
3771 d->setConstraints_sys();
3773 d->updateGeometry_helper(true);
3775 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3779 void QWidget::setMinimumWidth(int w)
3783 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3784 setMinimumSize(w, minimumSize().height());
3785 d->extra->explicitMinSize = expl;
3788 void QWidget::setMinimumHeight(int h)
3792 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3793 setMinimumSize(minimumSize().width(), h);
3794 d->extra->explicitMinSize = expl;
3797 void QWidget::setMaximumWidth(int w)
3801 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3802 setMaximumSize(w, maximumSize().height());
3803 d->extra->explicitMaxSize = expl;
3806 void QWidget::setMaximumHeight(int h)
3810 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3811 setMaximumSize(maximumSize().width(), h);
3812 d->extra->explicitMaxSize = expl;
3816 Sets both the minimum and maximum width of the widget to \a w
3817 without changing the heights. Provided for convenience.
3819 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3822 void QWidget::setFixedWidth(int w)
3826 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3827 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3828 setMinimumSize(w, minimumSize().height());
3829 setMaximumSize(w, maximumSize().height());
3830 d->extra->explicitMinSize = explMin;
3831 d->extra->explicitMaxSize = explMax;
3836 Sets both the minimum and maximum heights of the widget to \a h
3837 without changing the widths. Provided for convenience.
3839 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3842 void QWidget::setFixedHeight(int h)
3846 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3847 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3848 setMinimumSize(minimumSize().width(), h);
3849 setMaximumSize(maximumSize().width(), h);
3850 d->extra->explicitMinSize = explMin;
3851 d->extra->explicitMaxSize = explMax;
3856 Translates the widget coordinate \a pos to the coordinate system
3857 of \a parent. The \a parent must not be 0 and must be a parent
3858 of the calling widget.
3860 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
3863 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
3867 const QWidget * w = this;
3868 while (w != parent) {
3869 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
3870 "parent must be in parent hierarchy");
3871 p = w->mapToParent(p);
3872 w = w->parentWidget();
3880 Translates the widget coordinate \a pos from the coordinate system
3881 of \a parent to this widget's coordinate system. The \a parent
3882 must not be 0 and must be a parent of the calling widget.
3884 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
3887 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
3891 const QWidget * w = this;
3892 while (w != parent) {
3893 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
3894 "parent must be in parent hierarchy");
3896 p = w->mapFromParent(p);
3897 w = w->parentWidget();
3905 Translates the widget coordinate \a pos to a coordinate in the
3908 Same as mapToGlobal() if the widget has no parent.
3910 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
3913 QPoint QWidget::mapToParent(const QPoint &pos) const
3915 return pos + data->crect.topLeft();
3919 Translates the parent widget coordinate \a pos to widget
3922 Same as mapFromGlobal() if the widget has no parent.
3924 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
3927 QPoint QWidget::mapFromParent(const QPoint &pos) const
3929 return pos - data->crect.topLeft();
3934 Returns the window for this widget, i.e. the next ancestor widget
3935 that has (or could have) a window-system frame.
3937 If the widget is a window, the widget itself is returned.
3939 Typical usage is changing the window title:
3941 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
3946 QWidget *QWidget::window() const
3948 QWidget *w = (QWidget *)this;
3949 QWidget *p = w->parentWidget();
3950 while (!w->isWindow() && p) {
3952 p = p->parentWidget();
3960 Returns the native parent for this widget, i.e. the next ancestor widget
3961 that has a system identifier, or 0 if it does not have any native parent.
3963 \sa effectiveWinId()
3965 QWidget *QWidget::nativeParentWidget() const
3967 QWidget *parent = parentWidget();
3968 while (parent && !parent->internalWinId())
3969 parent = parent->parentWidget();
3973 /*! \fn QWidget *QWidget::topLevelWidget() const
3976 Use window() instead.
3982 Returns the background role of the widget.
3984 The background role defines the brush from the widget's \l palette that
3985 is used to render the background.
3987 If no explicit background role is set, the widget inherts its parent
3988 widget's background role.
3990 \sa setBackgroundRole(), foregroundRole()
3992 QPalette::ColorRole QWidget::backgroundRole() const
3995 const QWidget *w = this;
3997 QPalette::ColorRole role = w->d_func()->bg_role;
3998 if (role != QPalette::NoRole)
4000 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4002 w = w->parentWidget();
4004 return QPalette::Window;
4008 Sets the background role of the widget to \a role.
4010 The background role defines the brush from the widget's \l palette that
4011 is used to render the background.
4013 If \a role is QPalette::NoRole, then the widget inherits its
4014 parent's background role.
4016 Note that styles are free to choose any color from the palette.
4017 You can modify the palette or set a style sheet if you don't
4018 achieve the result you want with setBackgroundRole().
4020 \sa backgroundRole(), foregroundRole()
4023 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4027 d->updateSystemBackground();
4028 d->propagatePaletteChange();
4029 d->updateIsOpaque();
4033 Returns the foreground role.
4035 The foreground role defines the color from the widget's \l palette that
4036 is used to draw the foreground.
4038 If no explicit foreground role is set, the function returns a role
4039 that contrasts with the background role.
4041 \sa setForegroundRole(), backgroundRole()
4043 QPalette::ColorRole QWidget::foregroundRole() const
4046 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4047 if (rl != QPalette::NoRole)
4049 QPalette::ColorRole role = QPalette::WindowText;
4050 switch (backgroundRole()) {
4051 case QPalette::Button:
4052 role = QPalette::ButtonText;
4054 case QPalette::Base:
4055 role = QPalette::Text;
4057 case QPalette::Dark:
4058 case QPalette::Shadow:
4059 role = QPalette::Light;
4061 case QPalette::Highlight:
4062 role = QPalette::HighlightedText;
4064 case QPalette::ToolTipBase:
4065 role = QPalette::ToolTipText;
4074 Sets the foreground role of the widget to \a role.
4076 The foreground role defines the color from the widget's \l palette that
4077 is used to draw the foreground.
4079 If \a role is QPalette::NoRole, the widget uses a foreground role
4080 that contrasts with the background role.
4082 Note that styles are free to choose any color from the palette.
4083 You can modify the palette or set a style sheet if you don't
4084 achieve the result you want with setForegroundRole().
4086 \sa foregroundRole(), backgroundRole()
4088 void QWidget::setForegroundRole(QPalette::ColorRole role)
4092 d->updateSystemBackground();
4093 d->propagatePaletteChange();
4097 \property QWidget::palette
4098 \brief the widget's palette
4100 This property describes the widget's palette. The palette is used by the
4101 widget's style when rendering standard components, and is available as a
4102 means to ensure that custom widgets can maintain consistency with the
4103 native platform's look and feel. It's common that different platforms, or
4104 different styles, have different palettes.
4106 When you assign a new palette to a widget, the color roles from this
4107 palette are combined with the widget's default palette to form the
4108 widget's final palette. The palette entry for the widget's background role
4109 is used to fill the widget's background (see QWidget::autoFillBackground),
4110 and the foreground role initializes QPainter's pen.
4112 The default depends on the system environment. QApplication maintains a
4113 system/theme palette which serves as a default for all widgets. There may
4114 also be special palette defaults for certain types of widgets (e.g., on
4115 Windows XP and Vista, all classes that derive from QMenuBar have a special
4116 default palette). You can also define default palettes for widgets
4117 yourself by passing a custom palette and the name of a widget to
4118 QApplication::setPalette(). Finally, the style always has the option of
4119 polishing the palette as it's assigned (see QStyle::polish()).
4121 QWidget propagates explicit palette roles from parent to child. If you
4122 assign a brush or color to a specific role on a palette and assign that
4123 palette to a widget, that role will propagate to all the widget's
4124 children, overriding any system defaults for that role. Note that palettes
4125 by default don't propagate to windows (see isWindow()) unless the
4126 Qt::WA_WindowPropagation attribute is enabled.
4128 QWidget's palette propagation is similar to its font propagation.
4130 The current style, which is used to render the content of all standard Qt
4131 widgets, is free to choose colors and brushes from the widget palette, or
4132 in some cases, to ignore the palette (partially, or completely). In
4133 particular, certain styles like GTK style, Mac style, Windows XP, and
4134 Vista style, depend on third party APIs to render the content of widgets,
4135 and these styles typically do not follow the palette. Because of this,
4136 assigning roles to a widget's palette is not guaranteed to change the
4137 appearance of the widget. Instead, you may choose to apply a \l
4138 styleSheet. You can refer to our Knowledge Base article
4139 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4142 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4143 When using style sheets, the palette of a widget can be customized using
4144 the "color", "background-color", "selection-color",
4145 "selection-background-color" and "alternate-background-color".
4147 \sa QApplication::palette(), QWidget::font()
4149 const QPalette &QWidget::palette() const
4152 data->pal.setCurrentColorGroup(QPalette::Disabled);
4153 } else if ((!isVisible() || isActiveWindow())
4154 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
4155 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4158 data->pal.setCurrentColorGroup(QPalette::Active);
4161 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4162 if (qt_mac_can_clickThrough(this))
4163 data->pal.setCurrentColorGroup(QPalette::Active);
4166 data->pal.setCurrentColorGroup(QPalette::Inactive);
4171 void QWidget::setPalette(const QPalette &palette)
4174 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4176 // Determine which palette is inherited from this widget's ancestors and
4177 // QApplication::palette, resolve this against \a palette (attributes from
4178 // the inherited palette are copied over this widget's palette). Then
4179 // propagate this palette to this widget's children.
4180 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4181 QPalette resolvedPalette = palette.resolve(naturalPalette);
4182 d->setPalette_helper(resolvedPalette);
4188 Returns the palette that the widget \a w inherits from its ancestors and
4189 QApplication::palette. \a inheritedMask is the combination of the widget's
4190 ancestors palette request masks (i.e., which attributes from the parent
4191 widget's palette are implicitly imposed on this widget by the user). Note
4192 that this font does not take into account the palette set on \a w itself.
4194 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4197 QPalette naturalPalette = QApplication::palette(q);
4198 if (!q->testAttribute(Qt::WA_StyleSheet)
4199 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4200 #ifndef QT_NO_GRAPHICSVIEW
4201 || (extra && extra->proxyWidget)
4202 #endif //QT_NO_GRAPHICSVIEW
4204 if (QWidget *p = q->parentWidget()) {
4205 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4206 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4207 QPalette inheritedPalette = p->palette();
4208 inheritedPalette.resolve(inheritedMask);
4209 naturalPalette = inheritedPalette.resolve(naturalPalette);
4211 naturalPalette = p->palette();
4215 #ifndef QT_NO_GRAPHICSVIEW
4216 else if (extra && extra->proxyWidget) {
4217 QPalette inheritedPalette = extra->proxyWidget->palette();
4218 inheritedPalette.resolve(inheritedMask);
4219 naturalPalette = inheritedPalette.resolve(naturalPalette);
4221 #endif //QT_NO_GRAPHICSVIEW
4223 naturalPalette.resolve(0);
4224 return naturalPalette;
4229 Determine which palette is inherited from this widget's ancestors and
4230 QApplication::palette, resolve this against this widget's palette
4231 (attributes from the inherited palette are copied over this widget's
4232 palette). Then propagate this palette to this widget's children.
4234 void QWidgetPrivate::resolvePalette()
4236 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4237 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4238 setPalette_helper(resolvedPalette);
4241 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4244 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4247 updateSystemBackground();
4248 propagatePaletteChange();
4255 \property QWidget::font
4256 \brief the font currently set for the widget
4258 This property describes the widget's requested font. The font is used by
4259 the widget's style when rendering standard components, and is available as
4260 a means to ensure that custom widgets can maintain consistency with the
4261 native platform's look and feel. It's common that different platforms, or
4262 different styles, define different fonts for an application.
4264 When you assign a new font to a widget, the properties from this font are
4265 combined with the widget's default font to form the widget's final
4266 font. You can call fontInfo() to get a copy of the widget's final
4267 font. The final font is also used to initialize QPainter's font.
4269 The default depends on the system environment. QApplication maintains a
4270 system/theme font which serves as a default for all widgets. There may
4271 also be special font defaults for certain types of widgets. You can also
4272 define default fonts for widgets yourself by passing a custom font and the
4273 name of a widget to QApplication::setFont(). Finally, the font is matched
4274 against Qt's font database to find the best match.
4276 QWidget propagates explicit font properties from parent to child. If you
4277 change a specific property on a font and assign that font to a widget,
4278 that property will propagate to all the widget's children, overriding any
4279 system defaults for that property. Note that fonts by default don't
4280 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4281 attribute is enabled.
4283 QWidget's font propagation is similar to its palette propagation.
4285 The current style, which is used to render the content of all standard Qt
4286 widgets, is free to choose to use the widget font, or in some cases, to
4287 ignore it (partially, or completely). In particular, certain styles like
4288 GTK style, Mac style, Windows XP, and Vista style, apply special
4289 modifications to the widget font to match the platform's native look and
4290 feel. Because of this, assigning properties to a widget's font is not
4291 guaranteed to change the appearance of the widget. Instead, you may choose
4292 to apply a \l styleSheet.
4294 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4295 style sheets will take precedence if the settings conflict.
4297 \sa fontInfo(), fontMetrics()
4300 void QWidget::setFont(const QFont &font)
4304 #ifndef QT_NO_STYLE_STYLESHEET
4305 const QStyleSheetStyle* style;
4306 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4307 style->saveWidgetFont(this, font);
4311 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4313 // Determine which font is inherited from this widget's ancestors and
4314 // QApplication::font, resolve this against \a font (attributes from the
4315 // inherited font are copied over). Then propagate this font to this
4316 // widget's children.
4317 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4318 QFont resolvedFont = font.resolve(naturalFont);
4319 d->setFont_helper(resolvedFont);
4325 Returns the font that the widget \a w inherits from its ancestors and
4326 QApplication::font. \a inheritedMask is the combination of the widget's
4327 ancestors font request masks (i.e., which attributes from the parent
4328 widget's font are implicitly imposed on this widget by the user). Note
4329 that this font does not take into account the font set on \a w itself.
4331 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4332 is applied, fonts are not propagated anymore
4334 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4337 QFont naturalFont = QApplication::font(q);
4338 if (!q->testAttribute(Qt::WA_StyleSheet)
4339 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4340 #ifndef QT_NO_GRAPHICSVIEW
4341 || (extra && extra->proxyWidget)
4342 #endif //QT_NO_GRAPHICSVIEW
4344 if (QWidget *p = q->parentWidget()) {
4345 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4346 if (!naturalFont.isCopyOf(QApplication::font())) {
4347 QFont inheritedFont = p->font();
4348 inheritedFont.resolve(inheritedMask);
4349 naturalFont = inheritedFont.resolve(naturalFont);
4351 naturalFont = p->font();
4355 #ifndef QT_NO_GRAPHICSVIEW
4356 else if (extra && extra->proxyWidget) {
4357 QFont inheritedFont = extra->proxyWidget->font();
4358 inheritedFont.resolve(inheritedMask);
4359 naturalFont = inheritedFont.resolve(naturalFont);
4361 #endif //QT_NO_GRAPHICSVIEW
4363 naturalFont.resolve(0);
4370 Determine which font is implicitly imposed on this widget by its ancestors
4371 and QApplication::font, resolve this against its own font (attributes from
4372 the implicit font are copied over). Then propagate this font to this
4375 void QWidgetPrivate::resolveFont()
4377 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4378 QFont resolvedFont = data.fnt.resolve(naturalFont);
4379 setFont_helper(resolvedFont);
4385 Assign \a font to this widget, and propagate it to all children, except
4386 style sheet widgets (handled differently) and windows that don't enable
4387 window propagation. \a implicitMask is the union of all ancestor widgets'
4388 font request masks, and determines which attributes from this widget's
4389 font should propagate.
4391 void QWidgetPrivate::updateFont(const QFont &font)
4394 #ifndef QT_NO_STYLE_STYLESHEET
4395 const QStyleSheetStyle* cssStyle;
4396 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4399 data.fnt = QFont(font, q);
4400 #if defined(Q_WS_X11)
4401 // make sure the font set on this widget is associated with the correct screen
4402 data.fnt.x11SetScreen(xinfo.screen());
4404 // Combine new mask with natural mask and propagate to children.
4405 #ifndef QT_NO_GRAPHICSVIEW
4406 if (!q->parentWidget() && extra && extra->proxyWidget) {
4407 QGraphicsProxyWidget *p = extra->proxyWidget;
4408 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4410 #endif //QT_NO_GRAPHICSVIEW
4411 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4412 inheritedFontResolveMask = 0;
4414 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4416 for (int i = 0; i < children.size(); ++i) {
4417 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4420 #ifndef QT_NO_STYLE_STYLESHEET
4421 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4422 // Style sheets follow a different font propagation scheme.
4424 cssStyle->updateStyleSheetFont(w);
4426 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4427 // Propagate font changes.
4428 QWidgetPrivate *wd = w->d_func();
4429 wd->inheritedFontResolveMask = newMask;
4435 #ifndef QT_NO_STYLE_STYLESHEET
4437 cssStyle->updateStyleSheetFont(q);
4441 QEvent e(QEvent::FontChange);
4442 QApplication::sendEvent(q, &e);
4445 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4449 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4451 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4452 if (!children.isEmpty()) {
4453 for (int i = 0; i < children.size(); ++i) {
4454 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4455 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4456 w->d_func()->setLayoutDirection_helper(direction);
4459 QEvent e(QEvent::LayoutDirectionChange);
4460 QApplication::sendEvent(q, &e);
4463 void QWidgetPrivate::resolveLayoutDirection()
4466 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4467 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4471 \property QWidget::layoutDirection
4473 \brief the layout direction for this widget
4475 By default, this property is set to Qt::LeftToRight.
4477 When the layout direction is set on a widget, it will propagate to
4478 the widget's children, but not to a child that is a window and not
4479 to a child for which setLayoutDirection() has been explicitly
4480 called. Also, child widgets added \e after setLayoutDirection()
4481 has been called for the parent do not inherit the parent's layout
4484 This method no longer affects text layout direction since Qt 4.7.
4486 \sa QApplication::layoutDirection
4488 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4492 if (direction == Qt::LayoutDirectionAuto) {
4493 unsetLayoutDirection();
4497 setAttribute(Qt::WA_SetLayoutDirection);
4498 d->setLayoutDirection_helper(direction);
4501 Qt::LayoutDirection QWidget::layoutDirection() const
4503 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4506 void QWidget::unsetLayoutDirection()
4509 setAttribute(Qt::WA_SetLayoutDirection, false);
4510 d->resolveLayoutDirection();
4514 \fn QFontMetrics QWidget::fontMetrics() const
4516 Returns the font metrics for the widget's current font.
4517 Equivalent to QFontMetrics(widget->font()).
4519 \sa font(), fontInfo(), setFont()
4523 \fn QFontInfo QWidget::fontInfo() const
4525 Returns the font info for the widget's current font.
4526 Equivalent to QFontInto(widget->font()).
4528 \sa font(), fontMetrics(), setFont()
4533 \property QWidget::cursor
4534 \brief the cursor shape for this widget
4536 The mouse cursor will assume this shape when it's over this
4537 widget. See the \link Qt::CursorShape list of predefined cursor
4538 objects\endlink for a range of useful shapes.
4540 An editor widget might use an I-beam cursor:
4541 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4543 If no cursor has been set, or after a call to unsetCursor(), the
4544 parent's cursor is used.
4546 By default, this property contains a cursor with the Qt::ArrowCursor
4549 Some underlying window implementations will reset the cursor if it
4550 leaves a widget even if the mouse is grabbed. If you want to have
4551 a cursor set for all widgets, even when outside the window, consider
4552 QApplication::setOverrideCursor().
4554 \sa QApplication::setOverrideCursor()
4557 #ifndef QT_NO_CURSOR
4558 QCursor QWidget::cursor() const
4561 if (testAttribute(Qt::WA_SetCursor))
4562 return (d->extra && d->extra->curs)
4564 : QCursor(Qt::ArrowCursor);
4565 if (isWindow() || !parentWidget())
4566 return QCursor(Qt::ArrowCursor);
4567 return parentWidget()->cursor();
4570 void QWidget::setCursor(const QCursor &cursor)
4573 // On Mac we must set the cursor even if it is the ArrowCursor.
4574 #if !defined(Q_WS_MAC)
4575 if (cursor.shape() != Qt::ArrowCursor
4576 || (d->extra && d->extra->curs))
4580 QCursor *newCursor = new QCursor(cursor);
4581 delete d->extra->curs;
4582 d->extra->curs = newCursor;
4584 setAttribute(Qt::WA_SetCursor);
4585 d->setCursor_sys(cursor);
4587 QEvent event(QEvent::CursorChange);
4588 QApplication::sendEvent(this, &event);
4591 void QWidget::unsetCursor()
4595 delete d->extra->curs;
4599 setAttribute(Qt::WA_SetCursor, false);
4600 d->unsetCursor_sys();
4602 QEvent event(QEvent::CursorChange);
4603 QApplication::sendEvent(this, &event);
4609 \enum QWidget::RenderFlag
4611 This enum describes how to render the widget when calling QWidget::render().
4613 \value DrawWindowBackground If you enable this option, the widget's background
4614 is rendered into the target even if autoFillBackground is not set. By default,
4615 this option is enabled.
4617 \value DrawChildren If you enable this option, the widget's children
4618 are rendered recursively into the target. By default, this option is enabled.
4620 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4621 is ignored when rendering into the target. By default, this option is disabled.
4629 Renders the \a sourceRegion of this widget into the \a target
4630 using \a renderFlags to determine how to render. Rendering
4631 starts at \a targetOffset in the \a target. For example:
4633 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4635 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4636 the region, i.e. the entire widget.
4638 Ensure that you call QPainter::end() for the \a target device's
4639 active painter (if any) before rendering. For example:
4641 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4643 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4644 or QGLWidget::renderPixmap() instead.
4646 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4647 const QRegion &sourceRegion, RenderFlags renderFlags)
4649 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4655 Renders the widget into the \a painter's QPainter::device().
4657 Transformations and settings applied to the \a painter will be used
4660 \note The \a painter must be active. On Mac OS X the widget will be
4661 rendered into a QPixmap and then drawn by the \a painter.
4663 \sa QPainter::device()
4665 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4666 const QRegion &sourceRegion, RenderFlags renderFlags)
4669 qWarning("QWidget::render: Null pointer to painter");
4673 if (!painter->isActive()) {
4674 qWarning("QWidget::render: Cannot render with an inactive painter");
4678 const qreal opacity = painter->opacity();
4679 if (qFuzzyIsNull(opacity))
4680 return; // Fully transparent.
4683 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4684 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4686 if (toBePainted.isEmpty())
4691 d->extra->inRenderWithPainter = true;
4694 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4696 QPaintEngine *engine = painter->paintEngine();
4698 QPaintEnginePrivate *enginePriv = engine->d_func();
4699 Q_ASSERT(enginePriv);
4700 QPaintDevice *target = engine->paintDevice();
4703 // Render via a pixmap when dealing with non-opaque painters or printers.
4704 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4705 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4706 d->extra->inRenderWithPainter = false;
4710 // Set new shared painter.
4711 QPainter *oldPainter = d->sharedPainter();
4712 d->setSharedPainter(painter);
4714 // Save current system clip, viewport and transform,
4715 const QTransform oldTransform = enginePriv->systemTransform;
4716 const QRegion oldSystemClip = enginePriv->systemClip;
4717 const QRegion oldSystemViewport = enginePriv->systemViewport;
4719 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4720 if (painter->hasClipping()) {
4721 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4722 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4724 enginePriv->setSystemViewport(oldSystemClip);
4727 render(target, targetOffset, toBePainted, renderFlags);
4729 // Restore system clip, viewport and transform.
4730 enginePriv->systemClip = oldSystemClip;
4731 enginePriv->setSystemViewport(oldSystemViewport);
4732 enginePriv->setSystemTransform(oldTransform);
4734 // Restore shared painter.
4735 d->setSharedPainter(oldPainter);
4738 d->extra->inRenderWithPainter = false;
4741 static void sendResizeEvents(QWidget *target)
4743 QResizeEvent e(target->size(), QSize());
4744 QApplication::sendEvent(target, &e);
4746 const QObjectList children = target->children();
4747 for (int i = 0; i < children.size(); ++i) {
4748 QWidget *child = static_cast<QWidget*>(children.at(i));
4749 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4750 sendResizeEvents(child);
4757 Renders the widget into a pixmap restricted by the
4758 given \a rectangle. If the \a widget has any children, then
4759 they are also painted in the appropriate positions.
4761 If no rectangle is specified (the default) the entire widget is
4764 Replacement for Qt 4's QPixmap::grabWidget().
4766 \sa render(), QPixmap
4769 /* INVOKABLE since used by QPixmap::grabWidget(). */
4770 QPixmap QWidget::grab(const QRect &rectangle)
4773 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4774 sendResizeEvents(this);
4780 r.setWidth(width() - rectangle.x());
4782 r.setHeight(height() - rectangle.y());
4784 if (!r.intersects(rect()))
4787 QPixmap res(r.size());
4789 res.fill(Qt::transparent);
4790 render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
4791 | QWidget::DrawChildren | QWidget::IgnoreMask);
4796 \brief The graphicsEffect function returns a pointer to the
4797 widget's graphics effect.
4799 If the widget has no graphics effect, 0 is returned.
4803 \sa setGraphicsEffect()
4805 #ifndef QT_NO_GRAPHICSEFFECT
4806 QGraphicsEffect *QWidget::graphicsEffect() const
4809 return d->graphicsEffect;
4811 #endif //QT_NO_GRAPHICSEFFECT
4815 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4817 Sets \a effect as the widget's effect. If there already is an effect installed
4818 on this widget, QWidget will delete the existing effect before installing
4821 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4822 the effect from the widget and install it on this widget.
4824 QWidget takes ownership of \a effect.
4826 \note This function will apply the effect on itself and all its children.
4830 \sa graphicsEffect()
4832 #ifndef QT_NO_GRAPHICSEFFECT
4833 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4836 if (d->graphicsEffect == effect)
4839 if (d->graphicsEffect) {
4840 d->invalidateBuffer(rect());
4841 delete d->graphicsEffect;
4842 d->graphicsEffect = 0;
4847 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4848 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4849 d->graphicsEffect = effect;
4850 effect->d_func()->setGraphicsEffectSource(source);
4854 d->updateIsOpaque();
4856 #endif //QT_NO_GRAPHICSEFFECT
4858 bool QWidgetPrivate::isAboutToShow() const
4867 // The widget will be shown if any of its ancestors are about to show.
4868 QWidget *parent = q->parentWidget();
4869 return parent ? parent->d_func()->isAboutToShow() : false;
4872 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
4875 const bool isVisible = q->isVisible();
4877 // Make sure the widget is laid out correctly.
4878 if (!isVisible && !isAboutToShow()) {
4879 QWidget *topLevel = q->window();
4880 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4881 topLevel->ensurePolished();
4883 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4884 // they're not explicitly hidden.
4885 QWidget *widget = q;
4886 QWidgetList hiddenWidgets;
4888 if (widget->isHidden()) {
4889 widget->setAttribute(Qt::WA_WState_Hidden, false);
4890 hiddenWidgets.append(widget);
4891 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4892 widget->d_func()->updateGeometry_helper(true);
4894 widget = widget->parentWidget();
4897 // Activate top-level layout.
4898 if (topLevel->d_func()->layout)
4899 topLevel->d_func()->layout->activate();
4901 // Adjust size if necessary.
4902 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4903 if (topLevelExtra && !topLevelExtra->sizeAdjusted
4904 && !topLevel->testAttribute(Qt::WA_Resized)) {
4905 topLevel->adjustSize();
4906 topLevel->setAttribute(Qt::WA_Resized, false);
4909 // Activate child layouts.
4910 topLevel->d_func()->activateChildLayoutsRecursively();
4912 // We're not cheating with WA_WState_Hidden anymore.
4913 for (int i = 0; i < hiddenWidgets.size(); ++i) {
4914 QWidget *widget = hiddenWidgets.at(i);
4915 widget->setAttribute(Qt::WA_WState_Hidden);
4916 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4917 widget->parentWidget()->d_func()->layout->invalidate();
4919 } else if (isVisible) {
4920 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
4923 // Calculate the region to be painted.
4924 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
4925 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
4926 toBePainted &= extra->mask;
4930 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
4931 QWidget::RenderFlags renderFlags)
4934 Q_ASSERT(!toBePainted.isEmpty());
4938 const QTransform originalTransform = painter->worldTransform();
4939 const bool useDeviceCoordinates = originalTransform.isScaling();
4940 if (!useDeviceCoordinates) {
4942 // Render via a pixmap.
4943 const QRect rect = toBePainted.boundingRect();
4944 const QSize size = rect.size();
4948 QPixmap pixmap(size);
4949 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
4950 pixmap.fill(Qt::transparent);
4951 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
4953 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
4954 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
4956 painter->drawPixmap(targetOffset, pixmap);
4959 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
4963 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
4964 QTransform transform = originalTransform;
4965 transform.translate(targetOffset.x(), targetOffset.y());
4967 QPaintDevice *device = painter->device();
4970 // Calculate device rect.
4971 const QRectF rect(toBePainted.boundingRect());
4972 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
4973 deviceRect &= QRect(0, 0, device->width(), device->height());
4975 QPixmap pixmap(deviceRect.size());
4976 pixmap.fill(Qt::transparent);
4978 // Create a pixmap device coordinate painter.
4979 QPainter pixmapPainter(&pixmap);
4980 pixmapPainter.setRenderHints(painter->renderHints());
4981 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
4982 pixmapPainter.setTransform(transform);
4984 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
4985 pixmapPainter.end();
4987 // And then draw the pixmap.
4988 painter->setTransform(QTransform());
4989 painter->drawPixmap(deviceRect.topLeft(), pixmap);
4990 painter->setTransform(originalTransform);
4995 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
4996 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5002 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5003 dirtyOnWidget = QRegion();
5005 // We disable the rendering of QToolBar in the backingStore if
5006 // it's supposed to be in the unified toolbar on Mac OS X.
5007 if (backingStore && isInUnifiedToolbar)
5013 #ifndef QT_NO_GRAPHICSEFFECT
5014 if (graphicsEffect && graphicsEffect->isEnabled()) {
5015 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5016 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5018 if (!sourced->context) {
5019 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5020 sourced->context = &context;
5021 if (!sharedPainter) {
5022 QPaintEngine *paintEngine = pdev->paintEngine();
5023 paintEngine->d_func()->systemClip = rgn.translated(offset);
5025 p.translate(offset);
5026 context.painter = &p;
5027 graphicsEffect->draw(&p);
5028 paintEngine->d_func()->systemClip = QRegion();
5030 context.painter = sharedPainter;
5031 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5032 sourced->invalidateCache();
5033 sourced->lastEffectTransform = sharedPainter->worldTransform();
5035 sharedPainter->save();
5036 sharedPainter->translate(offset);
5037 graphicsEffect->draw(sharedPainter);
5038 sharedPainter->restore();
5040 sourced->context = 0;
5044 #endif //QT_NO_GRAFFICSEFFECT
5046 const bool asRoot = flags & DrawAsRoot;
5047 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5048 const bool recursive = flags & DrawRecursive;
5049 const bool alsoInvisible = flags & DrawInvisible;
5051 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5053 QRegion toBePainted(rgn);
5054 if (asRoot && !alsoInvisible)
5055 toBePainted &= clipRect(); //(rgn & visibleRegion());
5056 if (!(flags & DontSubtractOpaqueChildren))
5057 subtractOpaqueChildren(toBePainted, q->rect());
5059 if (!toBePainted.isEmpty()) {
5060 bool onScreen = paintOnScreen();
5061 if (!onScreen || alsoOnScreen) {
5062 //update the "in paint event" flag
5063 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5064 qWarning("QWidget::repaint: Recursive repaint detected");
5065 q->setAttribute(Qt::WA_WState_InPaintEvent);
5067 //clip away the new area
5068 #ifndef QT_NO_PAINT_DEBUG
5069 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5071 QPaintEngine *paintEngine = pdev->paintEngine();
5073 setRedirected(pdev, -offset);
5076 // (Alien support) Special case for Mac when redirecting: If the paint device
5077 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5078 // outside the paint event is not supported on QWidgets. The attributeis
5079 // restored further down.
5080 if (pdev->devType() == QInternal::Widget)
5081 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5085 paintEngine->d_func()->systemClip = toBePainted;
5087 paintEngine->d_func()->systemRect = q->data->crect;
5089 //paint the background
5090 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5091 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5093 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5097 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5099 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5101 QColor tint = q->palette().window().color();
5102 tint.setAlphaF(qreal(.6));
5103 p.fillRect(toBePainted.boundingRect(), tint);
5108 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5109 qDebug() << "clipping to" << toBePainted << "location == " << offset
5110 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5113 //actually send the paint event
5114 QPaintEvent e(toBePainted);
5115 QCoreApplication::sendSpontaneousEvent(q, &e);
5120 if (pdev->devType() == QInternal::Widget)
5121 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5123 restoreRedirected();
5125 paintEngine->d_func()->systemRect = QRect();
5127 paintEngine->d_func()->currentClipDevice = 0;
5128 paintEngine->d_func()->systemClip = QRegion();
5130 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5131 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5132 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5134 if (paintEngine && paintEngine->autoDestruct()) {
5138 #ifndef QT_NO_PAINT_DEBUG
5140 QWidgetBackingStore::unflushPaint(q, toBePainted);
5142 } else if (q->isWindow()) {
5143 QPaintEngine *engine = pdev->paintEngine();
5146 p.setClipRegion(toBePainted);
5147 const QBrush bg = q->palette().brush(QPalette::Window);
5148 if (bg.style() == Qt::TexturePattern)
5149 p.drawTiledPixmap(q->rect(), bg.texture());
5151 p.fillRect(q->rect(), bg);
5153 if (engine->autoDestruct())
5159 if (recursive && !children.isEmpty()) {
5160 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5161 , sharedPainter, backingStore);
5165 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5166 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5170 qWarning("QWidget::render: null pointer to paint device");
5174 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5175 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5176 ? prepareToRender(sourceRegion, renderFlags)
5178 if (paintRegion.isEmpty())
5182 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5184 // Use the target's shared painter if set (typically set when doing
5185 // "other->render(widget);" in the widget's paintEvent.
5186 if (target->devType() == QInternal::Widget) {
5187 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5188 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5189 QPainter *targetPainter = targetPrivate->sharedPainter();
5190 if (targetPainter && targetPainter->isActive())
5191 setSharedPainter(targetPainter);
5196 // Use the target's redirected device if set and adjust offset and paint
5197 // region accordingly. This is typically the case when people call render
5198 // from the paintEvent.
5199 QPoint offset = targetOffset;
5200 offset -= paintRegion.boundingRect().topLeft();
5201 QPoint redirectionOffset;
5202 QPaintDevice *redirected = 0;
5204 if (target->devType() == QInternal::Widget)
5205 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5207 redirected = QPainter::redirected(target, &redirectionOffset);
5210 target = redirected;
5211 offset -= redirectionOffset;
5214 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5215 if (QPaintEngine *targetEngine = target->paintEngine()) {
5216 const QRegion targetSystemClip = targetEngine->systemClip();
5217 if (!targetSystemClip.isEmpty())
5218 paintRegion &= targetSystemClip.translated(-offset);
5222 // Set backingstore flags.
5223 int flags = DrawPaintOnScreen | DrawInvisible;
5224 if (renderFlags & QWidget::DrawWindowBackground)
5225 flags |= DrawAsRoot;
5227 if (renderFlags & QWidget::DrawChildren)
5228 flags |= DrawRecursive;
5230 flags |= DontSubtractOpaqueChildren;
5232 if (target->devType() == QInternal::Printer) {
5234 render_helper(&p, targetOffset, paintRegion, renderFlags);
5239 // Render via backingstore.
5240 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5242 // Restore shared painter.
5243 if (oldSharedPainter)
5244 setSharedPainter(oldSharedPainter);
5246 // Render via backingstore (no shared painter).
5247 drawWidget(target, paintRegion, offset, flags, 0);
5251 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5252 const QPoint &offset, int flags
5253 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5257 bool dirtyBoundingRect = true;
5258 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5259 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5262 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5263 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5264 && !(excludeNativeChildren && x->internalWinId())) {
5265 if (dirtyBoundingRect) {
5266 boundingRect = rgn.boundingRect();
5267 dirtyBoundingRect = false;
5270 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5276 } while (index >= 0);
5281 QWidgetPrivate *wd = w->d_func();
5282 const QPoint widgetPos(w->data->crect.topLeft());
5283 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5287 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5288 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5289 , sharedPainter, backingStore);
5292 if (w->updatesEnabled()
5293 #ifndef QT_NO_GRAPHICSVIEW
5294 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5295 #endif //QT_NO_GRAPHICSVIEW
5297 QRegion wRegion(rgn);
5298 wRegion &= wd->effectiveRectFor(w->data->crect);
5299 wRegion.translate(-widgetPos);
5301 wRegion &= wd->extra->mask;
5302 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5306 #ifndef QT_NO_GRAPHICSEFFECT
5307 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5309 if (system != Qt::DeviceCoordinates)
5310 return m_widget->rect();
5313 // Device coordinates without context not yet supported.
5314 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5318 return context->painter->worldTransform().mapRect(m_widget->rect());
5321 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5323 if (!context || context->painter != painter) {
5324 m_widget->render(painter);
5328 // The region saved in the context is neither clipped to the rect
5329 // nor the mask, so we have to clip it here before calling drawWidget.
5330 QRegion toBePainted = context->rgn;
5331 toBePainted &= m_widget->rect();
5332 QWidgetPrivate *wd = qt_widget_private(m_widget);
5333 if (wd->extra && wd->extra->hasMask)
5334 toBePainted &= wd->extra->mask;
5336 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5337 context->sharedPainter, context->backingStore);
5340 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5341 QGraphicsEffect::PixmapPadMode mode) const
5343 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5344 if (!context && deviceCoordinates) {
5345 // Device coordinates without context not yet supported.
5346 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5350 QPoint pixmapOffset;
5351 QRectF sourceRect = m_widget->rect();
5353 if (deviceCoordinates) {
5354 const QTransform &painterTransform = context->painter->worldTransform();
5355 sourceRect = painterTransform.mapRect(sourceRect);
5356 pixmapOffset = painterTransform.map(pixmapOffset);
5361 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5362 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5363 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5364 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5366 effectRect = sourceRect.toAlignedRect();
5369 *offset = effectRect.topLeft();
5371 pixmapOffset -= effectRect.topLeft();
5373 QPixmap pixmap(effectRect.size());
5374 pixmap.fill(Qt::transparent);
5375 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5378 #endif //QT_NO_GRAPHICSEFFECT
5380 #ifndef QT_NO_GRAPHICSVIEW
5384 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5385 widget and its ancestors. The search starts at \a origin (inclusive).
5386 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5389 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5392 QWExtra *extra = origin->d_func()->extra;
5393 if (extra && extra->proxyWidget)
5394 return extra->proxyWidget;
5395 return nearestGraphicsProxyWidget(origin->parentWidget());
5402 \property QWidget::locale
5403 \brief the widget's locale
5406 As long as no special locale has been set, this is either
5407 the parent's locale or (if this widget is a top level widget),
5410 If the widget displays dates or numbers, these should be formatted
5411 using the widget's locale.
5413 \sa QLocale QLocale::setDefault()
5416 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5419 if (locale == loc && !forceUpdate)
5424 if (!children.isEmpty()) {
5425 for (int i = 0; i < children.size(); ++i) {
5426 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5429 if (w->testAttribute(Qt::WA_SetLocale))
5431 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5433 w->d_func()->setLocale_helper(loc, forceUpdate);
5436 QEvent e(QEvent::LocaleChange);
5437 QApplication::sendEvent(q, &e);
5440 void QWidget::setLocale(const QLocale &locale)
5444 setAttribute(Qt::WA_SetLocale);
5445 d->setLocale_helper(locale);
5448 QLocale QWidget::locale() const
5455 void QWidgetPrivate::resolveLocale()
5459 if (!q->testAttribute(Qt::WA_SetLocale)) {
5460 setLocale_helper(q->isWindow()
5462 : q->parentWidget()->locale());
5466 void QWidget::unsetLocale()
5469 setAttribute(Qt::WA_SetLocale, false);
5473 static QString constructWindowTitleFromFilePath(const QString &filePath)
5475 QFileInfo fi(filePath);
5476 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5478 QString appName = QApplication::applicationName();
5479 if (!appName.isEmpty())
5480 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5486 \property QWidget::windowTitle
5487 \brief the window title (caption)
5489 This property only makes sense for top-level widgets, such as
5490 windows and dialogs. If no caption has been set, the title is based of the
5491 \l windowFilePath. If neither of these is set, then the title is
5494 If you use the \l windowModified mechanism, the window title must
5495 contain a "[*]" placeholder, which indicates where the '*' should
5496 appear. Normally, it should appear right after the file name
5497 (e.g., "document1.txt[*] - Text Editor"). If the \l
5498 windowModified property is false (the default), the placeholder
5501 \sa windowIcon, windowIconText, windowModified, windowFilePath
5503 QString QWidget::windowTitle() const
5506 if (d->extra && d->extra->topextra) {
5507 if (!d->extra->topextra->caption.isEmpty())
5508 return d->extra->topextra->caption;
5509 if (!d->extra->topextra->filePath.isEmpty())
5510 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5516 Returns a modified window title with the [*] place holder
5517 replaced according to the rules described in QWidget::setWindowTitle
5519 This function assumes that "[*]" can be quoted by another
5520 "[*]", so it will replace two place holders by one and
5521 a single last one by either "*" or nothing depending on
5526 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5531 extern QString qt_eval_adapt_window_title(const QString &title);
5532 QString cap = qt_eval_adapt_window_title(title);
5534 QString cap = title;
5540 QLatin1String placeHolder("[*]");
5541 int placeHolderLength = 3; // QLatin1String doesn't have length()
5543 int index = cap.indexOf(placeHolder);
5545 // here the magic begins
5546 while (index != -1) {
5547 index += placeHolderLength;
5549 while (cap.indexOf(placeHolder, index) == index) {
5551 index += placeHolderLength;
5554 if (count%2) { // odd number of [*] -> replace last one
5555 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5556 if (widget->isWindowModified()
5557 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5558 cap.replace(lastIndex, 3, QWidget::tr("*"));
5560 cap.remove(lastIndex, 3);
5563 index = cap.indexOf(placeHolder, index);
5566 cap.replace(QLatin1String("[*][*]"), placeHolder);
5571 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5574 if (q->testAttribute(Qt::WA_WState_Created))
5575 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5578 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5581 if (q->testAttribute(Qt::WA_WState_Created))
5582 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5585 void QWidget::setWindowIconText(const QString &iconText)
5587 if (QWidget::windowIconText() == iconText)
5591 d->topData()->iconText = iconText;
5592 d->setWindowIconText_helper(iconText);
5594 QEvent e(QEvent::IconTextChange);
5595 QApplication::sendEvent(this, &e);
5598 void QWidget::setWindowTitle(const QString &title)
5600 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5604 d->topData()->caption = title;
5605 d->setWindowTitle_helper(title);
5607 QEvent e(QEvent::WindowTitleChange);
5608 QApplication::sendEvent(this, &e);
5613 \property QWidget::windowIcon
5614 \brief the widget's icon
5616 This property only makes sense for windows. If no icon
5617 has been set, windowIcon() returns the application icon
5618 (QApplication::windowIcon()).
5620 \sa windowIconText, windowTitle
5622 QIcon QWidget::windowIcon() const
5624 const QWidget *w = this;
5626 const QWidgetPrivate *d = w->d_func();
5627 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5628 return *d->extra->topextra->icon;
5629 w = w->parentWidget();
5631 return QApplication::windowIcon();
5634 void QWidgetPrivate::setWindowIcon_helper()
5636 QEvent e(QEvent::WindowIconChange);
5637 QApplication::sendEvent(q_func(), &e);
5638 for (int i = 0; i < children.size(); ++i) {
5639 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5640 if (w && !w->isWindow())
5641 QApplication::sendEvent(w, &e);
5645 void QWidget::setWindowIcon(const QIcon &icon)
5649 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5652 if (!d->extra->topextra->icon)
5653 d->extra->topextra->icon = new QIcon();
5654 *d->extra->topextra->icon = icon;
5656 delete d->extra->topextra->iconPixmap;
5657 d->extra->topextra->iconPixmap = 0;
5659 d->setWindowIcon_sys();
5660 d->setWindowIcon_helper();
5665 \property QWidget::windowIconText
5666 \brief the widget's icon text
5668 This property only makes sense for windows. If no icon
5669 text has been set, this functions returns an empty string.
5671 \sa windowIcon, windowTitle
5674 QString QWidget::windowIconText() const
5677 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5681 \property QWidget::windowFilePath
5683 \brief the file path associated with a widget
5685 This property only makes sense for windows. It associates a file path with
5686 a window. If you set the file path, but have not set the window title, Qt
5687 sets the window title to contain a string created using the following
5693 \li The file name of the specified path, obtained using QFileInfo::fileName().
5699 \li The file name of the specified path, obtained using QFileInfo::fileName().
5700 \li An optional \c{*} character, if the \l windowModified property is set.
5701 \li The \c{0x2014} unicode character, padded either side by spaces.
5702 \li The application name, obtained from the application's
5703 \l{QCoreApplication::}{applicationName} property.
5706 If the window title is set at any point, then the window title takes precedence and
5707 will be shown instead of the file path string.
5709 Additionally, on Mac OS X, this has an added benefit that it sets the
5710 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5711 for the window, assuming that the file path exists.
5713 If no file path is set, this property contains an empty string.
5715 By default, this property contains an empty string.
5717 \sa windowTitle, windowIcon
5720 QString QWidget::windowFilePath() const
5723 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5726 void QWidget::setWindowFilePath(const QString &filePath)
5728 if (filePath == windowFilePath())
5734 d->extra->topextra->filePath = filePath;
5735 d->setWindowFilePath_helper(filePath);
5738 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5740 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5742 setWindowTitle_helper(QFileInfo(filePath).fileName());
5746 setWindowTitle_helper(q->windowTitle());
5750 setWindowFilePath_sys(filePath);
5755 Returns the window's role, or an empty string.
5757 \sa windowIcon, windowTitle
5760 QString QWidget::windowRole() const
5763 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5767 Sets the window's role to \a role. This only makes sense for
5770 void QWidget::setWindowRole(const QString &role)
5772 #if defined(Q_WS_X11)
5774 d->topData()->role = role;
5782 \property QWidget::mouseTracking
5783 \brief whether mouse tracking is enabled for the widget
5785 If mouse tracking is disabled (the default), the widget only
5786 receives mouse move events when at least one mouse button is
5787 pressed while the mouse is being moved.
5789 If mouse tracking is enabled, the widget receives mouse move
5790 events even if no buttons are pressed.
5792 \sa mouseMoveEvent()
5797 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5798 function resets this widget to have no focus proxy.
5800 Some widgets can "have focus", but create a child widget, such as
5801 QLineEdit, to actually handle the focus. In this case, the widget
5802 can set the line edit to be its focus proxy.
5804 setFocusProxy() sets the widget which will actually get focus when
5805 "this widget" gets it. If there is a focus proxy, setFocus() and
5806 hasFocus() operate on the focus proxy.
5811 void QWidget::setFocusProxy(QWidget * w)
5814 if (!w && !d->extra)
5817 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5819 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5825 d->extra->focus_proxy = w;
5830 Returns the focus proxy, or 0 if there is no focus proxy.
5835 QWidget * QWidget::focusProxy() const
5838 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5843 \property QWidget::focus
5844 \brief whether this widget (or its focus proxy) has the keyboard
5847 By default, this property is false.
5849 \note Obtaining the value of this property for a widget is effectively equivalent
5850 to checking whether QApplication::focusWidget() refers to the widget.
5852 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5854 bool QWidget::hasFocus() const
5856 const QWidget* w = this;
5857 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5858 w = w->d_func()->extra->focus_proxy;
5859 if (QWidget *window = w->window()) {
5860 #ifndef QT_NO_GRAPHICSVIEW
5861 QWExtra *e = window->d_func()->extra;
5862 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5866 return (QApplication::focusWidget() == w);
5870 Gives the keyboard input focus to this widget (or its focus
5871 proxy) if this widget or one of its parents is the \link
5872 isActiveWindow() active window\endlink. The \a reason argument will
5873 be passed into any focus event sent from this function, it is used
5874 to give an explanation of what caused the widget to get focus.
5875 If the window is not active, the widget will be given the focus when
5876 the window becomes active.
5878 First, a focus about to change event is sent to the focus widget (if any) to
5879 tell it that it is about to lose the focus. Then focus is changed, a
5880 focus out event is sent to the previous focus item and a focus in event is sent
5881 to the new item to tell it that it just received the focus.
5882 (Nothing happens if the focus in and focus out widgets are the
5885 \note On embedded platforms, setFocus() will not cause an input panel
5886 to be opened by the input method. If you want this to happen, you
5887 have to send a QEvent::RequestSoftwareInputPanel event to the
5890 setFocus() gives focus to a widget regardless of its focus policy,
5891 but does not clear any keyboard grab (see grabKeyboard()).
5893 Be aware that if the widget is hidden, it will not accept focus
5896 \warning If you call setFocus() in a function which may itself be
5897 called from focusOutEvent() or focusInEvent(), you may get an
5900 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5901 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5902 grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
5905 void QWidget::setFocus(Qt::FocusReason reason)
5911 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
5912 f = f->d_func()->extra->focus_proxy;
5914 if (QApplication::focusWidget() == f
5915 #if defined(Q_WS_WIN)
5916 && GetFocus() == f->internalWinId()
5921 #ifndef QT_NO_GRAPHICSVIEW
5922 QWidget *previousProxyFocus = 0;
5923 if (QWExtra *topData = window()->d_func()->extra) {
5924 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
5925 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
5926 if (previousProxyFocus && previousProxyFocus->focusProxy())
5927 previousProxyFocus = previousProxyFocus->focusProxy();
5928 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
5934 #ifndef QT_NO_GRAPHICSVIEW
5935 // Update proxy state
5936 if (QWExtra *topData = window()->d_func()->extra) {
5937 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
5938 f->d_func()->updateFocusChild();
5939 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
5940 topData->proxyWidget->setFocus(reason);
5941 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
5946 if (f->isActiveWindow()) {
5947 QWidget *prev = QApplicationPrivate::focus_widget;
5949 if (reason != Qt::PopupFocusReason && reason != Qt::MenuBarFocusReason
5950 && prev->testAttribute(Qt::WA_InputMethodEnabled)) {
5951 qApp->inputMethod()->reset();
5954 if (reason != Qt::NoFocusReason) {
5955 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange, reason);
5956 QApplication::sendEvent(prev, &focusAboutToChange);
5960 f->d_func()->updateFocusChild();
5962 QApplicationPrivate::setFocusWidget(f, reason);
5963 #ifndef QT_NO_ACCESSIBILITY
5965 // The negation of the condition in setFocus_sys
5966 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
5967 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
5970 // menus update the focus manually and this would create bogus events
5971 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
5974 QAccessibleEvent event(f, QAccessible::Focus);
5975 QAccessible::updateAccessibility(&event);
5978 #ifndef QT_NO_GRAPHICSVIEW
5979 if (QWExtra *topData = window()->d_func()->extra) {
5980 if (topData->proxyWidget) {
5981 if (previousProxyFocus && previousProxyFocus != f) {
5982 // Send event to self
5983 QFocusEvent event(QEvent::FocusOut, reason);
5984 QPointer<QWidget> that = previousProxyFocus;
5985 QApplication::sendEvent(previousProxyFocus, &event);
5987 QApplication::sendEvent(that->style(), &event);
5990 #ifndef QT_NO_GRAPHICSVIEW
5991 // Update proxy state
5992 if (QWExtra *topData = window()->d_func()->extra)
5993 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
5994 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
5996 // Send event to self
5997 QFocusEvent event(QEvent::FocusIn, reason);
5998 QPointer<QWidget> that = f;
5999 QApplication::sendEvent(f, &event);
6001 QApplication::sendEvent(that->style(), &event);
6007 f->d_func()->updateFocusChild();
6010 if (QTLWExtra *extra = f->window()->d_func()->maybeTopData())
6011 emit extra->window->focusObjectChanged(f);
6014 // updates focus_child on parent widgets to point into this widget
6015 void QWidgetPrivate::updateFocusChild()
6020 if (q->isHidden()) {
6021 while (w && w->isHidden()) {
6022 w->d_func()->focus_child = q;
6023 w = w->isWindow() ? 0 : w->parentWidget();
6027 w->d_func()->focus_child = q;
6028 w = w->isWindow() ? 0 : w->parentWidget();
6034 \fn void QWidget::setFocus()
6037 Gives the keyboard input focus to this widget (or its focus
6038 proxy) if this widget or one of its parents is the
6039 \l{isActiveWindow()}{active window}.
6043 Takes keyboard input focus from the widget.
6045 If the widget has active focus, a \link focusOutEvent() focus out
6046 event\endlink is sent to this widget to tell it that it has
6049 This widget must enable focus setting in order to get the keyboard
6050 input focus, i.e. it must call setFocusPolicy().
6052 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6053 setFocusPolicy(), QApplication::focusWidget()
6056 void QWidget::clearFocus()
6059 if (testAttribute(Qt::WA_InputMethodEnabled))
6060 qApp->inputMethod()->reset();
6062 QFocusEvent focusAboutToChange(QEvent::FocusAboutToChange);
6063 QApplication::sendEvent(this, &focusAboutToChange);
6068 if (w->d_func()->focus_child == this)
6069 w->d_func()->focus_child = 0;
6070 w = w->parentWidget();
6072 #ifndef QT_NO_GRAPHICSVIEW
6073 QWExtra *topData = d_func()->extra;
6074 if (topData && topData->proxyWidget)
6075 topData->proxyWidget->clearFocus();
6079 // Update proxy state
6080 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6081 #if defined(Q_WS_WIN)
6082 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6087 #ifndef QT_NO_ACCESSIBILITY
6088 QAccessibleEvent event(this, QAccessible::Focus);
6089 QAccessible::updateAccessibility(&event);
6097 \fn bool QWidget::focusNextChild()
6099 Finds a new widget to give the keyboard focus to, as appropriate
6100 for \key Tab, and returns true if it can find a new widget, or
6103 \sa focusPreviousChild()
6107 \fn bool QWidget::focusPreviousChild()
6109 Finds a new widget to give the keyboard focus to, as appropriate
6110 for \key Shift+Tab, and returns true if it can find a new widget,
6111 or false if it can't.
6113 \sa focusNextChild()
6117 Finds a new widget to give the keyboard focus to, as appropriate
6118 for Tab and Shift+Tab, and returns true if it can find a new
6119 widget, or false if it can't.
6121 If \a next is true, this function searches forward, if \a next
6122 is false, it searches backward.
6124 Sometimes, you will want to reimplement this function. For
6125 example, a web browser might reimplement it to move its "current
6126 active link" forward or backward, and call
6127 focusNextPrevChild() only when it reaches the last or
6128 first link on the "page".
6130 Child widgets call focusNextPrevChild() on their parent widgets,
6131 but only the window that contains the child widgets decides where
6132 to redirect focus. By reimplementing this function for an object,
6133 you thus gain control of focus traversal for all child widgets.
6135 \sa focusNextChild(), focusPreviousChild()
6138 bool QWidget::focusNextPrevChild(bool next)
6141 QWidget* p = parentWidget();
6142 bool isSubWindow = (windowType() == Qt::SubWindow);
6143 if (!isWindow() && !isSubWindow && p)
6144 return p->focusNextPrevChild(next);
6145 #ifndef QT_NO_GRAPHICSVIEW
6146 if (d->extra && d->extra->proxyWidget)
6147 return d->extra->proxyWidget->focusNextPrevChild(next);
6149 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6150 if (!w) return false;
6152 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6157 Returns the last child of this widget that setFocus had been
6158 called on. For top level widgets this is the widget that will get
6159 focus in case this window gets activated
6161 This is not the same as QApplication::focusWidget(), which returns
6162 the focus widget in the currently active window.
6165 QWidget *QWidget::focusWidget() const
6167 return const_cast<QWidget *>(d_func()->focus_child);
6171 Returns the next widget in this widget's focus chain.
6173 \sa previousInFocusChain()
6175 QWidget *QWidget::nextInFocusChain() const
6177 return const_cast<QWidget *>(d_func()->focus_next);
6181 \brief The previousInFocusChain function returns the previous
6182 widget in this widget's focus chain.
6184 \sa nextInFocusChain()
6188 QWidget *QWidget::previousInFocusChain() const
6190 return const_cast<QWidget *>(d_func()->focus_prev);
6194 \property QWidget::isActiveWindow
6195 \brief whether this widget's window is the active window
6197 The active window is the window that contains the widget that has
6198 keyboard focus (The window may still have focus if it has no
6199 widgets or none of its widgets accepts keyboard focus).
6201 When popup windows are visible, this property is true for both the
6202 active window \e and for the popup.
6204 By default, this property is false.
6206 \sa activateWindow(), QApplication::activeWindow()
6208 bool QWidget::isActiveWindow() const
6210 QWidget *tlw = window();
6211 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6214 #ifndef QT_NO_GRAPHICSVIEW
6215 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6216 if (isVisible() && tlwExtra->proxyWidget)
6217 return tlwExtra->proxyWidget->isActiveWindow();
6222 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6223 if(qt_mac_is_macdrawer(tlw) &&
6224 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6227 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6228 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6231 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6232 if(tlw->windowType() == Qt::Tool &&
6234 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6236 QWidget *w = QApplication::activeWindow();
6237 while(w && tlw->windowType() == Qt::Tool &&
6238 !w->isModal() && w->parentWidget()) {
6239 w = w->parentWidget()->window();
6244 #if defined(Q_WS_WIN32)
6245 HWND active = GetActiveWindow();
6246 if (!tlw->testAttribute(Qt::WA_WState_Created))
6248 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6255 Puts the \a second widget after the \a first widget in the focus order.
6257 Note that since the tab order of the \a second widget is changed, you
6258 should order a chain like this:
6260 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6264 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6266 If \a first or \a second has a focus proxy, setTabOrder()
6267 correctly substitutes the proxy.
6269 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6271 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6273 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6276 if (first->window() != second->window()) {
6277 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6281 QWidget *fp = first->focusProxy();
6283 // If first is redirected, set first to the last child of first
6284 // that can take keyboard focus so that second is inserted after
6285 // that last child, and the focus order within first is (more
6286 // likely to be) preserved.
6287 QList<QWidget *> l = first->findChildren<QWidget *>();
6288 for (int i = l.size()-1; i >= 0; --i) {
6289 QWidget * next = l.at(i);
6290 if (next->window() == fp->window()) {
6292 if (fp->focusPolicy() != Qt::NoFocus)
6302 if (QWidget *sp = second->focusProxy())
6305 // QWidget *fp = first->d_func()->focus_prev;
6306 QWidget *fn = first->d_func()->focus_next;
6308 if (fn == second || first == second)
6311 QWidget *sp = second->d_func()->focus_prev;
6312 QWidget *sn = second->d_func()->focus_next;
6314 fn->d_func()->focus_prev = second;
6315 first->d_func()->focus_next = second;
6317 second->d_func()->focus_next = fn;
6318 second->d_func()->focus_prev = first;
6320 sp->d_func()->focus_next = sn;
6321 sn->d_func()->focus_prev = sp;
6324 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6325 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6327 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6328 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6333 Moves the relevant subwidgets of this widget from the \a oldtlw's
6334 tab chain to that of the new parent, if there's anything to move and
6337 This function is called from QWidget::reparent() *after* the widget
6338 has been reparented.
6343 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6346 if (oldtlw == q->window())
6347 return; // nothing to do
6350 focus_child->clearFocus();
6352 // separate the focus chain into new (children of myself) and old (the rest)
6353 QWidget *firstOld = 0;
6354 //QWidget *firstNew = q; //invariant
6355 QWidget *o = 0; // last in the old list
6356 QWidget *n = q; // last in the new list
6358 bool prevWasNew = true;
6359 QWidget *w = focus_next;
6361 //Note: for efficiency, we do not maintain the list invariant inside the loop
6362 //we append items to the relevant list, and we optimize by not changing pointers
6363 //when subsequent items are going into the same list.
6365 bool currentIsNew = q->isAncestorOf(w);
6368 //prev was old -- append to new list
6369 n->d_func()->focus_next = w;
6370 w->d_func()->focus_prev = n;
6375 //prev was new -- append to old list, if there is one
6377 o->d_func()->focus_next = w;
6378 w->d_func()->focus_prev = o;
6380 // "create" the old list
6386 w = w->d_func()->focus_next;
6387 prevWasNew = currentIsNew;
6390 //repair the old list:
6392 o->d_func()->focus_next = firstOld;
6393 firstOld->d_func()->focus_prev = o;
6396 if (!q->isWindow()) {
6397 QWidget *topLevel = q->window();
6398 //insert new chain into toplevel's chain
6400 QWidget *prev = topLevel->d_func()->focus_prev;
6402 topLevel->d_func()->focus_prev = n;
6403 prev->d_func()->focus_next = q;
6406 n->d_func()->focus_next = topLevel;
6408 //repair the new list
6409 n->d_func()->focus_next = q;
6417 Measures the shortest distance from a point to a rect.
6419 This function is called from QDesktopwidget::screen(QPoint) to find the
6420 closest screen for a point.
6421 In directional KeypadNavigation, it is called to find the closest
6422 widget to the current focus widget center.
6424 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6428 if (p.x() < r.left())
6429 dx = r.left() - p.x();
6430 else if (p.x() > r.right())
6431 dx = p.x() - r.right();
6432 if (p.y() < r.top())
6433 dy = r.top() - p.y();
6434 else if (p.y() > r.bottom())
6435 dy = p.y() - r.bottom();
6440 \property QWidget::frameSize
6441 \brief the size of the widget including any window frame
6443 By default, this property contains a value that depends on the user's
6444 platform and screen geometry.
6446 QSize QWidget::frameSize() const
6449 if (isWindow() && !(windowType() == Qt::Popup)) {
6450 QRect fs = d->frameStrut();
6451 return QSize(data->crect.width() + fs.left() + fs.right(),
6452 data->crect.height() + fs.top() + fs.bottom());
6454 return data->crect.size();
6457 /*! \fn void QWidget::move(int x, int y)
6461 This corresponds to move(QPoint(\a x, \a y)).
6464 void QWidget::move(const QPoint &p)
6467 setAttribute(Qt::WA_Moved);
6469 d->topData()->posFromMove = true;
6470 if (testAttribute(Qt::WA_WState_Created)) {
6471 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6472 p.y() + geometry().y() - QWidget::y(),
6473 width(), height(), true);
6474 d->setDirtyOpaqueRegion();
6476 data->crect.moveTopLeft(p); // no frame yet
6477 setAttribute(Qt::WA_PendingMoveEvent);
6481 /*! \fn void QWidget::resize(int w, int h)
6484 This corresponds to resize(QSize(\a w, \a h)).
6487 void QWidget::resize(const QSize &s)
6490 setAttribute(Qt::WA_Resized);
6491 if (testAttribute(Qt::WA_WState_Created)) {
6492 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6493 d->setDirtyOpaqueRegion();
6495 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6496 setAttribute(Qt::WA_PendingResizeEvent);
6500 void QWidget::setGeometry(const QRect &r)
6503 setAttribute(Qt::WA_Resized);
6504 setAttribute(Qt::WA_Moved);
6506 d->topData()->posFromMove = false;
6507 if (testAttribute(Qt::WA_WState_Created)) {
6508 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6509 d->setDirtyOpaqueRegion();
6511 data->crect.setTopLeft(r.topLeft());
6512 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6513 setAttribute(Qt::WA_PendingMoveEvent);
6514 setAttribute(Qt::WA_PendingResizeEvent);
6520 Saves the current geometry and state for top-level widgets.
6522 To save the geometry when the window closes, you can
6523 implement a close event like this:
6525 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6527 See the \l{Window Geometry} documentation for an overview of geometry
6528 issues with windows.
6530 Use QMainWindow::saveState() to save the geometry and the state of
6531 toolbars and dock widgets.
6533 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6535 QByteArray QWidget::saveGeometry() const
6538 // We check if the window was maximized during this invocation. If so, we need to record the
6539 // starting position as 0,0.
6541 QRect newFramePosition = frameGeometry();
6542 QRect newNormalPosition = normalGeometry();
6543 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6544 // Change the starting position
6545 newFramePosition.moveTo(0, 0);
6546 newNormalPosition.moveTo(0, 0);
6550 QDataStream stream(&array, QIODevice::WriteOnly);
6551 stream.setVersion(QDataStream::Qt_4_0);
6552 const quint32 magicNumber = 0x1D9D0CB;
6553 quint16 majorVersion = 1;
6554 quint16 minorVersion = 0;
6555 stream << magicNumber
6560 << newNormalPosition
6565 << qint32(QApplication::desktop()->screenNumber(this))
6566 << quint8(windowState() & Qt::WindowMaximized)
6567 << quint8(windowState() & Qt::WindowFullScreen);
6574 Restores the geometry and state top-level widgets stored in the
6575 byte array \a geometry. Returns true on success; otherwise
6578 If the restored geometry is off-screen, it will be modified to be
6579 inside the available screen geometry.
6581 To restore geometry saved using QSettings, you can use code like
6584 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6586 See the \l{Window Geometry} documentation for an overview of geometry
6587 issues with windows.
6589 Use QMainWindow::restoreState() to restore the geometry and the
6590 state of toolbars and dock widgets.
6592 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6594 bool QWidget::restoreGeometry(const QByteArray &geometry)
6596 if (geometry.size() < 4)
6598 QDataStream stream(geometry);
6599 stream.setVersion(QDataStream::Qt_4_0);
6601 const quint32 magicNumber = 0x1D9D0CB;
6602 quint32 storedMagicNumber;
6603 stream >> storedMagicNumber;
6604 if (storedMagicNumber != magicNumber)
6607 const quint16 currentMajorVersion = 1;
6608 quint16 majorVersion = 0;
6609 quint16 minorVersion = 0;
6611 stream >> majorVersion >> minorVersion;
6613 if (majorVersion != currentMajorVersion)
6615 // (Allow all minor versions.)
6617 QRect restoredFrameGeometry;
6618 QRect restoredNormalGeometry;
6619 qint32 restoredScreenNumber;
6623 stream >> restoredFrameGeometry
6624 >> restoredNormalGeometry
6625 >> restoredScreenNumber
6629 const int frameHeight = 20;
6630 if (!restoredFrameGeometry.isValid())
6631 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6633 if (!restoredNormalGeometry.isValid())
6634 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6635 if (!restoredNormalGeometry.isValid()) {
6636 // use the widget's adjustedSize if the sizeHint() doesn't help
6637 restoredNormalGeometry.setSize(restoredNormalGeometry
6639 .expandedTo(d_func()->adjustedSize()));
6642 const QDesktopWidget * const desktop = QApplication::desktop();
6643 if (restoredScreenNumber >= desktop->numScreens())
6644 restoredScreenNumber = desktop->primaryScreen();
6646 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6648 // Modify the restored geometry if we are about to restore to coordinates
6649 // that would make the window "lost". This happens if:
6650 // - The restored geometry is completely oustside the available geometry
6651 // - The title bar is outside the available geometry.
6652 // - (Mac only) The window is higher than the available geometry. It must
6653 // be possible to bring the size grip on screen by moving the window.
6655 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6656 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6659 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6660 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6661 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6662 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6664 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6666 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6667 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6668 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6669 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6671 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6673 if (maximized || fullScreen) {
6674 // set geomerty before setting the window state to make
6675 // sure the window is maximized to the right screen.
6676 // Skip on windows: the window is restored into a broken
6677 // half-maximized state.
6679 setGeometry(restoredNormalGeometry);
6681 Qt::WindowStates ws = windowState();
6683 ws |= Qt::WindowMaximized;
6685 ws |= Qt::WindowFullScreen;
6687 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6692 offset = d_func()->topData()->fullScreenOffset;
6694 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6695 move(restoredFrameGeometry.topLeft() + offset);
6696 resize(restoredNormalGeometry.size());
6701 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6704 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6708 Sets the margins around the contents of the widget to have the sizes
6709 \a left, \a top, \a right, and \a bottom. The margins are used by
6710 the layout system, and may be used by subclasses to specify the area
6711 to draw in (e.g. excluding the frame).
6713 Changing the margins will trigger a resizeEvent().
6715 \sa contentsRect(), getContentsMargins()
6717 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6720 if (left == d->leftmargin && top == d->topmargin
6721 && right == d->rightmargin && bottom == d->bottommargin)
6723 d->leftmargin = left;
6725 d->rightmargin = right;
6726 d->bottommargin = bottom;
6728 if (QLayout *l=d->layout)
6729 l->update(); //force activate; will do updateGeometry
6733 // ### Qt 5: compat, remove
6736 QResizeEvent e(data->crect.size(), data->crect.size());
6737 QApplication::sendEvent(this, &e);
6739 setAttribute(Qt::WA_PendingResizeEvent, true);
6742 QEvent e(QEvent::ContentsRectChange);
6743 QApplication::sendEvent(this, &e);
6750 \brief The setContentsMargins function sets the margins around the
6753 Sets the margins around the contents of the widget to have the
6754 sizes determined by \a margins. The margins are
6755 used by the layout system, and may be used by subclasses to
6756 specify the area to draw in (e.g. excluding the frame).
6758 Changing the margins will trigger a resizeEvent().
6760 \sa contentsRect(), getContentsMargins()
6762 void QWidget::setContentsMargins(const QMargins &margins)
6764 setContentsMargins(margins.left(), margins.top(),
6765 margins.right(), margins.bottom());
6769 Returns the widget's contents margins for \a left, \a top, \a
6770 right, and \a bottom.
6772 \sa setContentsMargins(), contentsRect()
6774 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6778 *left = d->leftmargin;
6780 *top = d->topmargin;
6782 *right = d->rightmargin;
6784 *bottom = d->bottommargin;
6790 \brief The contentsMargins function returns the widget's contents margins.
6792 \sa getContentsMargins(), setContentsMargins(), contentsRect()
6794 QMargins QWidget::contentsMargins() const
6797 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6802 Returns the area inside the widget's margins.
6804 \sa setContentsMargins(), getContentsMargins()
6806 QRect QWidget::contentsRect() const
6809 return QRect(QPoint(d->leftmargin, d->topmargin),
6810 QPoint(data->crect.width() - 1 - d->rightmargin,
6811 data->crect.height() - 1 - d->bottommargin));
6818 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6820 This signal is emitted when the widget's \l contextMenuPolicy is
6821 Qt::CustomContextMenu, and the user has requested a context menu on
6822 the widget. The position \a pos is the position of the context menu
6823 event that the widget receives. Normally this is in widget
6824 coordinates. The exception to this rule is QAbstractScrollArea and
6825 its subclasses that map the context menu event to coordinates of the
6826 \link QAbstractScrollArea::viewport() viewport() \endlink .
6829 \sa mapToGlobal() QMenu contextMenuPolicy
6834 \property QWidget::contextMenuPolicy
6835 \brief how the widget shows a context menu
6837 The default value of this property is Qt::DefaultContextMenu,
6838 which means the contextMenuEvent() handler is called. Other values
6839 are Qt::NoContextMenu, Qt::PreventContextMenu,
6840 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6841 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6844 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6847 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6849 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6852 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6854 data->context_menu_policy = (uint) policy;
6858 \property QWidget::focusPolicy
6859 \brief the way the widget accepts keyboard focus
6861 The policy is Qt::TabFocus if the widget accepts keyboard
6862 focus by tabbing, Qt::ClickFocus if the widget accepts
6863 focus by clicking, Qt::StrongFocus if it accepts both, and
6864 Qt::NoFocus (the default) if it does not accept focus at
6867 You must enable keyboard focus for a widget if it processes
6868 keyboard events. This is normally done from the widget's
6869 constructor. For instance, the QLineEdit constructor calls
6870 setFocusPolicy(Qt::StrongFocus).
6872 If the widget has a focus proxy, then the focus policy will
6873 be propagated to it.
6875 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6879 Qt::FocusPolicy QWidget::focusPolicy() const
6881 return (Qt::FocusPolicy)data->focus_policy;
6884 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6886 data->focus_policy = (uint) policy;
6888 if (d->extra && d->extra->focus_proxy)
6889 d->extra->focus_proxy->setFocusPolicy(policy);
6893 \property QWidget::updatesEnabled
6894 \brief whether updates are enabled
6896 An updates enabled widget receives paint events and has a system
6897 background; a disabled widget does not. This also implies that
6898 calling update() and repaint() has no effect if updates are
6901 By default, this property is true.
6903 setUpdatesEnabled() is normally used to disable updates for a
6904 short period of time, for instance to avoid screen flicker during
6905 large changes. In Qt, widgets normally do not generate screen
6906 flicker, but on X11 the server might erase regions on the screen
6907 when widgets get hidden before they can be replaced by other
6908 widgets. Disabling updates solves this.
6911 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
6913 Disabling a widget implicitly disables all its children. Enabling a widget
6914 enables all child widgets \e except top-level widgets or those that
6915 have been explicitly disabled. Re-enabling updates implicitly calls
6916 update() on the widget.
6920 void QWidget::setUpdatesEnabled(bool enable)
6923 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6924 d->setUpdatesEnabled_helper(enable);
6927 /*! \fn void QWidget::show()
6929 Shows the widget and its child widgets. This function is
6930 equivalent to setVisible(true).
6932 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6933 showNormal(), isVisible()
6939 Makes the widget visible in the isVisible() meaning of the word.
6940 It is only called for toplevels or widgets with visible parents.
6942 void QWidgetPrivate::show_recursive()
6945 // polish if necessary
6947 if (!q->testAttribute(Qt::WA_WState_Created))
6948 createRecursively();
6949 q->ensurePolished();
6951 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
6952 q->parentWidget()->d_func()->layout->activate();
6953 // activate our layout before we and our children become visible
6960 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
6964 disableUpdates = disableUpdates && q->updatesEnabled();
6966 q->setAttribute(Qt::WA_UpdatesDisabled);
6968 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
6969 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
6970 QApplication::sendEvent(q, &e);
6971 q->setAttribute(Qt::WA_PendingMoveEvent, false);
6974 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
6975 QResizeEvent e(data.crect.size(), QSize());
6976 QApplication::sendEvent(q, &e);
6977 q->setAttribute(Qt::WA_PendingResizeEvent, false);
6981 q->setAttribute(Qt::WA_UpdatesDisabled, false);
6986 for (int i = 0; i < children.size(); ++i) {
6987 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
6988 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
6992 void QWidgetPrivate::activateChildLayoutsRecursively()
6994 sendPendingMoveAndResizeEvents(false, true);
6996 for (int i = 0; i < children.size(); ++i) {
6997 QWidget *child = qobject_cast<QWidget *>(children.at(i));
6998 if (!child || child->isHidden() || child->isWindow())
7001 child->ensurePolished();
7003 // Activate child's layout
7004 QWidgetPrivate *childPrivate = child->d_func();
7005 if (childPrivate->layout)
7006 childPrivate->layout->activate();
7008 // Pretend we're visible.
7009 const bool wasVisible = child->isVisible();
7011 child->setAttribute(Qt::WA_WState_Visible);
7013 // Do the same for all my children.
7014 childPrivate->activateChildLayoutsRecursively();
7016 // We're not cheating anymore.
7018 child->setAttribute(Qt::WA_WState_Visible, false);
7022 void QWidgetPrivate::show_helper()
7025 data.in_show = true; // qws optimization
7026 // make sure we receive pending move and resize events
7027 sendPendingMoveAndResizeEvents();
7029 // become visible before showing all children
7030 q->setAttribute(Qt::WA_WState_Visible);
7032 // finally show all children recursively
7033 showChildren(false);
7037 // popup handling: new popups and tools need to be raised, and
7038 // existing popups must be closed. Also propagate the current
7039 // windows's KeyboardFocusChange status.
7040 if (q->isWindow()) {
7041 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7043 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7044 q->setAttribute(Qt::WA_KeyboardFocusChange);
7046 while (QApplication::activePopupWidget()) {
7047 if (!QApplication::activePopupWidget()->close())
7053 // Automatic embedding of child windows of widgets already embedded into
7054 // QGraphicsProxyWidget when they are shown the first time.
7055 bool isEmbedded = false;
7056 #ifndef QT_NO_GRAPHICSVIEW
7057 if (q->isWindow()) {
7058 isEmbedded = q->graphicsProxyWidget() ? true : false;
7059 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7060 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7061 if (ancestorProxy) {
7063 ancestorProxy->d_func()->embedSubWindow(q);
7068 Q_UNUSED(isEmbedded);
7071 // On Windows, show the popup now so that our own focus handling
7072 // stores the correct old focus widget even if it's stolen in the
7074 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
7075 if (!isEmbedded && q->windowType() == Qt::Popup)
7076 qApp->d_func()->openPopup(q);
7079 // send the show event before showing the window
7080 QShowEvent showEvent;
7081 QApplication::sendEvent(q, &showEvent);
7083 if (!isEmbedded && q->isModal() && q->isWindow())
7084 // QApplicationPrivate::enterModal *before* show, otherwise the initial
7085 // stacking might be wrong
7086 QApplicationPrivate::enterModal(q);
7091 if (!isEmbedded && q->windowType() == Qt::Popup)
7092 qApp->d_func()->openPopup(q);
7094 #ifndef QT_NO_ACCESSIBILITY
7095 if (q->windowType() != Qt::ToolTip) { // Tooltips are read aloud twice in MS narrator.
7096 QAccessibleEvent event(q, QAccessible::ObjectShow);
7097 QAccessible::updateAccessibility(&event);
7101 if (QApplicationPrivate::hidden_focus_widget == q) {
7102 QApplicationPrivate::hidden_focus_widget = 0;
7103 q->setFocus(Qt::OtherFocusReason);
7106 // Process events when showing a Qt::SplashScreen widget before the event loop
7107 // is spinnning; otherwise it might not show up on particular platforms.
7108 // This makes QSplashScreen behave the same on all platforms.
7109 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7110 QApplication::processEvents();
7112 data.in_show = false; // reset qws optimization
7115 /*! \fn void QWidget::hide()
7117 Hides the widget. This function is equivalent to
7121 \note If you are working with QDialog or its subclasses and you invoke
7122 the show() function after this function, the dialog will be displayed in
7123 its original position.
7125 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7130 void QWidgetPrivate::hide_helper()
7134 bool isEmbedded = false;
7135 #if !defined QT_NO_GRAPHICSVIEW
7136 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7138 Q_UNUSED(isEmbedded);
7141 if (!isEmbedded && (q->windowType() == Qt::Popup))
7142 qApp->d_func()->closePopup(q);
7144 // Move test modal here. Otherwise, a modal dialog could get
7145 // destroyed and we lose all access to its parent because we haven't
7146 // left modality. (Eg. modal Progress Dialog)
7147 if (!isEmbedded && q->isModal() && q->isWindow())
7148 QApplicationPrivate::leaveModal(q);
7150 #if defined(Q_WS_WIN)
7151 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7152 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7153 q->parentWidget()->activateWindow(); // Activate parent
7156 q->setAttribute(Qt::WA_Mapped, false);
7159 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7162 q->setAttribute(Qt::WA_WState_Visible, false);
7166 QHideEvent hideEvent;
7167 QApplication::sendEvent(q, &hideEvent);
7168 hideChildren(false);
7170 // next bit tries to move the focus if the focus widget is now
7173 qApp->d_func()->sendSyntheticEnterLeave(q);
7174 QWidget *fw = QApplication::focusWidget();
7175 while (fw && !fw->isWindow()) {
7177 q->focusNextPrevChild(true);
7180 fw = fw->parentWidget();
7184 if (QWidgetBackingStore *bs = maybeBackingStore())
7185 bs->removeDirtyWidget(q);
7187 #ifndef QT_NO_ACCESSIBILITY
7189 QAccessibleEvent event(q, QAccessible::ObjectHide);
7190 QAccessible::updateAccessibility(&event);
7196 \fn bool QWidget::isHidden() const
7198 Returns true if the widget is hidden, otherwise returns false.
7200 A hidden widget will only become visible when show() is called on
7201 it. It will not be automatically shown when the parent is shown.
7203 To check visibility, use !isVisible() instead (notice the exclamation mark).
7205 isHidden() implies !isVisible(), but a widget can be not visible
7206 and not hidden at the same time. This is the case for widgets that are children of
7207 widgets that are not visible.
7210 Widgets are hidden if:
7212 \li they were created as independent windows,
7213 \li they were created as children of visible widgets,
7214 \li hide() or setVisible(false) was called.
7219 void QWidget::setVisible(bool visible)
7221 if (visible) { // show
7222 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7227 // Designer uses a trick to make grabWidget work without showing
7228 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7229 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7230 parentWidget()->window()->d_func()->createRecursively();
7232 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7233 //but not children of non-visible parents
7234 QWidget *pw = parentWidget();
7235 if (!testAttribute(Qt::WA_WState_Created)
7236 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7240 #if defined(Q_WS_X11)
7241 if (windowType() == Qt::Window)
7242 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7245 bool wasResized = testAttribute(Qt::WA_Resized);
7246 Qt::WindowStates initialWindowState = windowState();
7248 // polish if necessary
7251 // remember that show was called explicitly
7252 setAttribute(Qt::WA_WState_ExplicitShowHide);
7253 // whether we need to inform the parent widget immediately
7254 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7255 // we are no longer hidden
7256 setAttribute(Qt::WA_WState_Hidden, false);
7258 if (needUpdateGeometry)
7259 d->updateGeometry_helper(true);
7261 // activate our layout before we and our children become visible
7263 d->layout->activate();
7266 QWidget *parent = parentWidget();
7267 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7268 parent->d_func()->layout->activate();
7269 if (parent->isWindow())
7271 parent = parent->parentWidget();
7274 parent->d_func()->setDirtyOpaqueRegion();
7277 // adjust size if necessary
7279 && (isWindow() || !parentWidget()->d_func()->layout)) {
7282 if (windowState() != initialWindowState)
7283 setWindowState(initialWindowState);
7287 setAttribute(Qt::WA_Resized, false);
7290 setAttribute(Qt::WA_KeyboardFocusChange, false);
7292 if (isWindow() || parentWidget()->isVisible()) {
7295 qApp->d_func()->sendSyntheticEnterLeave(this);
7298 QEvent showToParentEvent(QEvent::ShowToParent);
7299 QApplication::sendEvent(this, &showToParentEvent);
7301 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7303 #if defined(Q_WS_WIN)
7304 // reset WS_DISABLED style in a Blocked window
7305 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7306 && QApplicationPrivate::isBlockedByModal(this))
7308 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7309 dwStyle &= ~WS_DISABLED;
7310 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7313 if (QApplicationPrivate::hidden_focus_widget == this)
7314 QApplicationPrivate::hidden_focus_widget = 0;
7318 // hw: The test on getOpaqueRegion() needs to be more intelligent
7319 // currently it doesn't work if the widget is hidden (the region will
7320 // be clipped). The real check should be testing the cached region
7321 // (and dirty flag) directly.
7322 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7323 parentWidget()->d_func()->setDirtyOpaqueRegion();
7325 setAttribute(Qt::WA_WState_Hidden);
7326 setAttribute(Qt::WA_WState_ExplicitShowHide);
7327 if (testAttribute(Qt::WA_WState_Created))
7330 // invalidate layout similar to updateGeometry()
7331 if (!isWindow() && parentWidget()) {
7332 if (parentWidget()->d_func()->layout)
7333 parentWidget()->d_func()->layout->invalidate();
7334 else if (parentWidget()->isVisible())
7335 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7338 QEvent hideToParentEvent(QEvent::HideToParent);
7339 QApplication::sendEvent(this, &hideToParentEvent);
7343 /*!\fn void QWidget::setHidden(bool hidden)
7345 Convenience function, equivalent to setVisible(!\a hidden).
7349 void QWidgetPrivate::_q_showIfNotHidden()
7352 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7353 q->setVisible(true);
7356 void QWidgetPrivate::showChildren(bool spontaneous)
7358 QList<QObject*> childList = children;
7359 for (int i = 0; i < childList.size(); ++i) {
7360 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7362 || widget->isWindow()
7363 || widget->testAttribute(Qt::WA_WState_Hidden))
7366 widget->setAttribute(Qt::WA_Mapped);
7367 widget->d_func()->showChildren(true);
7369 QApplication::sendSpontaneousEvent(widget, &e);
7371 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7372 widget->d_func()->show_recursive();
7379 void QWidgetPrivate::hideChildren(bool spontaneous)
7381 QList<QObject*> childList = children;
7382 for (int i = 0; i < childList.size(); ++i) {
7383 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7384 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7387 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7388 // When hiding a widget we need to make sure that no mouse_down events are active, because
7389 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7390 // The solution is simple, before going through with this we check if there are any mouse_down events in
7391 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7392 // then we continue.
7393 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7394 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7395 // mouse release event. There are two ways to interpret this:
7396 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7397 // might be waiting for a release event that will never arrive.
7398 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7399 // supposed to trigger because it is not visible.
7400 if(widget == qt_button_down)
7404 widget->setAttribute(Qt::WA_Mapped, false);
7406 widget->setAttribute(Qt::WA_WState_Visible, false);
7407 widget->d_func()->hideChildren(spontaneous);
7410 QApplication::sendSpontaneousEvent(widget, &e);
7412 QApplication::sendEvent(widget, &e);
7413 if (widget->internalWinId()
7414 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7415 // hide_sys() on an ancestor won't have any affect on this
7416 // widget, so it needs an explicit hide_sys() of its own
7417 widget->d_func()->hide_sys();
7420 qApp->d_func()->sendSyntheticEnterLeave(widget);
7421 #ifndef QT_NO_ACCESSIBILITY
7423 QAccessibleEvent event(widget, QAccessible::ObjectHide);
7424 QAccessible::updateAccessibility(&event);
7430 bool QWidgetPrivate::close_helper(CloseMode mode)
7432 if (data.is_closing)
7436 data.is_closing = 1;
7438 QPointer<QWidget> that = q;
7439 QPointer<QWidget> parentWidget = q->parentWidget();
7441 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7442 if (mode != CloseNoEvent) {
7444 if (mode == CloseWithSpontaneousEvent)
7445 QApplication::sendSpontaneousEvent(q, &e);
7447 QApplication::sendEvent(q, &e);
7448 if (!that.isNull() && !e.isAccepted()) {
7449 data.is_closing = 0;
7454 if (!that.isNull() && !q->isHidden())
7457 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7458 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7461 /* if there is no non-withdrawn primary window left (except
7462 the ones without QuitOnClose), we emit the lastWindowClosed
7464 QWidgetList list = QApplication::topLevelWidgets();
7465 bool lastWindowClosed = true;
7466 for (int i = 0; i < list.size(); ++i) {
7467 QWidget *w = list.at(i);
7468 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7470 lastWindowClosed = false;
7473 if (lastWindowClosed) {
7474 QGuiApplicationPrivate::emitLastWindowClosed();
7475 QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
7476 applicationPrivate->maybeQuit();
7481 if (!that.isNull()) {
7482 data.is_closing = 0;
7483 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7484 q->setAttribute(Qt::WA_DeleteOnClose, false);
7493 Closes this widget. Returns true if the widget was closed;
7494 otherwise returns false.
7496 First it sends the widget a QCloseEvent. The widget is \link
7497 hide() hidden\endlink if it \link QCloseEvent::accept()
7498 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7499 ignores\endlink the event, nothing happens. The default
7500 implementation of QWidget::closeEvent() accepts the close event.
7502 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7503 is also deleted. A close events is delivered to the widget no
7504 matter if the widget is visible or not.
7506 The \l QApplication::lastWindowClosed() signal is emitted when the
7507 last visible primary window (i.e. window with no parent) with the
7508 Qt::WA_QuitOnClose attribute set is closed. By default this
7509 attribute is set for all widgets except transient windows such as
7510 splash screens, tool windows, and popup menus.
7514 bool QWidget::close()
7516 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7520 \property QWidget::visible
7521 \brief whether the widget is visible
7523 Calling setVisible(true) or show() sets the widget to visible
7524 status if all its parent widgets up to the window are visible. If
7525 an ancestor is not visible, the widget won't become visible until
7526 all its ancestors are shown. If its size or position has changed,
7527 Qt guarantees that a widget gets move and resize events just
7528 before it is shown. If the widget has not been resized yet, Qt
7529 will adjust the widget's size to a useful default using
7532 Calling setVisible(false) or hide() hides a widget explicitly. An
7533 explicitly hidden widget will never become visible, even if all
7534 its ancestors become visible, unless you show it.
7536 A widget receives show and hide events when its visibility status
7537 changes. Between a hide and a show event, there is no need to
7538 waste CPU cycles preparing or displaying information to the user.
7539 A video application, for example, might simply stop generating new
7542 A widget that happens to be obscured by other windows on the
7543 screen is considered to be visible. The same applies to iconified
7544 windows and windows that exist on another virtual
7545 desktop (on platforms that support this concept). A widget
7546 receives spontaneous show and hide events when its mapping status
7547 is changed by the window system, e.g. a spontaneous hide event
7548 when the user minimizes the window, and a spontaneous show event
7549 when the window is restored again.
7551 You almost never have to reimplement the setVisible() function. If
7552 you need to change some settings before a widget is shown, use
7553 showEvent() instead. If you need to do some delayed initialization
7554 use the Polish event delivered to the event() function.
7556 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7557 showEvent(), hideEvent()
7562 Returns true if this widget would become visible if \a ancestor is
7563 shown; otherwise returns false.
7565 The true case occurs if neither the widget itself nor any parent
7566 up to but excluding \a ancestor has been explicitly hidden.
7568 This function will still return true if the widget is obscured by
7569 other windows on the screen, but could be physically visible if it
7570 or they were to be moved.
7572 isVisibleTo(0) is identical to isVisible().
7574 \sa show() hide() isVisible()
7577 bool QWidget::isVisibleTo(const QWidget *ancestor) const
7581 const QWidget * w = this;
7582 while (!w->isHidden()
7584 && w->parentWidget()
7585 && w->parentWidget() != ancestor)
7586 w = w->parentWidget();
7587 return !w->isHidden();
7592 Returns the unobscured region where paint events can occur.
7594 For visible widgets, this is an approximation of the area not
7595 covered by other widgets; otherwise, this is an empty region.
7597 The repaint() function calls this function if necessary, so in
7598 general you do not need to call it.
7601 QRegion QWidget::visibleRegion() const
7605 QRect clipRect = d->clipRect();
7606 if (clipRect.isEmpty())
7608 QRegion r(clipRect);
7609 d->subtractOpaqueChildren(r, clipRect);
7610 d->subtractOpaqueSiblings(r);
7615 QSize QWidgetPrivate::adjustedSize() const
7619 QSize s = q->sizeHint();
7621 if (q->isWindow()) {
7622 Qt::Orientations exp;
7624 if (layout->hasHeightForWidth())
7625 s.setHeight(layout->totalHeightForWidth(s.width()));
7626 exp = layout->expandingDirections();
7629 if (q->sizePolicy().hasHeightForWidth())
7630 s.setHeight(q->heightForWidth(s.width()));
7631 exp = q->sizePolicy().expandingDirections();
7633 if (exp & Qt::Horizontal)
7634 s.setWidth(qMax(s.width(), 200));
7635 if (exp & Qt::Vertical)
7636 s.setHeight(qMax(s.height(), 100));
7637 #if defined(Q_WS_X11)
7638 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7640 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7642 #if defined (Q_OS_WINCE)
7643 s.setWidth(qMin(s.width(), screen.width()));
7644 s.setHeight(qMin(s.height(), screen.height()));
7646 s.setWidth(qMin(s.width(), screen.width()*2/3));
7647 s.setHeight(qMin(s.height(), screen.height()*2/3));
7649 if (QTLWExtra *extra = maybeTopData())
7650 extra->sizeAdjusted = true;
7654 QRect r = q->childrenRect(); // get children rectangle
7657 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7664 Adjusts the size of the widget to fit its contents.
7666 This function uses sizeHint() if it is valid, i.e., the size hint's width
7667 and height are \>= 0. Otherwise, it sets the size to the children
7668 rectangle that covers all child widgets (the union of all child widget
7671 For windows, the screen size is also taken into account. If the sizeHint()
7672 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7673 {expanding}, the window will be at least (200, 100). The maximum size of
7674 a window is 2/3 of the screen's width and height.
7676 \sa sizeHint(), childrenRect()
7679 void QWidget::adjustSize()
7683 QSize s = d->adjustedSize();
7686 d->layout->activate();
7694 \property QWidget::sizeHint
7695 \brief the recommended size for the widget
7697 If the value of this property is an invalid size, no size is
7700 The default implementation of sizeHint() returns an invalid size
7701 if there is no layout for this widget, and returns the layout's
7702 preferred size otherwise.
7704 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7705 setMinimumSize(), updateGeometry()
7708 QSize QWidget::sizeHint() const
7712 return d->layout->totalSizeHint();
7713 return QSize(-1, -1);
7717 \property QWidget::minimumSizeHint
7718 \brief the recommended minimum size for the widget
7720 If the value of this property is an invalid size, no minimum size
7723 The default implementation of minimumSizeHint() returns an invalid
7724 size if there is no layout for this widget, and returns the
7725 layout's minimum size otherwise. Most built-in widgets reimplement
7728 \l QLayout will never resize a widget to a size smaller than the
7729 minimum size hint unless minimumSize() is set or the size policy is
7730 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7731 size hint will be ignored.
7733 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7735 QSize QWidget::minimumSizeHint() const
7739 return d->layout->totalMinimumSize();
7740 return QSize(-1, -1);
7745 \fn QWidget *QWidget::parentWidget() const
7747 Returns the parent of this widget, or 0 if it does not have any
7753 Returns true if this widget is a parent, (or grandparent and so on
7754 to any level), of the given \a child, and both widgets are within
7755 the same window; otherwise returns false.
7758 bool QWidget::isAncestorOf(const QWidget *child) const
7763 if (child->isWindow())
7765 child = child->parentWidget();
7770 #if defined(Q_WS_WIN)
7771 inline void setDisabledStyle(QWidget *w, bool setStyle)
7773 // set/reset WS_DISABLED style.
7774 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7775 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7776 LONG newStyle = dwStyle;
7778 newStyle |= WS_DISABLED;
7780 newStyle &= ~WS_DISABLED;
7781 if (newStyle != dwStyle) {
7782 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7783 // we might need to repaint in some situations (eg. menu)
7790 /*****************************************************************************
7791 QWidget event handling
7792 *****************************************************************************/
7795 This is the main event handler; it handles event \a event. You can
7796 reimplement this function in a subclass, but we recommend using
7797 one of the specialized event handlers instead.
7799 Key press and release events are treated differently from other
7800 events. event() checks for Tab and Shift+Tab and tries to move the
7801 focus appropriately. If there is no widget to move the focus to
7802 (or the key press is not Tab or Shift+Tab), event() calls
7805 Mouse and tablet event handling is also slightly special: only
7806 when the widget is \l enabled, event() will call the specialized
7807 handlers such as mousePressEvent(); otherwise it will discard the
7810 This function returns true if the event was recognized, otherwise
7811 it returns false. If the recognized event was accepted (see \l
7812 QEvent::accepted), any further processing such as event
7813 propagation to the parent widget stops.
7815 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7816 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7817 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7818 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7819 QObject::event(), QObject::timerEvent()
7822 bool QWidget::event(QEvent *event)
7826 // ignore mouse events when disabled
7828 switch(event->type()) {
7829 case QEvent::TabletPress:
7830 case QEvent::TabletRelease:
7831 case QEvent::TabletMove:
7832 case QEvent::MouseButtonPress:
7833 case QEvent::MouseButtonRelease:
7834 case QEvent::MouseButtonDblClick:
7835 case QEvent::MouseMove:
7836 case QEvent::TouchBegin:
7837 case QEvent::TouchUpdate:
7838 case QEvent::TouchEnd:
7839 case QEvent::TouchCancel:
7840 case QEvent::ContextMenu:
7841 #ifndef QT_NO_WHEELEVENT
7849 switch (event->type()) {
7850 case QEvent::MouseMove:
7851 mouseMoveEvent((QMouseEvent*)event);
7854 case QEvent::MouseButtonPress:
7855 mousePressEvent((QMouseEvent*)event);
7858 case QEvent::MouseButtonRelease:
7859 mouseReleaseEvent((QMouseEvent*)event);
7862 case QEvent::MouseButtonDblClick:
7863 mouseDoubleClickEvent((QMouseEvent*)event);
7865 #ifndef QT_NO_WHEELEVENT
7867 wheelEvent((QWheelEvent*)event);
7870 #ifndef QT_NO_TABLETEVENT
7871 case QEvent::TabletMove:
7872 case QEvent::TabletPress:
7873 case QEvent::TabletRelease:
7874 tabletEvent((QTabletEvent*)event);
7877 case QEvent::KeyPress: {
7878 QKeyEvent *k = (QKeyEvent *)event;
7880 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7881 if (k->key() == Qt::Key_Backtab
7882 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7883 res = focusNextPrevChild(false);
7884 else if (k->key() == Qt::Key_Tab)
7885 res = focusNextPrevChild(true);
7890 #ifdef QT_KEYPAD_NAVIGATION
7891 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7892 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7893 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7894 if (k->key() == Qt::Key_Up)
7895 res = focusNextPrevChild(false);
7896 else if (k->key() == Qt::Key_Down)
7897 res = focusNextPrevChild(true);
7898 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7899 if (k->key() == Qt::Key_Up)
7900 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7901 else if (k->key() == Qt::Key_Right)
7902 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7903 else if (k->key() == Qt::Key_Down)
7904 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7905 else if (k->key() == Qt::Key_Left)
7906 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7914 #ifndef QT_NO_WHATSTHIS
7915 if (!k->isAccepted()
7916 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7917 && d->whatsThis.size()) {
7918 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7925 case QEvent::KeyRelease:
7926 keyReleaseEvent((QKeyEvent*)event);
7928 case QEvent::ShortcutOverride:
7931 case QEvent::InputMethod:
7932 inputMethodEvent((QInputMethodEvent *) event);
7935 case QEvent::InputMethodQuery:
7936 if (testAttribute(Qt::WA_InputMethodEnabled)) {
7937 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7938 Qt::InputMethodQueries queries = query->queries();
7939 for (uint i = 0; i < 32; ++i) {
7940 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7942 QVariant v = inputMethodQuery(q);
7943 if (q == Qt::ImEnabled && !v.isValid() && isEnabled())
7944 v = QVariant(true); // special case for Qt4 compatibility
7945 query->setValue(q, v);
7952 case QEvent::PolishRequest:
7956 case QEvent::Polish: {
7957 style()->polish(this);
7958 setAttribute(Qt::WA_WState_Polished);
7959 if (!QApplication::font(this).isCopyOf(QApplication::font()))
7961 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
7962 d->resolvePalette();
7966 case QEvent::ApplicationWindowIconChange:
7967 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
7968 d->setWindowIcon_sys();
7969 d->setWindowIcon_helper();
7972 case QEvent::FocusIn:
7973 #ifdef QT_SOFTKEYS_ENABLED
7974 QSoftKeyManager::updateSoftKeys();
7976 focusInEvent((QFocusEvent*)event);
7977 d->updateWidgetTransform();
7980 case QEvent::FocusOut:
7981 focusOutEvent((QFocusEvent*)event);
7985 #ifndef QT_NO_STATUSTIP
7986 if (d->statusTip.size()) {
7987 QStatusTipEvent tip(d->statusTip);
7988 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
7995 #ifndef QT_NO_STATUSTIP
7996 if (d->statusTip.size()) {
7998 QStatusTipEvent tip(empty);
7999 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8005 case QEvent::HoverEnter:
8006 case QEvent::HoverLeave:
8011 // At this point the event has to be delivered, regardless
8012 // whether the widget isVisible() or not because it
8013 // already went through the filters
8014 paintEvent((QPaintEvent*)event);
8018 moveEvent((QMoveEvent*)event);
8019 d->updateWidgetTransform();
8022 case QEvent::Resize:
8023 resizeEvent((QResizeEvent*)event);
8024 d->updateWidgetTransform();
8028 closeEvent((QCloseEvent *)event);
8031 #ifndef QT_NO_CONTEXTMENU
8032 case QEvent::ContextMenu:
8033 switch (data->context_menu_policy) {
8034 case Qt::PreventContextMenu:
8036 case Qt::DefaultContextMenu:
8037 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8039 case Qt::CustomContextMenu:
8040 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8043 case Qt::ActionsContextMenu:
8044 if (d->actions.count()) {
8045 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8056 #endif // QT_NO_CONTEXTMENU
8058 #ifndef QT_NO_DRAGANDDROP
8060 dropEvent((QDropEvent*) event);
8063 case QEvent::DragEnter:
8064 dragEnterEvent((QDragEnterEvent*) event);
8067 case QEvent::DragMove:
8068 dragMoveEvent((QDragMoveEvent*) event);
8071 case QEvent::DragLeave:
8072 dragLeaveEvent((QDragLeaveEvent*) event);
8077 showEvent((QShowEvent*) event);
8081 hideEvent((QHideEvent*) event);
8084 case QEvent::ShowWindowRequest:
8089 case QEvent::ApplicationFontChange:
8092 case QEvent::ApplicationPaletteChange:
8093 if (!(windowType() == Qt::Desktop))
8094 d->resolvePalette();
8097 case QEvent::ToolBarChange:
8098 case QEvent::ActivationChange:
8099 case QEvent::EnabledChange:
8100 case QEvent::FontChange:
8101 case QEvent::StyleChange:
8102 case QEvent::PaletteChange:
8103 case QEvent::WindowTitleChange:
8104 case QEvent::IconTextChange:
8105 case QEvent::ModifiedChange:
8106 case QEvent::MouseTrackingChange:
8107 case QEvent::ParentChange:
8108 case QEvent::WindowStateChange:
8109 case QEvent::LocaleChange:
8110 case QEvent::MacSizeChange:
8111 case QEvent::ContentsRectChange:
8112 case QEvent::ThemeChange:
8116 case QEvent::WindowActivate:
8117 case QEvent::WindowDeactivate: {
8118 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8120 QList<QObject*> childList = d->children;
8121 for (int i = 0; i < childList.size(); ++i) {
8122 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8123 if (w && w->isVisible() && !w->isWindow())
8124 QApplication::sendEvent(w, event);
8127 #ifdef QT_SOFTKEYS_ENABLED
8129 QSoftKeyManager::updateSoftKeys();
8134 case QEvent::LanguageChange:
8137 QList<QObject*> childList = d->children;
8138 for (int i = 0; i < childList.size(); ++i) {
8139 QObject *o = childList.at(i);
8141 QApplication::sendEvent(o, event);
8147 case QEvent::ApplicationLayoutDirectionChange:
8148 d->resolveLayoutDirection();
8151 case QEvent::LayoutDirectionChange:
8153 d->layout->invalidate();
8157 case QEvent::UpdateRequest:
8158 d->syncBackingStore();
8160 case QEvent::UpdateLater:
8161 update(static_cast<QUpdateLaterEvent*>(event)->region());
8164 case QEvent::WindowBlocked:
8165 case QEvent::WindowUnblocked:
8167 QList<QObject*> childList = d->children;
8168 for (int i = 0; i < childList.size(); ++i) {
8169 QObject *o = childList.at(i);
8170 if (o && o != QApplication::activeModalWidget()) {
8171 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8172 // do not forward the event to child windows,
8173 // QApplication does this for us
8176 QApplication::sendEvent(o, event);
8179 #if defined(Q_WS_WIN)
8180 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8184 #ifndef QT_NO_TOOLTIP
8185 case QEvent::ToolTip:
8186 if (!d->toolTip.isEmpty())
8187 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8192 #ifndef QT_NO_WHATSTHIS
8193 case QEvent::WhatsThis:
8194 if (d->whatsThis.size())
8195 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8199 case QEvent::QueryWhatsThis:
8200 if (d->whatsThis.isEmpty())
8204 case QEvent::EmbeddingControl:
8205 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8206 data->fstrut_dirty = false;
8207 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8208 d->topData()->embedded = 1;
8211 #ifndef QT_NO_ACTION
8212 case QEvent::ActionAdded:
8213 case QEvent::ActionRemoved:
8214 case QEvent::ActionChanged:
8215 #ifdef QT_SOFTKEYS_ENABLED
8216 QSoftKeyManager::updateSoftKeys();
8218 actionEvent((QActionEvent*)event);
8222 case QEvent::KeyboardLayoutChange:
8226 // inform children of the change
8227 QList<QObject*> childList = d->children;
8228 for (int i = 0; i < childList.size(); ++i) {
8229 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8230 if (w && w->isVisible() && !w->isWindow())
8231 QApplication::sendEvent(w, event);
8236 case QEvent::MacGLWindowChange:
8237 d->needWindowChange = false;
8240 case QEvent::TouchBegin:
8241 case QEvent::TouchUpdate:
8242 case QEvent::TouchEnd:
8243 case QEvent::TouchCancel:
8248 #ifndef QT_NO_GESTURES
8249 case QEvent::Gesture:
8253 #ifndef QT_NO_PROPERTIES
8254 case QEvent::DynamicPropertyChange: {
8255 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8256 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8257 uint value = property(propName.constData()).toUInt();
8260 const char axis = propName.at(12);
8262 d->extra->customDpiX = value;
8263 else if (axis == 'Y')
8264 d->extra->customDpiY = value;
8265 d->updateFont(d->data.fnt);
8271 return QObject::event(event);
8277 This event handler can be reimplemented to handle state changes.
8279 The state being changed in this event can be retrieved through the \a event
8282 Change events include: QEvent::ToolBarChange,
8283 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8284 QEvent::StyleChange, QEvent::PaletteChange,
8285 QEvent::WindowTitleChange, QEvent::IconTextChange,
8286 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8287 QEvent::ParentChange, QEvent::WindowStateChange,
8288 QEvent::LanguageChange, QEvent::LocaleChange,
8289 QEvent::LayoutDirectionChange.
8292 void QWidget::changeEvent(QEvent * event)
8294 switch(event->type()) {
8295 case QEvent::EnabledChange: {
8297 #ifndef QT_NO_ACCESSIBILITY
8298 QAccessible::State s;
8300 QAccessibleStateChangeEvent event(this, s);
8301 QAccessible::updateAccessibility(&event);
8306 case QEvent::FontChange:
8307 case QEvent::StyleChange: {
8312 d->layout->invalidate();
8316 case QEvent::PaletteChange:
8320 case QEvent::ThemeChange:
8321 if (QApplication::desktopSettingsAware() && windowType() != Qt::Desktop
8322 && qApp && !QApplication::closingDown()) {
8323 if (testAttribute(Qt::WA_WState_Polished))
8324 QApplication::style()->unpolish(this);
8325 if (testAttribute(Qt::WA_WState_Polished))
8326 QApplication::style()->polish(this);
8327 QEvent styleChangedEvent(QEvent::StyleChange);
8328 QCoreApplication::sendEvent(this, &styleChangedEvent);
8335 case QEvent::MacSizeChange:
8338 case QEvent::ToolTipChange:
8339 case QEvent::MouseTrackingChange:
8340 qt_mac_update_mouseTracking(this);
8350 This event handler, for event \a event, can be reimplemented in a
8351 subclass to receive mouse move events for the widget.
8353 If mouse tracking is switched off, mouse move events only occur if
8354 a mouse button is pressed while the mouse is being moved. If mouse
8355 tracking is switched on, mouse move events occur even if no mouse
8358 QMouseEvent::pos() reports the position of the mouse cursor,
8359 relative to this widget. For press and release events, the
8360 position is usually the same as the position of the last mouse
8361 move event, but it might be different if the user's hand shakes.
8362 This is a feature of the underlying window system, not Qt.
8364 If you want to show a tooltip immediately, while the mouse is
8365 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8366 and show them as a tooltip), you must first enable mouse tracking
8367 as described above. Then, to ensure that the tooltip is updated
8368 immediately, you must call QToolTip::showText() instead of
8369 setToolTip() in your implementation of mouseMoveEvent().
8371 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8372 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8375 void QWidget::mouseMoveEvent(QMouseEvent *event)
8381 This event handler, for event \a event, can be reimplemented in a
8382 subclass to receive mouse press events for the widget.
8384 If you create new widgets in the mousePressEvent() the
8385 mouseReleaseEvent() may not end up where you expect, depending on
8386 the underlying window system (or X11 window manager), the widgets'
8387 location and maybe more.
8389 The default implementation implements the closing of popup widgets
8390 when you click outside the window. For other widget types it does
8393 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8394 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8397 void QWidget::mousePressEvent(QMouseEvent *event)
8400 if ((windowType() == Qt::Popup)) {
8403 while ((w = QApplication::activePopupWidget()) && w != this){
8405 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8406 w->hide(); // hide at least
8408 if (!rect().contains(event->pos())){
8415 This event handler, for event \a event, can be reimplemented in a
8416 subclass to receive mouse release events for the widget.
8418 \sa mousePressEvent(), mouseDoubleClickEvent(),
8419 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8422 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8428 This event handler, for event \a event, can be reimplemented in a
8429 subclass to receive mouse double click events for the widget.
8431 The default implementation generates a normal mouse press event.
8433 \note The widget will also receive mouse press and mouse release
8434 events in addition to the double click event. It is up to the
8435 developer to ensure that the application interprets these events
8438 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8439 event(), QMouseEvent
8442 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8447 #ifndef QT_NO_WHEELEVENT
8449 This event handler, for event \a event, can be reimplemented in a
8450 subclass to receive wheel events for the widget.
8452 If you reimplement this handler, it is very important that you
8453 \link QWheelEvent ignore()\endlink the event if you do not handle
8454 it, so that the widget's parent can interpret it.
8456 The default implementation ignores the event.
8458 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8462 void QWidget::wheelEvent(QWheelEvent *event)
8466 #endif // QT_NO_WHEELEVENT
8468 #ifndef QT_NO_TABLETEVENT
8470 This event handler, for event \a event, can be reimplemented in a
8471 subclass to receive tablet events for the widget.
8473 If you reimplement this handler, it is very important that you
8474 \link QTabletEvent ignore()\endlink the event if you do not handle
8475 it, so that the widget's parent can interpret it.
8477 The default implementation ignores the event.
8479 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8483 void QWidget::tabletEvent(QTabletEvent *event)
8487 #endif // QT_NO_TABLETEVENT
8490 This event handler, for event \a event, can be reimplemented in a
8491 subclass to receive key press events for the widget.
8493 A widget must call setFocusPolicy() to accept focus initially and
8494 have focus in order to receive a key press event.
8496 If you reimplement this handler, it is very important that you
8497 call the base class implementation if you do not act upon the key.
8499 The default implementation closes popup widgets if the user
8500 presses Esc. Otherwise the event is ignored, so that the widget's
8501 parent can interpret it.
8503 Note that QKeyEvent starts with isAccepted() == true, so you do not
8504 need to call QKeyEvent::accept() - just do not call the base class
8505 implementation if you act upon the key.
8507 \sa keyReleaseEvent(), setFocusPolicy(),
8508 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8511 void QWidget::keyPressEvent(QKeyEvent *event)
8513 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8522 This event handler, for event \a event, can be reimplemented in a
8523 subclass to receive key release events for the widget.
8525 A widget must \link setFocusPolicy() accept focus\endlink
8526 initially and \link hasFocus() have focus\endlink in order to
8527 receive a key release event.
8529 If you reimplement this handler, it is very important that you
8530 call the base class implementation if you do not act upon the key.
8532 The default implementation ignores the event, so that the widget's
8533 parent can interpret it.
8535 Note that QKeyEvent starts with isAccepted() == true, so you do not
8536 need to call QKeyEvent::accept() - just do not call the base class
8537 implementation if you act upon the key.
8539 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8540 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8543 void QWidget::keyReleaseEvent(QKeyEvent *event)
8549 \fn void QWidget::focusInEvent(QFocusEvent *event)
8551 This event handler can be reimplemented in a subclass to receive
8552 keyboard focus events (focus received) for the widget. The event
8553 is passed in the \a event parameter
8555 A widget normally must setFocusPolicy() to something other than
8556 Qt::NoFocus in order to receive focus events. (Note that the
8557 application programmer can call setFocus() on any widget, even
8558 those that do not normally accept focus.)
8560 The default implementation updates the widget (except for windows
8561 that do not specify a focusPolicy()).
8563 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8564 keyReleaseEvent(), event(), QFocusEvent
8567 void QWidget::focusInEvent(QFocusEvent *)
8569 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8575 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8577 This event handler can be reimplemented in a subclass to receive
8578 keyboard focus events (focus lost) for the widget. The events is
8579 passed in the \a event parameter.
8581 A widget normally must setFocusPolicy() to something other than
8582 Qt::NoFocus in order to receive focus events. (Note that the
8583 application programmer can call setFocus() on any widget, even
8584 those that do not normally accept focus.)
8586 The default implementation updates the widget (except for windows
8587 that do not specify a focusPolicy()).
8589 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8590 keyReleaseEvent(), event(), QFocusEvent
8593 void QWidget::focusOutEvent(QFocusEvent *)
8595 if (focusPolicy() != Qt::NoFocus || !isWindow())
8600 \fn void QWidget::enterEvent(QEvent *event)
8602 This event handler can be reimplemented in a subclass to receive
8603 widget enter events which are passed in the \a event parameter.
8605 An event is sent to the widget when the mouse cursor enters the
8608 \sa leaveEvent(), mouseMoveEvent(), event()
8611 void QWidget::enterEvent(QEvent *)
8616 \fn void QWidget::leaveEvent(QEvent *event)
8618 This event handler can be reimplemented in a subclass to receive
8619 widget leave events which are passed in the \a event parameter.
8621 A leave event is sent to the widget when the mouse cursor leaves
8624 \sa enterEvent(), mouseMoveEvent(), event()
8627 void QWidget::leaveEvent(QEvent *)
8632 \fn void QWidget::paintEvent(QPaintEvent *event)
8634 This event handler can be reimplemented in a subclass to receive paint
8635 events passed in \a event.
8637 A paint event is a request to repaint all or part of a widget. It can
8638 happen for one of the following reasons:
8641 \li repaint() or update() was invoked,
8642 \li the widget was obscured and has now been uncovered, or
8643 \li many other reasons.
8646 Many widgets can simply repaint their entire surface when asked to, but
8647 some slow widgets need to optimize by painting only the requested region:
8648 QPaintEvent::region(). This speed optimization does not change the result,
8649 as painting is clipped to that region during event processing. QListView
8650 and QTableView do this, for example.
8652 Qt also tries to speed up painting by merging multiple paint events into
8653 one. When update() is called several times or the window system sends
8654 several paint events, Qt merges these events into one event with a larger
8655 region (see QRegion::united()). The repaint() function does not permit this
8656 optimization, so we suggest using update() whenever possible.
8658 When the paint event occurs, the update region has normally been erased, so
8659 you are painting on the widget's background.
8661 The background can be set using setBackgroundRole() and setPalette().
8663 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8664 is no need to write double-buffering code in paintEvent() to avoid flicker.
8666 \b{Note for the X11 platform}: It is possible to toggle global double
8667 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8669 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8671 \note Generally, you should refrain from calling update() or repaint()
8672 \b{inside} a paintEvent(). For example, calling update() or repaint() on
8673 children inside a paintevent() results in undefined behavior; the child may
8674 or may not get a paint event.
8676 \warning If you are using a custom paint engine without Qt's backingstore,
8677 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8678 never be called; the backingstore will be used instead.
8680 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8681 {Analog Clock Example}
8684 void QWidget::paintEvent(QPaintEvent *)
8690 \fn void QWidget::moveEvent(QMoveEvent *event)
8692 This event handler can be reimplemented in a subclass to receive
8693 widget move events which are passed in the \a event parameter.
8694 When the widget receives this event, it is already at the new
8697 The old position is accessible through QMoveEvent::oldPos().
8699 \sa resizeEvent(), event(), move(), QMoveEvent
8702 void QWidget::moveEvent(QMoveEvent *)
8708 This event handler can be reimplemented in a subclass to receive
8709 widget resize events which are passed in the \a event parameter.
8710 When resizeEvent() is called, the widget already has its new
8711 geometry. The old size is accessible through
8712 QResizeEvent::oldSize().
8714 The widget will be erased and receive a paint event immediately
8715 after processing the resize event. No drawing need be (or should
8716 be) done inside this handler.
8719 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8723 void QWidget::resizeEvent(QResizeEvent * /* event */)
8727 #ifndef QT_NO_ACTION
8729 \fn void QWidget::actionEvent(QActionEvent *event)
8731 This event handler is called with the given \a event whenever the
8732 widget's actions are changed.
8734 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8736 void QWidget::actionEvent(QActionEvent *)
8743 This event handler is called with the given \a event when Qt receives a window
8744 close request for a top-level widget from the window system.
8746 By default, the event is accepted and the widget is closed. You can reimplement
8747 this function to change the way the widget responds to window close requests.
8748 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8751 Main window applications typically use reimplementations of this function to check
8752 whether the user's work has been saved and ask for permission before closing.
8753 For example, the \l{Application Example} uses a helper function to determine whether
8754 or not to close the window:
8756 \snippet mainwindows/application/mainwindow.cpp 3
8757 \snippet mainwindows/application/mainwindow.cpp 4
8759 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8762 void QWidget::closeEvent(QCloseEvent *event)
8767 #ifndef QT_NO_CONTEXTMENU
8769 This event handler, for event \a event, can be reimplemented in a
8770 subclass to receive widget context menu events.
8772 The handler is called when the widget's \l contextMenuPolicy is
8773 Qt::DefaultContextMenu.
8775 The default implementation ignores the context event.
8776 See the \l QContextMenuEvent documentation for more details.
8778 \sa event(), QContextMenuEvent customContextMenuRequested()
8781 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8785 #endif // QT_NO_CONTEXTMENU
8789 This event handler, for event \a event, can be reimplemented in a
8790 subclass to receive Input Method composition events. This handler
8791 is called when the state of the input method changes.
8793 Note that when creating custom text editing widgets, the
8794 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8795 (using the setAttribute() function) in order to receive input
8798 The default implementation calls event->ignore(), which rejects the
8799 Input Method event. See the \l QInputMethodEvent documentation for more
8802 \sa event(), QInputMethodEvent
8804 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8810 This method is only relevant for input widgets. It is used by the
8811 input method to query a set of properties of the widget to be
8812 able to support complex input method operations as support for
8813 surrounding text and reconversions.
8815 \a query specifies which property is queried.
8817 \sa inputMethodEvent(), QInputMethodEven, inputMethodHints
8819 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8822 case Qt::ImCursorRectangle:
8823 return QRect(width()/2, 0, 1, height());
8826 case Qt::ImAnchorPosition:
8828 return inputMethodQuery(Qt::ImCursorPosition);
8830 return (int)inputMethodHints();
8837 \property QWidget::inputMethodHints
8838 \brief What input method specific hints the widget has.
8840 This is only relevant for input widgets. It is used by
8841 the input method to retrieve hints as to how the input method
8842 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8843 is set, the input method may change its visual components to reflect
8844 that only numbers can be entered.
8846 \note The flags are only hints, so the particular input method
8847 implementation is free to ignore them. If you want to be
8848 sure that a certain type of characters are entered,
8849 you should also set a QValidator on the widget.
8851 The default value is Qt::ImhNone.
8855 \sa inputMethodQuery()
8857 Qt::InputMethodHints QWidget::inputMethodHints() const
8860 const QWidgetPrivate *priv = d_func();
8861 while (priv->inheritsInputMethodHints) {
8862 priv = priv->q_func()->parentWidget()->d_func();
8865 return priv->imHints;
8871 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8876 qApp->inputMethod()->update(Qt::ImHints);
8881 #ifndef QT_NO_DRAGANDDROP
8884 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8886 This event handler is called when a drag is in progress and the
8887 mouse enters this widget. The event is passed in the \a event parameter.
8889 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8892 See the \link dnd.html Drag-and-drop documentation\endlink for an
8893 overview of how to provide drag-and-drop in your application.
8895 \sa QDrag, QDragEnterEvent
8897 void QWidget::dragEnterEvent(QDragEnterEvent *)
8902 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8904 This event handler is called if a drag is in progress, and when
8905 any of the following conditions occur: the cursor enters this widget,
8906 the cursor moves within this widget, or a modifier key is pressed on
8907 the keyboard while this widget has the focus. The event is passed
8908 in the \a event parameter.
8910 See the \link dnd.html Drag-and-drop documentation\endlink for an
8911 overview of how to provide drag-and-drop in your application.
8913 \sa QDrag, QDragMoveEvent
8915 void QWidget::dragMoveEvent(QDragMoveEvent *)
8920 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
8922 This event handler is called when a drag is in progress and the
8923 mouse leaves this widget. The event is passed in the \a event
8926 See the \link dnd.html Drag-and-drop documentation\endlink for an
8927 overview of how to provide drag-and-drop in your application.
8929 \sa QDrag, QDragLeaveEvent
8931 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
8936 \fn void QWidget::dropEvent(QDropEvent *event)
8938 This event handler is called when the drag is dropped on this
8939 widget. The event is passed in the \a event parameter.
8941 See the \link dnd.html Drag-and-drop documentation\endlink for an
8942 overview of how to provide drag-and-drop in your application.
8944 \sa QDrag, QDropEvent
8946 void QWidget::dropEvent(QDropEvent *)
8950 #endif // QT_NO_DRAGANDDROP
8953 \fn void QWidget::showEvent(QShowEvent *event)
8955 This event handler can be reimplemented in a subclass to receive
8956 widget show events which are passed in the \a event parameter.
8958 Non-spontaneous show events are sent to widgets immediately
8959 before they are shown. The spontaneous show events of windows are
8960 delivered afterwards.
8962 Note: A widget receives spontaneous show and hide events when its
8963 mapping status is changed by the window system, e.g. a spontaneous
8964 hide event when the user minimizes the window, and a spontaneous
8965 show event when the window is restored again. After receiving a
8966 spontaneous hide event, a widget is still considered visible in
8967 the sense of isVisible().
8969 \sa visible, event(), QShowEvent
8971 void QWidget::showEvent(QShowEvent *)
8976 \fn void QWidget::hideEvent(QHideEvent *event)
8978 This event handler can be reimplemented in a subclass to receive
8979 widget hide events. The event is passed in the \a event parameter.
8981 Hide events are sent to widgets immediately after they have been
8984 Note: A widget receives spontaneous show and hide events when its
8985 mapping status is changed by the window system, e.g. a spontaneous
8986 hide event when the user minimizes the window, and a spontaneous
8987 show event when the window is restored again. After receiving a
8988 spontaneous hide event, a widget is still considered visible in
8989 the sense of isVisible().
8991 \sa visible, event(), QHideEvent
8993 void QWidget::hideEvent(QHideEvent *)
8998 This special event handler can be reimplemented in a subclass to
8999 receive native platform events identified by \a eventType
9000 which are passed in the \a message parameter.
9002 In your reimplementation of this function, if you want to stop the
9003 event being handled by Qt, return true and set \a result.
9004 If you return false, this native event is passed back to Qt,
9005 which translates the event into a Qt event and sends it to the widget.
9007 \note Events are only delivered to this event handler if the widget is
9008 has a native Window handle.
9010 \note This function superseedes the event filter functions
9011 x11Event(), winEvent() and macEvent() of Qt 4.
9014 \header \li Platform \li Event Type Identifier \li Message Type \li Result Type
9015 \row \li Windows \li "windows_generic_MSG" \li MSG * \li LRESULT
9019 bool QWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
9021 Q_UNUSED(eventType);
9028 Ensures that the widget has been polished by QStyle (i.e., has a
9029 proper font and palette).
9031 QWidget calls this function after it has been fully constructed
9032 but before it is shown the very first time. You can call this
9033 function if you want to ensure that the widget is polished before
9034 doing an operation, e.g., the correct font size might be needed in
9035 the widget's sizeHint() reimplementation. Note that this function
9036 \e is called from the default implementation of sizeHint().
9038 Polishing is useful for final initialization that must happen after
9039 all constructors (from base classes as well as from subclasses)
9042 If you need to change some settings when a widget is polished,
9043 reimplement event() and handle the QEvent::Polish event type.
9045 \b{Note:} The function is declared const so that it can be called from
9046 other const functions (e.g., sizeHint()).
9050 void QWidget::ensurePolished() const
9054 const QMetaObject *m = metaObject();
9055 if (m == d->polished)
9059 QEvent e(QEvent::Polish);
9060 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9062 // polish children after 'this'
9063 QList<QObject*> children = d->children;
9064 for (int i = 0; i < children.size(); ++i) {
9065 QObject *o = children.at(i);
9066 if(!o->isWidgetType())
9068 if (QWidget *w = qobject_cast<QWidget *>(o))
9069 w->ensurePolished();
9072 if (d->parent && d->sendChildEvents) {
9073 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9074 QCoreApplication::sendEvent(d->parent, &e);
9076 if (d->extra && d->extra->topextra && d->extra->topextra->window
9077 && d->extra->topextra->window->objectName().isEmpty()) {
9078 QString on = objectName();
9080 on = QString::fromUtf8(metaObject()->className());
9081 on += QStringLiteral("Class");
9083 on += QStringLiteral("Window");
9084 d->extra->topextra->window->setObjectName(on);
9089 Returns the mask currently set on a widget. If no mask is set the
9090 return value will be an empty region.
9092 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9094 QRegion QWidget::mask() const
9097 return d->extra ? d->extra->mask : QRegion();
9101 Returns the layout manager that is installed on this widget, or 0
9102 if no layout manager is installed.
9104 The layout manager sets the geometry of the widget's children
9105 that have been added to the layout.
9107 \sa setLayout(), sizePolicy(), {Layout Management}
9109 QLayout *QWidget::layout() const
9111 return d_func()->layout;
9116 \fn void QWidget::setLayout(QLayout *layout)
9118 Sets the layout manager for this widget to \a layout.
9120 If there already is a layout manager installed on this widget,
9121 QWidget won't let you install another. You must first delete the
9122 existing layout manager (returned by layout()) before you can
9123 call setLayout() with the new layout.
9125 If \a layout is the layout manger on a different widget, setLayout()
9126 will reparent the layout and make it the layout manager for this widget.
9130 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9132 An alternative to calling this function is to pass this widget to
9133 the layout's constructor.
9135 The QWidget will take ownership of \a layout.
9137 \sa layout(), {Layout Management}
9140 void QWidget::setLayout(QLayout *l)
9143 qWarning("QWidget::setLayout: Cannot set layout to 0");
9148 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9149 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9150 objectName().toLocal8Bit().data());
9154 QObject *oldParent = l->parent();
9155 if (oldParent && oldParent != this) {
9156 if (oldParent->isWidgetType()) {
9157 // Steal the layout off a widget parent. Takes effect when
9158 // morphing laid-out container widgets in Designer.
9159 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9160 oldParentWidget->takeLayout();
9162 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9163 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9164 objectName().toLocal8Bit().data());
9170 l->d_func()->topLevel = true;
9172 if (oldParent != this) {
9174 l->d_func()->reparentChildWidgets(this);
9178 if (isWindow() && d->maybeTopData())
9179 d->topData()->sizeAdjusted = false;
9183 \fn QLayout *QWidget::takeLayout()
9185 Remove the layout from the widget.
9189 QLayout *QWidget::takeLayout()
9192 QLayout *l = layout();
9201 \property QWidget::sizePolicy
9202 \brief the default layout behavior of the widget
9204 If there is a QLayout that manages this widget's children, the
9205 size policy specified by that layout is used. If there is no such
9206 QLayout, the result of this function is used.
9208 The default policy is Preferred/Preferred, which means that the
9209 widget can be freely resized, but prefers to be the size
9210 sizeHint() returns. Button-like widgets set the size policy to
9211 specify that they may stretch horizontally, but are fixed
9212 vertically. The same applies to lineedit controls (such as
9213 QLineEdit, QSpinBox or an editable QComboBox) and other
9214 horizontally orientated widgets (such as QProgressBar).
9215 QToolButton's are normally square, so they allow growth in both
9216 directions. Widgets that support different directions (such as
9217 QSlider, QScrollBar or QHeader) specify stretching in the
9218 respective direction only. Widgets that can provide scroll bars
9219 (usually subclasses of QScrollArea) tend to specify that they can
9220 use additional space, and that they can make do with less than
9223 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9225 QSizePolicy QWidget::sizePolicy() const
9228 return d->size_policy;
9231 void QWidget::setSizePolicy(QSizePolicy policy)
9234 setAttribute(Qt::WA_WState_OwnSizePolicy);
9235 if (policy == d->size_policy)
9237 d->size_policy = policy;
9239 #ifndef QT_NO_GRAPHICSVIEW
9240 if (QWExtra *extra = d->extra) {
9241 if (extra->proxyWidget)
9242 extra->proxyWidget->setSizePolicy(policy);
9248 if (isWindow() && d->maybeTopData())
9249 d->topData()->sizeAdjusted = false;
9253 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9256 Sets the size policy of the widget to \a horizontal and \a
9257 vertical, with standard stretch and no height-for-width.
9259 \sa QSizePolicy::QSizePolicy()
9263 Returns the preferred height for this widget, given the width \a w.
9265 If this widget has a layout, the default implementation returns
9266 the layout's preferred height. if there is no layout, the default
9267 implementation returns -1 indicating that the preferred height
9268 does not depend on the width.
9271 int QWidget::heightForWidth(int w) const
9273 if (layout() && layout()->hasHeightForWidth())
9274 return layout()->totalHeightForWidth(w);
9282 Returns true if the widget's preferred height depends on its width; otherwise returns false.
9284 bool QWidget::hasHeightForWidth() const
9287 return d->layout ? d->layout->hasHeightForWidth() : d->size_policy.hasHeightForWidth();
9291 \fn QWidget *QWidget::childAt(int x, int y) const
9293 Returns the visible child widget at the position (\a{x}, \a{y})
9294 in the widget's coordinate system. If there is no visible child
9295 widget at the specified position, the function returns 0.
9301 Returns the visible child widget at point \a p in the widget's own
9305 QWidget *QWidget::childAt(const QPoint &p) const
9307 return d_func()->childAt_helper(p, false);
9310 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9312 if (children.isEmpty())
9317 // Unified tool bars on the Mac require special handling since they live outside
9318 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9319 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9320 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9322 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9325 if (!pointInsideRectAndMask(p))
9327 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9330 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9333 Q_UNUSED(includeFrame);
9335 for (int i = children.size() - 1; i >= 0; --i) {
9336 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9337 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9338 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9342 // Map the point 'p' from parent coordinates to child coordinates.
9343 QPoint childPoint = p;
9345 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9346 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9347 // QWidget::mapFromParent won't do the trick.
9348 if (includeFrame && qobject_cast<QToolBar *>(child))
9349 childPoint = qt_mac_nativeMapFromParent(child, p);
9352 childPoint -= child->data->crect.topLeft();
9354 // Check if the point hits the child.
9355 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9358 // Do the same for the child's descendants.
9359 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9362 // We have found our target; namely the child at position 'p'.
9368 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9372 widgetItem->invalidateSizeCache();
9374 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9375 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9376 if (parent->d_func()->layout)
9377 parent->d_func()->layout->invalidate();
9378 else if (parent->isVisible())
9379 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9385 Notifies the layout system that this widget has changed and may
9386 need to change geometry.
9388 Call this function if the sizeHint() or sizePolicy() have changed.
9390 For explicitly hidden widgets, updateGeometry() is a no-op. The
9391 layout system will be notified as soon as the widget is shown.
9394 void QWidget::updateGeometry()
9397 d->updateGeometry_helper(false);
9400 /*! \property QWidget::windowFlags
9402 Window flags are a combination of a type (e.g. Qt::Dialog) and
9403 zero or more hints to the window system (e.g.
9404 Qt::FramelessWindowHint).
9406 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9407 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9408 0) on the desktop. If the widget is a window and becomes a
9409 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9410 relative to its parent widget.
9412 \note This function calls setParent() when changing the flags for
9413 a window, causing the widget to be hidden. You must call show() to make
9414 the widget visible again..
9416 \sa windowType(), {Window Flags Example}
9418 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9420 if (data->window_flags == flags)
9425 if ((data->window_flags | flags) & Qt::Window) {
9426 // the old type was a window and/or the new type is a window
9427 QPoint oldPos = pos();
9428 bool visible = isVisible();
9429 setParent(parentWidget(), flags);
9431 // if both types are windows or neither of them are, we restore
9433 if (!((data->window_flags ^ flags) & Qt::Window)
9434 && (visible || testAttribute(Qt::WA_Moved))) {
9437 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9438 d->adjustQuitOnCloseAttribute();
9440 data->window_flags = flags;
9445 Sets the window flags for the widget to \a flags,
9446 \e without telling the window system.
9448 \warning Do not call this function unless you really know what
9451 \sa setWindowFlags()
9453 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9455 data->window_flags = flags;
9459 \fn Qt::WindowType QWidget::windowType() const
9461 Returns the window type of this widget. This is identical to
9462 windowFlags() & Qt::WindowType_Mask.
9468 Sets the parent of the widget to \a parent, and resets the window
9469 flags. The widget is moved to position (0, 0) in its new parent.
9471 If the new parent widget is in a different window, the
9472 reparented widget and its children are appended to the end of the
9473 \l{setFocusPolicy()}{tab chain} of the new parent
9474 widget, in the same internal order as before. If one of the moved
9475 widgets had keyboard focus, setParent() calls clearFocus() for that
9478 If the new parent widget is in the same window as the
9479 old parent, setting the parent doesn't change the tab order or
9482 If the "new" parent widget is the old parent widget, this function
9485 \note The widget becomes invisible as part of changing its parent,
9486 even if it was previously visible. You must call show() to make the
9487 widget visible again.
9489 \warning It is very unlikely that you will ever need this
9490 function. If you have a widget that changes its content
9491 dynamically, it is far easier to use \l QStackedWidget.
9493 \sa setWindowFlags()
9495 void QWidget::setParent(QWidget *parent)
9497 if (parent == parentWidget())
9499 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9505 This function also takes widget flags, \a f as an argument.
9508 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9511 d->inSetParent = true;
9512 bool resized = testAttribute(Qt::WA_Resized);
9513 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9514 QWidget *oldtlw = window();
9516 QWidget *desktopWidget = 0;
9517 if (parent && parent->windowType() == Qt::Desktop)
9518 desktopWidget = parent;
9519 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9521 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC)
9522 if (newParent && parent && !desktopWidget) {
9523 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9525 // On Mac, toolbars inside the unified title bar will never overlap with
9526 // siblings in the content view. So we skip enforce native siblings in that case
9527 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9530 parent->d_func()->enforceNativeChildren();
9531 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9532 setAttribute(Qt::WA_NativeWindow);
9537 if (!testAttribute(Qt::WA_WState_Hidden)) {
9539 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9542 QEvent e(QEvent::ParentAboutToChange);
9543 QApplication::sendEvent(this, &e);
9546 if (newParent && isAncestorOf(focusWidget()))
9547 focusWidget()->clearFocus();
9549 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9550 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9552 d->setParent_sys(parent, f);
9554 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9555 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9556 if (oldBsTracker && oldBsTracker != bsTracker)
9557 oldBsTracker->unregisterWidgetSubtree(this);
9562 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9564 oldBs->removeDirtyWidget(this);
9565 // Move the widget and all its static children from
9566 // the old backing store to the new one.
9567 oldBs->moveStaticWidgets(this);
9570 if (QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation) && !testAttribute(Qt::WA_WState_Created))
9573 d->reparentFocusWidgets(oldtlw);
9574 setAttribute(Qt::WA_Resized, resized);
9575 if (!testAttribute(Qt::WA_StyleSheet)
9576 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9578 d->resolvePalette();
9580 d->resolveLayoutDirection();
9583 // Note: GL widgets under WGL or EGL will always need a ParentChange
9584 // event to handle recreation/rebinding of the GL context, hence the
9585 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9588 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9589 || (f & Qt::MSWindowsOwnDC)
9592 // propagate enabled updates enabled state to non-windows
9594 if (!testAttribute(Qt::WA_ForceDisabled))
9595 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9596 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9597 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9601 // send and post remaining QObject events
9602 if (parent && d->sendChildEvents) {
9603 QChildEvent e(QEvent::ChildAdded, this);
9604 QApplication::sendEvent(parent, &e);
9607 //### already hidden above ---> must probably do something smart on the mac
9609 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9610 // if(!qt_mac_is_macdrawer(q)) //special case
9611 // q->setAttribute(Qt::WA_WState_Hidden);
9613 // q->setAttribute(Qt::WA_WState_Hidden);
9616 if (parent && d->sendChildEvents && d->polished) {
9617 QChildEvent e(QEvent::ChildPolished, this);
9618 QCoreApplication::sendEvent(parent, &e);
9621 QEvent e(QEvent::ParentChange);
9622 QApplication::sendEvent(this, &e);
9626 if (isWindow() || parentWidget()->isVisible())
9627 setAttribute(Qt::WA_WState_Hidden, true);
9628 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9629 setAttribute(Qt::WA_WState_Hidden, false);
9632 d->updateIsOpaque();
9634 #ifndef QT_NO_GRAPHICSVIEW
9635 // Embed the widget into a proxy if the parent is embedded.
9636 // ### Doesn't handle reparenting out of an embedded widget.
9637 if (oldtlw->graphicsProxyWidget()) {
9638 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9639 ancestorProxy->d_func()->unembedSubWindow(this);
9641 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9642 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9643 ancestorProxy->d_func()->embedSubWindow(this);
9647 d->inSetParent = false;
9651 Scrolls the widget including its children \a dx pixels to the
9652 right and \a dy downward. Both \a dx and \a dy may be negative.
9654 After scrolling, the widgets will receive paint events for
9655 the areas that need to be repainted. For widgets that Qt knows to
9656 be opaque, this is only the newly exposed parts.
9657 For example, if an opaque widget is scrolled 8 pixels to the left,
9658 only an 8-pixel wide stripe at the right edge needs updating.
9660 Since widgets propagate the contents of their parents by default,
9661 you need to set the \l autoFillBackground property, or use
9662 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9665 For widgets that use contents propagation, a scroll will cause an
9666 update of the entire scroll area.
9668 \sa {Transparency and Double Buffering}
9671 void QWidget::scroll(int dx, int dy)
9673 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9675 if (dx == 0 && dy == 0)
9678 #ifndef QT_NO_GRAPHICSVIEW
9679 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9680 // Graphics View maintains its own dirty region as a list of rects;
9681 // until we can connect item updates directly to the view, we must
9682 // separately add a translated dirty region.
9683 if (!d->dirty.isEmpty()) {
9684 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9685 proxy->update(rect);
9687 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9691 d->setDirtyOpaqueRegion();
9692 d->scroll_sys(dx, dy);
9698 This version only scrolls \a r and does not move the children of
9701 If \a r is empty or invalid, the result is undefined.
9705 void QWidget::scroll(int dx, int dy, const QRect &r)
9708 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9710 if (dx == 0 && dy == 0)
9713 #ifndef QT_NO_GRAPHICSVIEW
9714 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9715 // Graphics View maintains its own dirty region as a list of rects;
9716 // until we can connect item updates directly to the view, we must
9717 // separately add a translated dirty region.
9718 if (!d->dirty.isEmpty()) {
9719 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9720 proxy->update(rect);
9722 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9726 d->scroll_sys(dx, dy, r);
9730 Repaints the widget directly by calling paintEvent() immediately,
9731 unless updates are disabled or the widget is hidden.
9733 We suggest only using repaint() if you need an immediate repaint,
9734 for example during animation. In almost all circumstances update()
9735 is better, as it permits Qt to optimize for speed and minimize
9738 \warning If you call repaint() in a function which may itself be
9739 called from paintEvent(), you may get infinite recursion. The
9740 update() function never causes recursion.
9742 \sa update(), paintEvent(), setUpdatesEnabled()
9745 void QWidget::repaint()
9752 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9755 If \a w is negative, it is replaced with \c{width() - x}, and if
9756 \a h is negative, it is replaced width \c{height() - y}.
9758 void QWidget::repaint(int x, int y, int w, int h)
9760 if (x > data->crect.width() || y > data->crect.height())
9764 w = data->crect.width() - x;
9766 h = data->crect.height() - y;
9768 repaint(QRect(x, y, w, h));
9773 This version repaints a rectangle \a rect inside the widget.
9775 void QWidget::repaint(const QRect &rect)
9779 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9784 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9787 if (hasBackingStoreSupport()) {
9789 if (qt_widget_private(this)->isInUnifiedToolbar) {
9790 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9794 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9795 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9796 tlwExtra->inRepaint = true;
9797 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9798 tlwExtra->inRepaint = false;
9801 d->repaint_sys(rect);
9808 This version repaints a region \a rgn inside the widget.
9810 void QWidget::repaint(const QRegion &rgn)
9814 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9819 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9822 if (hasBackingStoreSupport()) {
9824 if (qt_widget_private(this)->isInUnifiedToolbar) {
9825 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9829 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9830 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9831 tlwExtra->inRepaint = true;
9832 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
9833 tlwExtra->inRepaint = false;
9836 d->repaint_sys(rgn);
9841 Updates the widget unless updates are disabled or the widget is
9844 This function does not cause an immediate repaint; instead it
9845 schedules a paint event for processing when Qt returns to the main
9846 event loop. This permits Qt to optimize for more speed and less
9847 flicker than a call to repaint() does.
9849 Calling update() several times normally results in just one
9852 Qt normally erases the widget's area before the paintEvent() call.
9853 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
9854 responsible for painting all its pixels with an opaque color.
9856 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
9858 void QWidget::update()
9863 /*! \fn void QWidget::update(int x, int y, int w, int h)
9866 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
9873 This version updates a rectangle \a rect inside the widget.
9875 void QWidget::update(const QRect &rect)
9877 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9880 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9881 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
9885 if (hasBackingStoreSupport()) {
9887 if (qt_widget_private(this)->isInUnifiedToolbar) {
9888 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9892 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9893 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9894 tlwExtra->backingStoreTracker->markDirty(rect, this);
9896 d_func()->repaint_sys(rect);
9903 This version repaints a region \a rgn inside the widget.
9905 void QWidget::update(const QRegion &rgn)
9907 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9910 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
9911 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
9915 if (hasBackingStoreSupport()) {
9917 if (qt_widget_private(this)->isInUnifiedToolbar) {
9918 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9922 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9923 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
9924 tlwExtra->backingStoreTracker->markDirty(rgn, this);
9926 d_func()->repaint_sys(rgn);
9934 This just sets the corresponding attribute bit to 1 or 0
9936 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
9939 if (attribute < int(8*sizeof(uint))) {
9941 data->widget_attributes |= (1<<attribute);
9943 data->widget_attributes &= ~(1<<attribute);
9945 const int x = attribute - 8*sizeof(uint);
9946 const int int_off = x / (8*sizeof(uint));
9948 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
9950 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
9955 Sets the attribute \a attribute on this widget if \a on is true;
9956 otherwise clears the attribute.
9960 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
9962 if (testAttribute(attribute) == on)
9966 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
9967 "QWidget::setAttribute(WidgetAttribute, bool)",
9968 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
9970 // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
9971 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
9972 // see qwidget_win.cpp, ::paintEngine for details
9974 if (d->noPaintOnScreen)
9979 setAttribute_internal(attribute, on, data, d);
9981 switch (attribute) {
9983 #ifndef QT_NO_DRAGANDDROP
9984 case Qt::WA_AcceptDrops: {
9985 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
9986 setAttribute(Qt::WA_DropSiteRegistered, true);
9987 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
9988 setAttribute(Qt::WA_DropSiteRegistered, false);
9989 QEvent e(QEvent::AcceptDropsChange);
9990 QApplication::sendEvent(this, &e);
9993 case Qt::WA_DropSiteRegistered: {
9994 d->registerDropSite(on);
9995 for (int i = 0; i < d->children.size(); ++i) {
9996 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
9997 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
9998 w->setAttribute(Qt::WA_DropSiteRegistered, on);
10004 case Qt::WA_NoChildEventsForParent:
10005 d->sendChildEvents = !on;
10007 case Qt::WA_NoChildEventsFromChildren:
10008 d->receiveChildEvents = !on;
10010 case Qt::WA_MacBrushedMetal:
10012 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
10013 // fall through since changing the metal attribute affects the opaque size grip.
10014 case Qt::WA_MacOpaqueSizeGrip:
10015 d->macUpdateOpaqueSizeGrip();
10017 case Qt::WA_MacShowFocusRect:
10024 qt_mac_update_mouseTracking(this);
10027 case Qt::WA_MacAlwaysShowToolWindow:
10029 d->macUpdateHideOnSuspend();
10032 case Qt::WA_MacNormalSize:
10033 case Qt::WA_MacSmallSize:
10034 case Qt::WA_MacMiniSize:
10037 // We can only have one of these set at a time
10038 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10039 Qt::WA_MacMiniSize };
10040 for (int i = 0; i < 3; ++i) {
10041 if (MacSizes[i] != attribute)
10042 setAttribute_internal(MacSizes[i], false, data, d);
10044 d->macUpdateSizeAttribute();
10048 case Qt::WA_ShowModal:
10051 QApplicationPrivate::leaveModal(this);
10052 // reset modality type to Modeless when clearing WA_ShowModal
10053 data->window_modality = Qt::NonModal;
10054 } else if (data->window_modality == Qt::NonModal) {
10055 // determine the modality type if it hasn't been set prior
10056 // to setting WA_ShowModal. set the default to WindowModal
10057 // if we are the child of a group leader; otherwise use
10058 // ApplicationModal.
10059 QWidget *w = parentWidget();
10062 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10063 w = w->parentWidget();
10067 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10069 : Qt::ApplicationModal;
10070 // Some window managers does not allow us to enter modal after the
10071 // window is showing. Therefore, to be consistent, we cannot call
10072 // QApplicationPrivate::enterModal(this) here. The window must be
10073 // hidden before changing modality.
10075 if (testAttribute(Qt::WA_WState_Created)) {
10076 // don't call setModal_sys() before create_sys()
10080 case Qt::WA_MouseTracking: {
10081 QEvent e(QEvent::MouseTrackingChange);
10082 QApplication::sendEvent(this, &e);
10084 case Qt::WA_NativeWindow: {
10085 d->createTLExtra();
10087 QWidget *focusWidget = d->effectiveFocusWidget();
10088 if (on && !internalWinId() && hasFocus()
10089 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10090 qApp->inputMethod()->reset();
10091 qApp->inputMethod()->update(Qt::ImEnabled);
10093 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10095 // On Mac, toolbars inside the unified title bar will never overlap with
10096 // siblings in the content view. So we skip enforce native siblings in that case
10097 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10100 parentWidget()->d_func()->enforceNativeChildren();
10101 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10103 if (isEnabled() && focusWidget->isEnabled()
10104 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10105 qApp->inputMethod()->update(Qt::ImEnabled);
10110 case Qt::WA_PaintOnScreen:
10111 d->updateIsOpaque();
10112 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC)
10113 // Recreate the widget if it's already created as an alien widget and
10114 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10115 // So must their children.
10117 setAttribute(Qt::WA_NativeWindow);
10118 d->enforceNativeChildren();
10122 case Qt::WA_OpaquePaintEvent:
10123 d->updateIsOpaque();
10125 case Qt::WA_NoSystemBackground:
10126 d->updateIsOpaque();
10128 case Qt::WA_UpdatesDisabled:
10129 d->updateSystemBackground();
10131 case Qt::WA_TransparentForMouseEvents:
10133 d->macUpdateIgnoreMouseEvents();
10136 case Qt::WA_InputMethodEnabled: {
10138 if (qApp->focusObject() == this) {
10140 qApp->inputMethod()->reset();
10141 qApp->inputMethod()->update(Qt::ImEnabled);
10146 case Qt::WA_WindowPropagation:
10147 d->resolvePalette();
10149 d->resolveLocale();
10152 case Qt::WA_NoX11EventCompression:
10155 d->extra->compress_events = on;
10157 case Qt::WA_X11OpenGLOverlay:
10158 d->updateIsOpaque();
10160 case Qt::WA_X11DoNotAcceptFocus:
10161 if (testAttribute(Qt::WA_WState_Created))
10162 d->updateX11AcceptFocus();
10165 case Qt::WA_DontShowOnScreen: {
10166 if (on && isVisible()) {
10167 // Make sure we keep the current state and only hide the widget
10168 // from the desktop. show_sys will only update platform specific
10169 // attributes at this point.
10177 case Qt::WA_X11NetWmWindowTypeDesktop:
10178 case Qt::WA_X11NetWmWindowTypeDock:
10179 case Qt::WA_X11NetWmWindowTypeToolBar:
10180 case Qt::WA_X11NetWmWindowTypeMenu:
10181 case Qt::WA_X11NetWmWindowTypeUtility:
10182 case Qt::WA_X11NetWmWindowTypeSplash:
10183 case Qt::WA_X11NetWmWindowTypeDialog:
10184 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10185 case Qt::WA_X11NetWmWindowTypePopupMenu:
10186 case Qt::WA_X11NetWmWindowTypeToolTip:
10187 case Qt::WA_X11NetWmWindowTypeNotification:
10188 case Qt::WA_X11NetWmWindowTypeCombo:
10189 case Qt::WA_X11NetWmWindowTypeDND:
10190 if (testAttribute(Qt::WA_WState_Created))
10191 d->setNetWmWindowTypes();
10195 case Qt::WA_StaticContents:
10196 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10198 bs->addStaticWidget(this);
10200 bs->removeStaticWidget(this);
10203 case Qt::WA_TranslucentBackground:
10205 setAttribute(Qt::WA_NoSystemBackground);
10206 d->updateIsTranslucent();
10210 case Qt::WA_AcceptTouchEvents:
10211 #if defined(Q_WS_WIN) || defined(Q_WS_MAC)
10213 d->registerTouchWindow();
10221 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10223 Returns true if attribute \a attribute is set on this widget;
10224 otherwise returns false.
10228 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10230 Q_D(const QWidget);
10231 const int x = attribute - 8*sizeof(uint);
10232 const int int_off = x / (8*sizeof(uint));
10233 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10237 \property QWidget::windowOpacity
10239 \brief The level of opacity for the window.
10241 The valid range of opacity is from 1.0 (completely opaque) to
10242 0.0 (completely transparent).
10244 By default the value of this property is 1.0.
10246 This feature is available on Embedded Linux, Mac OS X, Windows,
10247 and X11 platforms that support the Composite extension.
10249 This feature is not available on Windows CE.
10251 Note that under X11 you need to have a composite manager running,
10252 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10253 supported by the window manager you are using.
10255 \warning Changing this property from opaque to transparent might issue a
10256 paint event that needs to be processed before the window is displayed
10257 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10258 that semi-transparent windows update and resize significantly slower than
10263 qreal QWidget::windowOpacity() const
10265 Q_D(const QWidget);
10266 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10269 void QWidget::setWindowOpacity(qreal opacity)
10275 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10276 QTLWExtra *extra = d->topData();
10277 extra->opacity = uint(opacity * 255);
10278 setAttribute(Qt::WA_WState_WindowOpacitySet);
10280 if (!testAttribute(Qt::WA_WState_Created))
10283 #ifndef QT_NO_GRAPHICSVIEW
10284 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10285 // Avoid invalidating the cache if set.
10286 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10288 else if (QGraphicsScene *scene = proxy->scene())
10289 scene->update(proxy->sceneBoundingRect());
10294 d->setWindowOpacity_sys(opacity);
10298 \property QWidget::windowModified
10299 \brief whether the document shown in the window has unsaved changes
10301 A modified window is a window whose content has changed but has
10302 not been saved to disk. This flag will have different effects
10303 varied by the platform. On Mac OS X the close button will have a
10304 modified look; on other platforms, the window title will have an
10307 The window title must contain a "[*]" placeholder, which
10308 indicates where the '*' should appear. Normally, it should appear
10309 right after the file name (e.g., "document1.txt[*] - Text
10310 Editor"). If the window isn't modified, the placeholder is simply
10313 Note that if a widget is set as modified, all its ancestors will
10314 also be set as modified. However, if you call \c
10315 {setWindowModified(false)} on a widget, this will not propagate to
10316 its parent because other children of the parent might have been
10319 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10321 bool QWidget::isWindowModified() const
10323 return testAttribute(Qt::WA_WindowModified);
10326 void QWidget::setWindowModified(bool mod)
10329 setAttribute(Qt::WA_WindowModified, mod);
10332 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10333 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10335 d->setWindowTitle_helper(windowTitle());
10336 d->setWindowIconText_helper(windowIconText());
10338 d->setWindowModified_sys(mod);
10341 QEvent e(QEvent::ModifiedChange);
10342 QApplication::sendEvent(this, &e);
10345 #ifndef QT_NO_TOOLTIP
10347 \property QWidget::toolTip
10349 \brief the widget's tooltip
10351 Note that by default tooltips are only shown for widgets that are
10352 children of the active window. You can change this behavior by
10353 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10354 not on the widget with the tooltip.
10356 If you want to control a tooltip's behavior, you can intercept the
10357 event() function and catch the QEvent::ToolTip event (e.g., if you
10358 want to customize the area for which the tooltip should be shown).
10360 By default, this property contains an empty string.
10362 \sa QToolTip statusTip whatsThis
10364 void QWidget::setToolTip(const QString &s)
10369 QEvent event(QEvent::ToolTipChange);
10370 QApplication::sendEvent(this, &event);
10373 QString QWidget::toolTip() const
10375 Q_D(const QWidget);
10378 #endif // QT_NO_TOOLTIP
10381 #ifndef QT_NO_STATUSTIP
10383 \property QWidget::statusTip
10384 \brief the widget's status tip
10386 By default, this property contains an empty string.
10388 \sa toolTip whatsThis
10390 void QWidget::setStatusTip(const QString &s)
10396 QString QWidget::statusTip() const
10398 Q_D(const QWidget);
10399 return d->statusTip;
10401 #endif // QT_NO_STATUSTIP
10403 #ifndef QT_NO_WHATSTHIS
10405 \property QWidget::whatsThis
10407 \brief the widget's What's This help text.
10409 By default, this property contains an empty string.
10411 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10413 void QWidget::setWhatsThis(const QString &s)
10419 QString QWidget::whatsThis() const
10421 Q_D(const QWidget);
10422 return d->whatsThis;
10424 #endif // QT_NO_WHATSTHIS
10426 #ifndef QT_NO_ACCESSIBILITY
10428 \property QWidget::accessibleName
10430 \brief the widget's name as seen by assistive technologies
10432 This property is used by accessible clients to identify, find, or announce
10433 the widget for accessible clients.
10435 By default, this property contains an empty string.
10437 \sa QAccessibleInterface::text()
10439 void QWidget::setAccessibleName(const QString &name)
10442 d->accessibleName = name;
10443 QAccessibleEvent event(this, QAccessible::NameChanged);
10444 QAccessible::updateAccessibility(&event);
10447 QString QWidget::accessibleName() const
10449 Q_D(const QWidget);
10450 return d->accessibleName;
10454 \property QWidget::accessibleDescription
10456 \brief the widget's description as seen by assistive technologies
10458 By default, this property contains an empty string.
10460 \sa QAccessibleInterface::text()
10462 void QWidget::setAccessibleDescription(const QString &description)
10465 d->accessibleDescription = description;
10466 QAccessibleEvent event(this, QAccessible::DescriptionChanged);
10467 QAccessible::updateAccessibility(&event);
10470 QString QWidget::accessibleDescription() const
10472 Q_D(const QWidget);
10473 return d->accessibleDescription;
10475 #endif // QT_NO_ACCESSIBILITY
10477 #ifndef QT_NO_SHORTCUT
10479 Adds a shortcut to Qt's shortcut system that watches for the given
10480 \a key sequence in the given \a context. If the \a context is
10481 Qt::ApplicationShortcut, the shortcut applies to the application as a
10482 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10483 or to the window itself, Qt::WindowShortcut.
10485 If the same \a key sequence has been grabbed by several widgets,
10486 when the \a key sequence occurs a QEvent::Shortcut event is sent
10487 to all the widgets to which it applies in a non-deterministic
10488 order, but with the ``ambiguous'' flag set to true.
10490 \warning You should not normally need to use this function;
10491 instead create \l{QAction}s with the shortcut key sequences you
10492 require (if you also want equivalent menu options and toolbar
10493 buttons), or create \l{QShortcut}s if you just need key sequences.
10494 Both QAction and QShortcut handle all the event filtering for you,
10495 and provide signals which are triggered when the user triggers the
10496 key sequence, so are much easier to use than this low-level
10499 \sa releaseShortcut() setShortcutEnabled()
10501 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10506 setAttribute(Qt::WA_GrabbedShortcut);
10507 return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10511 Removes the shortcut with the given \a id from Qt's shortcut
10512 system. The widget will no longer receive QEvent::Shortcut events
10513 for the shortcut's key sequence (unless it has other shortcuts
10514 with the same key sequence).
10516 \warning You should not normally need to use this function since
10517 Qt's shortcut system removes shortcuts automatically when their
10518 parent widget is destroyed. It is best to use QAction or
10519 QShortcut to handle shortcuts, since they are easier to use than
10520 this low-level function. Note also that this is an expensive
10523 \sa grabShortcut() setShortcutEnabled()
10525 void QWidget::releaseShortcut(int id)
10529 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10533 If \a enable is true, the shortcut with the given \a id is
10534 enabled; otherwise the shortcut is disabled.
10536 \warning You should not normally need to use this function since
10537 Qt's shortcut system enables/disables shortcuts automatically as
10538 widgets become hidden/visible and gain or lose focus. It is best
10539 to use QAction or QShortcut to handle shortcuts, since they are
10540 easier to use than this low-level function.
10542 \sa grabShortcut() releaseShortcut()
10544 void QWidget::setShortcutEnabled(int id, bool enable)
10548 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10554 If \a enable is true, auto repeat of the shortcut with the
10555 given \a id is enabled; otherwise it is disabled.
10557 \sa grabShortcut() releaseShortcut()
10559 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10563 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10565 #endif // QT_NO_SHORTCUT
10568 Updates the widget's micro focus.
10570 void QWidget::updateMicroFocus()
10572 // updating everything since this is currently called for any kind of state change
10573 qApp->inputMethod()->update(Qt::ImQueryAll);
10577 Raises this widget to the top of the parent widget's stack.
10579 After this call the widget will be visually in front of any
10580 overlapping sibling widgets.
10582 \note When using activateWindow(), you can call this function to
10583 ensure that the window is stacked on top.
10585 \sa lower(), stackUnder()
10588 void QWidget::raise()
10592 QWidget *p = parentWidget();
10593 const int parentChildCount = p->d_func()->children.size();
10594 if (parentChildCount < 2)
10596 const int from = p->d_func()->children.indexOf(this);
10597 Q_ASSERT(from >= 0);
10598 // Do nothing if the widget is already in correct stacking order _and_ created.
10599 if (from != parentChildCount -1)
10600 p->d_func()->children.move(from, parentChildCount - 1);
10601 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10603 else if (from == parentChildCount - 1)
10606 QRegion region(rect());
10607 d->subtractOpaqueSiblings(region);
10608 d->invalidateBuffer(region);
10610 if (testAttribute(Qt::WA_WState_Created))
10613 QEvent e(QEvent::ZOrderChange);
10614 QApplication::sendEvent(this, &e);
10618 Lowers the widget to the bottom of the parent widget's stack.
10620 After this call the widget will be visually behind (and therefore
10621 obscured by) any overlapping sibling widgets.
10623 \sa raise(), stackUnder()
10626 void QWidget::lower()
10630 QWidget *p = parentWidget();
10631 const int parentChildCount = p->d_func()->children.size();
10632 if (parentChildCount < 2)
10634 const int from = p->d_func()->children.indexOf(this);
10635 Q_ASSERT(from >= 0);
10636 // Do nothing if the widget is already in correct stacking order _and_ created.
10638 p->d_func()->children.move(from, 0);
10639 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10641 else if (from == 0)
10644 if (testAttribute(Qt::WA_WState_Created))
10647 QEvent e(QEvent::ZOrderChange);
10648 QApplication::sendEvent(this, &e);
10653 Places the widget under \a w in the parent widget's stack.
10655 To make this work, the widget itself and \a w must be siblings.
10657 \sa raise(), lower()
10659 void QWidget::stackUnder(QWidget* w)
10662 QWidget *p = parentWidget();
10663 if (!w || isWindow() || p != w->parentWidget() || this == w)
10666 int from = p->d_func()->children.indexOf(this);
10667 int to = p->d_func()->children.indexOf(w);
10668 Q_ASSERT(from >= 0);
10672 // Do nothing if the widget is already in correct stacking order _and_ created.
10674 p->d_func()->children.move(from, to);
10675 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10677 else if (from == to)
10680 if (testAttribute(Qt::WA_WState_Created))
10681 d->stackUnder_sys(w);
10683 QEvent e(QEvent::ZOrderChange);
10684 QApplication::sendEvent(this, &e);
10689 \fn bool QWidget::isTopLevel() const
10692 Use isWindow() instead.
10696 \fn bool QWidget::isRightToLeft() const
10701 \fn bool QWidget::isLeftToRight() const
10706 \macro QWIDGETSIZE_MAX
10709 Defines the maximum size for a QWidget object.
10711 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
10712 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
10714 \sa QWidget::setMaximumSize()
10718 \fn QWidget::setupUi(QWidget *widget)
10720 Sets up the user interface for the specified \a widget.
10722 \note This function is available with widgets that derive from user
10723 interface descriptions created using \l{uic}.
10725 \sa {Using a Designer UI File in Your Application}
10728 QRect QWidgetPrivate::frameStrut() const
10730 Q_Q(const QWidget);
10731 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
10732 // x2 = x1 + w - 1, so w/h = 1
10733 return QRect(0, 0, 1, 1);
10736 if (data.fstrut_dirty
10738 // ### Fix properly for 4.3
10741 && q->testAttribute(Qt::WA_WState_Created))
10742 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
10744 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
10747 #ifdef QT_KEYPAD_NAVIGATION
10751 Changes the focus from the current focusWidget to a widget in
10754 Returns true, if there was a widget in that direction
10756 bool QWidgetPrivate::navigateToDirection(Direction direction)
10758 QWidget *targetWidget = widgetInNavigationDirection(direction);
10760 targetWidget->setFocus();
10761 return (targetWidget != 0);
10767 Searches for a widget that is positioned in the \a direction, starting
10768 from the current focusWidget.
10770 Returns the pointer to a found widget or 0, if there was no widget in
10773 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
10775 const QWidget *sourceWidget = QApplication::focusWidget();
10778 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
10779 const int sourceX =
10780 (direction == DirectionNorth || direction == DirectionSouth) ?
10781 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
10782 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
10783 const int sourceY =
10784 (direction == DirectionEast || direction == DirectionWest) ?
10785 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
10786 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
10787 const QPoint sourcePoint(sourceX, sourceY);
10788 const QPoint sourceCenter = sourceRect.center();
10789 const QWidget *sourceWindow = sourceWidget->window();
10791 QWidget *targetWidget = 0;
10792 int shortestDistance = INT_MAX;
10793 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
10795 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
10797 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
10798 // but the owner of the proxy cannot.
10799 // Additionally, empty widgets should be ignored.
10800 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
10803 // Only navigate to a target widget that...
10804 if ( targetCandidate != sourceWidget
10805 // ...takes the focus,
10806 && targetCandidate->focusPolicy() & Qt::TabFocus
10807 // ...is above if DirectionNorth,
10808 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
10809 // ...is on the right if DirectionEast,
10810 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
10811 // ...is below if DirectionSouth,
10812 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
10813 // ...is on the left if DirectionWest,
10814 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
10816 && targetCandidate->isEnabled()
10818 && targetCandidate->isVisible()
10819 // ...is in the same window,
10820 && targetCandidate->window() == sourceWindow) {
10821 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
10822 if (targetCandidateDistance < shortestDistance) {
10823 shortestDistance = targetCandidateDistance;
10824 targetWidget = targetCandidate;
10828 return targetWidget;
10834 Tells us if it there is currently a reachable widget by keypad navigation in
10835 a certain \a orientation.
10836 If no navigation is possible, occurring key events in that \a orientation may
10837 be used to interact with the value in the focused widget, even though it
10838 currently has not the editFocus.
10840 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
10842 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
10844 return orientation == Qt::Horizontal?
10845 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
10846 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
10847 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
10848 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
10853 Checks, if the \a widget is inside a QTabWidget. If is is inside
10854 one, left/right key events will be used to switch between tabs in keypad
10855 navigation. If there is no QTabWidget, the horizontal key events can be used
10857 interact with the value in the focused widget, even though it currently has
10860 \sa QWidget::hasEditFocus()
10862 bool QWidgetPrivate::inTabWidget(QWidget *widget)
10864 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
10865 if (qobject_cast<const QTabWidget*>(tabWidget))
10875 Sets the backing store to be the \a store specified.
10876 The QWidget will take ownership of the \a store.
10878 void QWidget::setBackingStore(QBackingStore *store)
10880 // ### createWinId() ??
10887 QTLWExtra *topData = d->topData();
10888 if (topData->backingStore == store)
10891 QBackingStore *oldStore = topData->backingStore;
10892 delete topData->backingStore;
10893 topData->backingStore = store;
10895 QWidgetBackingStore *bs = d->maybeBackingStore();
10899 if (isTopLevel()) {
10900 if (bs->store != oldStore && bs->store != store)
10909 Returns the QBackingStore this widget will be drawn into.
10911 QBackingStore *QWidget::backingStore() const
10913 Q_D(const QWidget);
10914 QTLWExtra *extra = d->maybeTopData();
10915 if (extra && extra->backingStore)
10916 return extra->backingStore;
10918 QWidgetBackingStore *bs = d->maybeBackingStore();
10920 return bs ? bs->store : 0;
10923 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
10926 *left = (int)leftLayoutItemMargin;
10928 *top = (int)topLayoutItemMargin;
10930 *right = (int)rightLayoutItemMargin;
10932 *bottom = (int)bottomLayoutItemMargin;
10935 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
10937 if (leftLayoutItemMargin == left
10938 && topLayoutItemMargin == top
10939 && rightLayoutItemMargin == right
10940 && bottomLayoutItemMargin == bottom)
10944 leftLayoutItemMargin = (signed char)left;
10945 topLayoutItemMargin = (signed char)top;
10946 rightLayoutItemMargin = (signed char)right;
10947 bottomLayoutItemMargin = (signed char)bottom;
10948 q->updateGeometry();
10951 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
10954 QStyleOption myOpt;
10957 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
10961 QRect liRect = q->style()->subElementRect(element, opt, q);
10962 if (liRect.isValid()) {
10963 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
10964 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
10965 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
10966 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
10968 leftLayoutItemMargin = 0;
10969 topLayoutItemMargin = 0;
10970 rightLayoutItemMargin = 0;
10971 bottomLayoutItemMargin = 0;
10974 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
10975 void QWidgetPrivate::adjustQuitOnCloseAttribute()
10979 if (!q->parentWidget()) {
10980 Qt::WindowType type = q->windowType();
10981 if (type == Qt::Widget || type == Qt::SubWindow)
10983 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
10984 q->setAttribute(Qt::WA_QuitOnClose, false);
10990 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
10992 return widget->data;
10995 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
10997 return widget->d_func();
11001 #ifndef QT_NO_GRAPHICSVIEW
11005 Returns the proxy widget for the corresponding embedded widget in a graphics
11006 view; otherwise returns 0.
11008 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
11009 QGraphicsScene::addWidget()
11011 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
11013 Q_D(const QWidget);
11015 return d->extra->proxyWidget;
11023 \typedef QWidgetList
11026 Synonym for QList<QWidget *>.
11029 #ifndef QT_NO_GESTURES
11031 Subscribes the widget to a given \a gesture with specific \a flags.
11033 \sa ungrabGesture(), QGestureEvent
11036 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11039 d->gestureContext.insert(gesture, flags);
11040 (void)QGestureManager::instance(); // create a gesture manager
11044 Unsubscribes the widget from a given \a gesture type
11046 \sa grabGesture(), QGestureEvent
11049 void QWidget::ungrabGesture(Qt::GestureType gesture)
11052 if (d->gestureContext.remove(gesture)) {
11053 if (QGestureManager *manager = QGestureManager::instance())
11054 manager->cleanupCachedGestures(this, gesture);
11057 #endif // QT_NO_GESTURES
11063 Platform dependent window identifier.
11067 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11069 Frees up window system resources. Destroys the widget window if \a
11070 destroyWindow is true.
11072 destroy() calls itself recursively for all the child widgets,
11073 passing \a destroySubWindows for the \a destroyWindow parameter.
11074 To have more control over destruction of subwidgets, destroy
11075 subwidgets selectively first.
11077 This function is usually called from the QWidget destructor.
11081 \fn QPaintEngine *QWidget::paintEngine() const
11083 Returns the widget's paint engine.
11085 Note that this function should not be called explicitly by the
11086 user, since it's meant for reimplementation purposes only. The
11087 function is called by Qt internally, and the default
11088 implementation may not always return a valid pointer.
11092 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11094 Translates the widget coordinate \a pos to global screen
11095 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11096 the global coordinates of the top-left pixel of the widget.
11098 \sa mapFromGlobal() mapTo() mapToParent()
11102 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11104 Translates the global screen coordinate \a pos to widget
11107 \sa mapToGlobal() mapFrom() mapFromParent()
11111 \fn void QWidget::grabMouse()
11113 Grabs the mouse input.
11115 This widget receives all mouse events until releaseMouse() is
11116 called; other widgets get no mouse events at all. Keyboard
11117 events are not affected. Use grabKeyboard() if you want to grab
11120 \warning Bugs in mouse-grabbing applications very often lock the
11121 terminal. Use this function with extreme caution, and consider
11122 using the \c -nograb command line option while debugging.
11124 It is almost never necessary to grab the mouse when using Qt, as
11125 Qt grabs and releases it sensibly. In particular, Qt grabs the
11126 mouse when a mouse button is pressed and keeps it until the last
11127 button is released.
11129 \note Only visible widgets can grab mouse input. If isVisible()
11130 returns false for a widget, that widget cannot call grabMouse().
11132 \note \b{(Mac OS X developers)} For \e Cocoa, calling
11133 grabMouse() on a widget only works when the mouse is inside the
11134 frame of that widget. For \e Carbon, it works outside the widget's
11135 frame as well, like for Windows and X11.
11137 \sa releaseMouse() grabKeyboard() releaseKeyboard()
11141 \fn void QWidget::grabMouse(const QCursor &cursor)
11142 \overload grabMouse()
11144 Grabs the mouse input and changes the cursor shape.
11146 The cursor will assume shape \a cursor (for as long as the mouse
11147 focus is grabbed) and this widget will be the only one to receive
11148 mouse events until releaseMouse() is called().
11150 \warning Grabbing the mouse might lock the terminal.
11152 \note \b{(Mac OS X developers)} See the note in QWidget::grabMouse().
11154 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11158 \fn void QWidget::releaseMouse()
11160 Releases the mouse grab.
11162 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11166 \fn void QWidget::grabKeyboard()
11168 Grabs the keyboard input.
11170 This widget receives all keyboard events until releaseKeyboard()
11171 is called; other widgets get no keyboard events at all. Mouse
11172 events are not affected. Use grabMouse() if you want to grab that.
11174 The focus widget is not affected, except that it doesn't receive
11175 any keyboard events. setFocus() moves the focus as usual, but the
11176 new focus widget receives keyboard events only after
11177 releaseKeyboard() is called.
11179 If a different widget is currently grabbing keyboard input, that
11180 widget's grab is released first.
11182 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11186 \fn void QWidget::releaseKeyboard()
11188 Releases the keyboard grab.
11190 \sa grabKeyboard(), grabMouse(), releaseMouse()
11194 \fn QWidget *QWidget::mouseGrabber()
11196 Returns the widget that is currently grabbing the mouse input.
11198 If no widget in this application is currently grabbing the mouse,
11201 \sa grabMouse(), keyboardGrabber()
11205 \fn QWidget *QWidget::keyboardGrabber()
11207 Returns the widget that is currently grabbing the keyboard input.
11209 If no widget in this application is currently grabbing the
11210 keyboard, 0 is returned.
11212 \sa grabMouse(), mouseGrabber()
11216 \fn void QWidget::activateWindow()
11218 Sets the top-level widget containing this widget to be the active
11221 An active window is a visible top-level window that has the
11222 keyboard input focus.
11224 This function performs the same operation as clicking the mouse on
11225 the title bar of a top-level window. On X11, the result depends on
11226 the Window Manager. If you want to ensure that the window is
11227 stacked on top as well you should also call raise(). Note that the
11228 window must be visible, otherwise activateWindow() has no effect.
11230 On Windows, if you are calling this when the application is not
11231 currently the active one then it will not make it the active
11232 window. It will change the color of the taskbar entry to indicate
11233 that the window has changed in some way. This is because Microsoft
11234 does not allow an application to interrupt what the user is currently
11235 doing in another application.
11237 \sa isActiveWindow(), window(), show()
11241 \fn int QWidget::metric(PaintDeviceMetric m) const
11243 Internal implementation of the virtual QPaintDevice::metric()
11246 \a m is the metric to get.
11249 void QWidget::init(QPainter *painter) const
11251 const QPalette &pal = palette();
11252 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
11253 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11254 QFont f(font(), const_cast<QWidget *>(this));
11255 painter->d_func()->state->deviceFont = f;
11256 painter->d_func()->state->font = f;
11259 QPaintDevice *QWidget::redirected(QPoint *offset) const
11261 return d_func()->redirected(offset);
11264 QPainter *QWidget::sharedPainter() const
11266 // Someone sent a paint event directly to the widget
11267 if (!d_func()->redirectDev)
11270 QPainter *sp = d_func()->sharedPainter();
11271 if (!sp || !sp->isActive())
11274 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11281 \fn void QWidget::setMask(const QRegion ®ion)
11284 Causes only the parts of the widget which overlap \a region to be
11285 visible. If the region includes pixels outside the rect() of the
11286 widget, window system controls in that area may or may not be
11287 visible, depending on the platform.
11289 Note that this effect can be slow if the region is particularly
11294 void QWidget::setMask(const QRegion &newMask)
11299 if (newMask == d->extra->mask)
11302 #ifndef QT_NO_BACKINGSTORE
11303 const QRegion oldMask(d->extra->mask);
11306 d->extra->mask = newMask;
11307 d->extra->hasMask = !newMask.isEmpty();
11310 if (!testAttribute(Qt::WA_WState_Created))
11314 d->setMask_sys(newMask);
11316 #ifndef QT_NO_BACKINGSTORE
11320 if (!d->extra->hasMask) {
11321 // Mask was cleared; update newly exposed area.
11322 QRegion expose(rect());
11324 if (!expose.isEmpty()) {
11325 d->setDirtyOpaqueRegion();
11332 // Update newly exposed area on the parent widget.
11333 QRegion parentExpose(rect());
11334 parentExpose -= newMask;
11335 if (!parentExpose.isEmpty()) {
11336 d->setDirtyOpaqueRegion();
11337 parentExpose.translate(data->crect.topLeft());
11338 parentWidget()->update(parentExpose);
11341 // Update newly exposed area on this widget
11342 if (!oldMask.isEmpty())
11343 update(newMask - oldMask);
11349 \fn void QWidget::setMask(const QBitmap &bitmap)
11351 Causes only the pixels of the widget for which \a bitmap has a
11352 corresponding 1 bit to be visible. If the region includes pixels
11353 outside the rect() of the widget, window system controls in that
11354 area may or may not be visible, depending on the platform.
11356 Note that this effect can be slow if the region is particularly
11359 The following code shows how an image with an alpha channel can be
11360 used to generate a mask for a widget:
11362 \snippet doc/src/snippets/widget-mask/main.cpp 0
11364 The label shown by this code is masked using the image it contains,
11365 giving the appearance that an irregularly-shaped image is being drawn
11366 directly onto the screen.
11368 Masked widgets receive mouse events only on their visible
11371 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
11373 void QWidget::setMask(const QBitmap &bitmap)
11375 setMask(QRegion(bitmap));
11379 \fn void QWidget::clearMask()
11381 Removes any mask set by setMask().
11385 void QWidget::clearMask()
11387 setMask(QRegion());
11390 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
11391 Returns the X11 Picture handle of the widget for XRender
11392 support. Use of this function is not portable. This function will
11393 return 0 if XRender support is not compiled into Qt, if the
11394 XRender extension is not supported on the X11 display, or if the
11395 handle could not be created.
11399 void QWidgetPrivate::syncUnifiedMode() {
11400 // The whole purpose of this method is to keep the unifiedToolbar in sync.
11401 // That means making sure we either exchange the drawing methods or we let
11402 // the toolbar know that it does not require to draw the baseline.
11404 // This function makes sense only if this is a top level
11407 OSWindowRef window = qt_mac_window_for(q);
11408 if(changeMethods) {
11409 // Ok, we are in documentMode.
11410 if(originalDrawMethod)
11411 qt_mac_replaceDrawRect(window, this);
11413 if(!originalDrawMethod)
11414 qt_mac_replaceDrawRectOriginal(window, this);
11422 #include "moc_qwidget.cpp"