1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtGui module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
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_windows.h"
67 # include "qt_mac_p.h"
68 # include "qt_cocoa_helpers_mac_p.h"
69 # include "qmainwindow.h"
70 # include "qtoolbar.h"
71 # include <private/qmainwindowlayout_p.h>
74 #include "qplatformwindow_qpa.h"
75 #include "private/qwidgetwindow_qpa_p.h"
79 #include "qwhatsthis.h"
81 #include "private/qstylesheetstyle_p.h"
82 #include "private/qstyle_p.h"
83 #include "qinputcontext.h"
84 #include "qfileinfo.h"
85 #include "private/qsoftkeymanager_p.h"
86 #include <QtGui/qinputpanel.h>
88 #include <private/qgraphicseffect_p.h>
89 #include <qbackingstore.h>
90 #include <private/qwidgetbackingstore_p.h>
92 # include <private/qpaintengine_mac_p.h>
94 #include <private/qpaintengine_raster_p.h>
96 #if defined(Q_OS_SYMBIAN)
97 #include "private/qt_s60_p.h"
100 #include "qwidget_p.h"
101 #include "qaction_p.h"
102 #include "qlayout_p.h"
103 #include "QtWidgets/qgraphicsproxywidget.h"
104 #include "QtWidgets/qgraphicsscene.h"
105 #include "private/qgraphicsproxywidget_p.h"
106 #include "QtWidgets/qabstractscrollarea.h"
107 #include "private/qabstractscrollarea_p.h"
108 #include "private/qevent_p.h"
110 #include "private/qgesturemanager_p.h"
112 #ifdef QT_KEYPAD_NAVIGATION
113 #include "qtabwidget.h" // Needed in inTabWidget()
114 #endif // QT_KEYPAD_NAVIGATION
117 #include <aknappui.h>
120 // widget/widget data creation count
121 //#define QWIDGET_EXTRA_DEBUG
122 //#define ALIEN_DEBUG
126 static bool qt_enable_backingstore = true;
128 // for compatibility with Qt 4.0
129 Q_WIDGETS_EXPORT void qt_x11_set_global_double_buffer(bool enable)
131 qt_enable_backingstore = enable;
135 #if defined(QT_MAC_USE_COCOA)
136 bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
139 static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
141 return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
142 qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
145 static inline bool hasBackingStoreSupport()
151 # define QT_NO_PAINT_DEBUG
154 extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
155 extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
159 \class QWidgetBackingStoreTracker
160 \brief Class which allows tracking of which widgets are using a given backing store
162 QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
163 which maintains a list of the QWidgets which are currently using the backing
164 store. This list is modified via the registerWidget and unregisterWidget functions.
167 QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
173 QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
180 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
181 widgets using the backing store, then create a new QWidgetBackingStore, providing
184 void QWidgetBackingStoreTracker::create(QWidget *widget)
187 m_ptr = new QWidgetBackingStore(widget);
192 Destroy the contained QWidgetBackingStore, if not null, and clear the list of
193 widgets using the backing store.
195 void QWidgetBackingStoreTracker::destroy()
204 Add the widget to the list of widgets currently using the backing store.
205 If the widget was already in the list, this function is a no-op.
207 void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
210 Q_ASSERT(w->internalWinId());
211 Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
217 Remove the widget from the list of widgets currently using the backing store.
218 If the widget was in the list, and removing it causes the list to be empty,
219 the backing store is deleted.
220 If the widget was not in the list, this function is a no-op.
222 void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
224 if (m_widgets.remove(w) && m_widgets.isEmpty()) {
232 Recursively remove widget and all of its descendents.
234 void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
236 unregisterWidget(widget);
237 foreach (QObject *child, widget->children())
238 if (QWidget *childWidget = qobject_cast<QWidget *>(child))
239 unregisterWidgetSubtree(childWidget);
242 QWidgetPrivate::QWidgetPrivate(int version)
243 : QObjectPrivate(version)
252 , extraPaintEngine(0)
255 #if !defined(QT_NO_IM)
256 , imHints(Qt::ImhNone)
258 , inheritedFontResolveMask(0)
259 , inheritedPaletteResolveMask(0)
264 , leftLayoutItemMargin(0)
265 , topLayoutItemMargin(0)
266 , rightLayoutItemMargin(0)
267 , bottomLayoutItemMargin(0)
269 , size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
270 , fg_role(QPalette::NoRole)
271 , bg_role(QPalette::NoRole)
272 , dirtyOpaqueChildren(1)
278 , usesDoubleBufferedGLContext(0)
280 , inheritsInputMethodHints(0)
283 #if defined(Q_WS_X11)
285 #elif defined(Q_WS_WIN)
287 #ifndef QT_NO_GESTURES
288 , nativeGesturePanEnabled(0)
290 #elif defined(Q_WS_MAC)
291 , needWindowChange(0)
294 #elif defined(Q_OS_SYMBIAN)
295 , symbianScreenNumber(0)
296 , fixNativeOrientationCalled(false)
300 qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
304 if (version != QObjectPrivateVersion)
305 qFatal("Cannot mix incompatible Qt libraries");
308 memset(high_attributes, 0, sizeof(high_attributes));
310 drawRectOriginalAdded = false;
311 originalDrawMethod = true;
312 changeMethods = false;
313 isInUnifiedToolbar = false;
315 toolbar_ancestor = 0;
316 flushRequested = false;
317 touchEventsEnabled = false;
318 #endif // QT_MAC_USE_COCOA
319 #ifdef QWIDGET_EXTRA_DEBUG
320 static int count = 0;
321 qDebug() << "widgets" << ++count;
326 QWidgetPrivate::~QWidgetPrivate()
334 #ifndef QT_NO_GRAPHICSEFFECT
335 delete graphicsEffect;
336 #endif //QT_NO_GRAPHICSEFFECT
342 void QWidgetPrivate::scrollChildren(int dx, int dy)
345 if (q->children().size() > 0) { // scroll children
347 QObjectList childObjects = q->children();
348 for (int i = 0; i < childObjects.size(); ++i) { // move all children
349 QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
350 if (w && !w->isWindow()) {
351 QPoint oldp = w->pos();
352 QRect r(w->pos() + pd, w->size());
354 if (w->testAttribute(Qt::WA_WState_Created))
355 w->d_func()->setWSGeometry();
356 w->d_func()->setDirtyOpaqueRegion();
357 QMoveEvent e(r.topLeft(), oldp);
358 QApplication::sendEvent(w, &e);
364 void QWidgetPrivate::updateWidgetTransform()
367 if (q == qApp->inputPanel()->inputItem()) {
369 QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
370 t.translate(p.x(), p.y());
371 qApp->inputPanel()->setInputItemTransform(t);
375 QInputContext *QWidgetPrivate::assignedInputContext() const
378 const QWidget *widget = q_func();
380 if (QInputContext *qic = widget->d_func()->ic)
382 widget = widget->parentWidget();
388 QInputContext *QWidgetPrivate::inputContext() const
391 if (QInputContext *qic = assignedInputContext())
393 return qApp->inputContext();
400 This function returns the QInputContext for this widget. By
401 default the input context is inherited from the widgets
402 parent. For toplevels it is inherited from QApplication.
404 You can override this and set a special input context for this
405 widget by using the setInputContext() method.
407 \sa setInputContext()
409 QInputContext *QWidget::inputContext()
412 if (!testAttribute(Qt::WA_InputMethodEnabled))
415 return d->inputContext();
419 This function sets the input context \a context
422 Qt takes ownership of the given input \a context.
426 void QWidget::setInputContext(QInputContext *context)
429 if (!testAttribute(Qt::WA_InputMethodEnabled))
432 if (context == d->ic)
438 d->ic->setParent(this);
446 This function can be called on the widget that currently has focus
447 to reset the input method operating on it.
449 This function is providing for convenience, instead you should use
450 \l{QInputContext::}{reset()} on the input context that was
451 returned by inputContext().
453 \sa QInputContext, inputContext(), QInputContext::reset()
455 void QWidget::resetInputContext()
460 QInputContext *qic = this->inputContext();
466 #ifdef QT_KEYPAD_NAVIGATION
467 QPointer<QWidget> QWidgetPrivate::editingWidget;
470 Returns true if this widget currently has edit focus; otherwise false.
472 This feature is only available in Qt for Embedded Linux.
474 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
476 bool QWidget::hasEditFocus() const
478 const QWidget* w = this;
479 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
480 w = w->d_func()->extra->focus_proxy;
481 return QWidgetPrivate::editingWidget == w;
485 \fn void QWidget::setEditFocus(bool enable)
487 If \a enable is true, make this widget have edit focus, in which
488 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
489 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
492 This feature is only available in Qt for Embedded Linux and Qt
495 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
497 void QWidget::setEditFocus(bool on)
500 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
501 f = f->d_func()->extra->focus_proxy;
503 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
504 QWidgetPrivate::editingWidget->setEditFocus(false);
506 if (on && !f->hasFocus())
509 if ((!on && !QWidgetPrivate::editingWidget)
510 || (on && QWidgetPrivate::editingWidget == f)) {
514 if (!on && QWidgetPrivate::editingWidget == f) {
515 QWidgetPrivate::editingWidget = 0;
516 QEvent event(QEvent::LeaveEditFocus);
517 QApplication::sendEvent(f, &event);
518 QApplication::sendEvent(f->style(), &event);
520 QWidgetPrivate::editingWidget = f;
521 QEvent event(QEvent::EnterEditFocus);
522 QApplication::sendEvent(f, &event);
523 QApplication::sendEvent(f->style(), &event);
529 \property QWidget::autoFillBackground
530 \brief whether the widget background is filled automatically
533 If enabled, this property will cause Qt to fill the background of the
534 widget before invoking the paint event. The color used is defined by the
535 QPalette::Window color role from the widget's \l{QPalette}{palette}.
537 In addition, Windows are always filled with QPalette::Window, unless the
538 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
540 This property cannot be turned off (i.e., set to false) if a widget's
541 parent has a static gradient for its background.
543 \warning Use this property with caution in conjunction with
544 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
545 background or a border-image, this property is automatically disabled.
547 By default, this property is false.
549 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
550 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
552 bool QWidget::autoFillBackground() const
555 return d->extra && d->extra->autoFillBackground;
558 void QWidget::setAutoFillBackground(bool enabled)
563 if (d->extra->autoFillBackground == enabled)
566 d->extra->autoFillBackground = enabled;
574 \brief The QWidget class is the base class of all user interface objects.
576 \ingroup basicwidgets
578 The widget is the atom of the user interface: it receives mouse, keyboard
579 and other events from the window system, and paints a representation of
580 itself on the screen. Every widget is rectangular, and they are sorted in a
581 Z-order. A widget is clipped by its parent and by the widgets in front of
584 A widget that is not embedded in a parent widget is called a window.
585 Usually, windows have a frame and a title bar, although it is also possible
586 to create windows without such decoration using suitable
587 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
588 subclasses of QDialog are the most common window types.
590 Every widget's constructor accepts one or two standard arguments:
593 \i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
594 (the default), the new widget will be a window. If not, it will be
595 a child of \e parent, and be constrained by \e parent's geometry
596 (unless you specify Qt::Window as window flag).
597 \i \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
598 the default is suitable for almost all widgets, but to get, for
599 example, a window without a window system frame, you must use
603 QWidget has many member functions, but some of them have little direct
604 functionality; for example, QWidget has a font property, but never uses
605 this itself. There are many subclasses which provide real functionality,
606 such as QLabel, QPushButton, QListWidget, and QTabWidget.
609 \section1 Top-Level and Child Widgets
611 A widget without a parent widget is always an independent window (top-level
612 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
613 title bar and icon respectively.
615 Non-window widgets are child widgets, displayed within their parent
616 widgets. Most widgets in Qt are mainly useful as child widgets. For
617 example, it is possible to display a button as a top-level window, but most
618 people prefer to put their buttons inside other widgets, such as QDialog.
620 \image parent-child-widgets.png A parent widget containing various child widgets.
622 The diagram above shows a QGroupBox widget being used to hold various child
623 widgets in a layout provided by QGridLayout. The QLabel child widgets have
624 been outlined to indicate their full sizes.
626 If you want to use a QWidget to hold child widgets you will usually want to
627 add a layout to the parent QWidget. See \l{Layout Management} for more
631 \section1 Composite Widgets
633 When a widget is used as a container to group a number of child widgets, it
634 is known as a composite widget. These can be created by constructing a
635 widget with the required visual properties - a QFrame, for example - and
636 adding child widgets to it, usually managed by a layout. The above diagram
637 shows such a composite widget that was created using \l{Qt Designer}.
639 Composite widgets can also be created by subclassing a standard widget,
640 such as QWidget or QFrame, and adding the necessary layout and child
641 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
642 {examples provided with Qt} use this approach, and it is also covered in
643 the Qt \l{Tutorials}.
646 \section1 Custom Widgets and Painting
648 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
649 display custom content that is composed using a series of painting
650 operations with an instance of the QPainter class. This approach contrasts
651 with the canvas-style approach used by the \l{Graphics View}
652 {Graphics View Framework} where items are added to a scene by the
653 application and are rendered by the framework itself.
655 Each widget performs all painting operations from within its paintEvent()
656 function. This is called whenever the widget needs to be redrawn, either
657 as a result of some external change or when requested by the application.
659 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
660 can handle paint events.
663 \section1 Size Hints and Size Policies
665 When implementing a new widget, it is almost always useful to reimplement
666 sizeHint() to provide a reasonable default size for the widget and to set
667 the correct size policy with setSizePolicy().
669 By default, composite widgets which do not provide a size hint will be
670 sized according to the space requirements of their child widgets.
672 The size policy lets you supply good default behavior for the layout
673 management system, so that other widgets can contain and manage yours
674 easily. The default size policy indicates that the size hint represents
675 the preferred size of the widget, and this is often good enough for many
678 \note The size of top-level widgets are constrained to 2/3 of the desktop's
679 height and width. You can resize() the widget manually if these bounds are
685 Widgets respond to events that are typically caused by user actions. Qt
686 delivers events to widgets by calling specific event handler functions with
687 instances of QEvent subclasses containing information about each event.
689 If your widget only contains child widgets, you probably do not need to
690 implement any event handlers. If you want to detect a mouse click in a
691 child widget call the child's underMouse() function inside the widget's
694 The \l{widgets/scribble}{Scribble example} implements a wider set of
695 events to handle mouse movement, button presses, and window resizing.
697 You will need to supply the behavior and content for your own widgets, but
698 here is a brief overview of the events that are relevant to QWidget,
699 starting with the most common ones:
702 \i paintEvent() is called whenever the widget needs to be repainted.
703 Every widget displaying custom content must implement it. Painting
704 using a QPainter can only take place in a paintEvent() or a
705 function called by a paintEvent().
706 \i resizeEvent() is called when the widget has been resized.
707 \i mousePressEvent() is called when a mouse button is pressed while
708 the mouse cursor is inside the widget, or when the widget has
709 grabbed the mouse using grabMouse(). Pressing the mouse without
710 releasing it is effectively the same as calling grabMouse().
711 \i mouseReleaseEvent() is called when a mouse button is released. A
712 widget receives mouse release events when it has received the
713 corresponding mouse press event. This means that if the user
714 presses the mouse inside \e your widget, then drags the mouse
715 somewhere else before releasing the mouse button, \e your widget
716 receives the release event. There is one exception: if a popup menu
717 appears while the mouse button is held down, this popup immediately
718 steals the mouse events.
719 \i mouseDoubleClickEvent() is called when the user double-clicks in
720 the widget. If the user double-clicks, the widget receives a mouse
721 press event, a mouse release event and finally this event instead
722 of a second mouse press event. (Some mouse move events may also be
723 received if the mouse is not held steady during this operation.) It
724 is \e{not possible} to distinguish a click from a double-click
725 until the second click arrives. (This is one reason why most GUI
726 books recommend that double-clicks be an extension of
727 single-clicks, rather than trigger a different action.)
730 Widgets that accept keyboard input need to reimplement a few more event
734 \i keyPressEvent() is called whenever a key is pressed, and again when
735 a key has been held down long enough for it to auto-repeat. The
736 \key Tab and \key Shift+Tab keys are only passed to the widget if
737 they are not used by the focus-change mechanisms. To force those
738 keys to be processed by your widget, you must reimplement
740 \i focusInEvent() is called when the widget gains keyboard focus
741 (assuming you have called setFocusPolicy()). Well-behaved widgets
742 indicate that they own the keyboard focus in a clear but discreet
744 \i focusOutEvent() is called when the widget loses keyboard focus.
747 You may be required to also reimplement some of the less common event
751 \i mouseMoveEvent() is called whenever the mouse moves while a mouse
752 button is held down. This can be useful during drag and drop
753 operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
754 you get mouse move events even when no buttons are held down.
755 (See also the \l{Drag and Drop} guide.)
756 \i keyReleaseEvent() is called whenever a key is released and while it
757 is held down (if the key is auto-repeating). In that case, the
758 widget will receive a pair of key release and key press event for
759 every repeat. The \key Tab and \key Shift+Tab keys are only passed
760 to the widget if they are not used by the focus-change mechanisms.
761 To force those keys to be processed by your widget, you must
762 reimplement QWidget::event().
763 \i wheelEvent() is called whenever the user turns the mouse wheel
764 while the widget has the focus.
765 \i enterEvent() is called when the mouse enters the widget's screen
766 space. (This excludes screen space owned by any of the widget's
768 \i leaveEvent() is called when the mouse leaves the widget's screen
769 space. If the mouse enters a child widget it will not cause a
771 \i moveEvent() is called when the widget has been moved relative to
773 \i closeEvent() is called when the user closes the widget (or when
777 There are also some rather obscure events described in the documentation
778 for QEvent::Type. To handle these events, you need to reimplement event()
781 The default implementation of event() handles \key Tab and \key Shift+Tab
782 (to move the keyboard focus), and passes on most of the other events to
783 one of the more specialized handlers above.
785 Events and the mechanism used to deliver them are covered in
786 \l{The Event System}.
788 \section1 Groups of Functions and Properties
791 \header \i Context \i Functions and Properties
793 \row \i Window functions \i
800 \row \i Top-level windows \i
801 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
802 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
803 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
806 \row \i Window contents \i
812 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
813 \l sizePolicy, sizeHint(), minimumSizeHint(),
814 updateGeometry(), layout(),
815 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
817 mapFromGlobal(), mapToGlobal(),
818 mapFromParent(), mapToParent(),
819 \l maximumSize, \l minimumSize, \l sizeIncrement,
820 \l baseSize, setFixedSize()
823 \l visible, isVisibleTo(),
824 \l enabled, isEnabledTo(),
831 \row \i Look and feel \i
838 backgroundRole(), setBackgroundRole(),
839 fontInfo(), fontMetrics().
841 \row \i Keyboard focus functions \i
842 \l focus, \l focusPolicy,
843 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
844 focusNextChild(), focusPreviousChild().
846 \row \i Mouse and keyboard grabbing \i
847 grabMouse(), releaseMouse(),
848 grabKeyboard(), releaseKeyboard(),
849 mouseGrabber(), keyboardGrabber().
851 \row \i Event handlers \i
855 mouseDoubleClickEvent(),
878 \row \i System functions \i
879 parentWidget(), window(), setParent(), winId(),
882 \row \i Interactive help \i
883 setToolTip(), setWhatsThis()
888 \section1 Widget Style Sheets
890 In addition to the standard widget styles for each platform, widgets can
891 also be styled according to rules specified in a \l{styleSheet}
892 {style sheet}. This feature enables you to customize the appearance of
893 specific widgets to provide visual cues to users about their purpose. For
894 example, a button could be styled in a particular way to indicate that it
895 performs a destructive action.
897 The use of widget style sheets is described in more detail in the
898 \l{Qt Style Sheets} document.
901 \section1 Transparency and Double Buffering
903 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
904 is no need to write double-buffering code in paintEvent() to avoid
907 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
908 deprecated. Instead, the contents of parent widgets are propagated by
909 default to each of their children as long as Qt::WA_PaintOnScreen is not
910 set. Custom widgets can be written to take advantage of this feature by
911 updating irregular regions (to create non-rectangular child widgets), or
912 painting with colors that have less than full alpha component. The
913 following diagram shows how attributes and properties of a custom widget
914 can be fine-tuned to achieve different effects.
916 \image propagation-custom.png
918 In the above diagram, a semi-transparent rectangular child widget with an
919 area removed is constructed and added to a parent widget (a QLabel showing
920 a pixmap). Then, different properties and widget attributes are set to
921 achieve different effects:
924 \i The left widget has no additional properties or widget attributes
925 set. This default state suits most custom widgets using
926 transparency, are irregularly-shaped, or do not paint over their
927 entire area with an opaque brush.
928 \i The center widget has the \l autoFillBackground property set. This
929 property is used with custom widgets that rely on the widget to
930 supply a default background, and do not paint over their entire
931 area with an opaque brush.
932 \i The right widget has the Qt::WA_OpaquePaintEvent widget attribute
933 set. This indicates that the widget will paint over its entire area
934 with opaque colors. The widget's area will initially be
935 \e{uninitialized}, represented in the diagram with a red diagonal
936 grid pattern that shines through the overpainted area. The
937 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
938 paint their own specialized contents quickly and do not need a
939 default filled background.
942 To rapidly update custom widgets with simple background colors, such as
943 real-time plotting or graphing widgets, it is better to define a suitable
944 background color (using setBackgroundRole() with the
945 QPalette::Window role), set the \l autoFillBackground property, and only
946 implement the necessary drawing functionality in the widget's paintEvent().
948 To rapidly update custom widgets that constantly paint over their entire
949 areas with opaque content, e.g., video streaming widgets, it is better to
950 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
951 associated with repainting the widget's background.
953 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
954 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
955 attribute takes precedence. Depending on your requirements, you should
956 choose either one of them.
958 Since Qt 4.1, the contents of parent widgets are also propagated to
959 standard Qt widgets. This can lead to some unexpected results if the
960 parent widget is decorated in a non-standard way, as shown in the diagram
963 \image propagation-standard.png
965 The scope for customizing the painting behavior of standard Qt widgets,
966 without resorting to subclassing, is slightly less than that possible for
967 custom widgets. Usually, the desired appearance of a standard widget can be
968 achieved by setting its \l autoFillBackground property.
971 \section1 Creating Translucent Windows
973 Since Qt 4.5, it has been possible to create windows with translucent regions
974 on window systems that support compositing.
976 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
977 attribute with setAttribute() and ensure that its background is painted with
978 non-opaque colors in the regions you want to be partially transparent.
983 \o X11: This feature relies on the use of an X server that supports ARGB visuals
984 and a compositing window manager.
985 \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
986 for the translucency to work.
990 \section1 Native Widgets vs Alien Widgets
992 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
993 system. They do not have a native window handle associated with them. This
994 feature significantly speeds up widget painting, resizing, and removes flicker.
996 Should you require the old behavior with native windows, you can choose
997 one of the following options:
1000 \i Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
1001 \i Set the Qt::AA_NativeWindows attribute on your application. All
1002 widgets will be native widgets.
1003 \i Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
1004 and all of its ancestors will become native (unless
1005 Qt::WA_DontCreateNativeAncestors is set).
1006 \i Call QWidget::winId to enforce a native window (this implies 3).
1007 \i Set the Qt::WA_PaintOnScreen attribute to enforce a native window
1011 \sa QEvent, QPainter, QGridLayout, QBoxLayout
1015 Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
1016 other visual representation on the screen that is generally located next to its
1017 physical counterpart. They are most often found on mobile phone platforms. In
1018 modern touch based user interfaces it is also possible to have softkeys that do
1019 not correspond to any physical keys. Softkeys differ from other onscreen labels
1020 in that they are contextual.
1022 In Qt, contextual softkeys are added to a widget by calling addAction() and
1023 passing a \c QAction with a softkey role set on it. When the widget
1024 containing the softkey actions has focus, its softkeys should appear in
1025 the user interface. Softkeys are discovered by traversing the widget
1026 hierarchy so it is possible to define a single set of softkeys that are
1027 present at all times by calling addAction() for a given top level widget.
1029 On some platforms, this concept overlaps with \c QMenuBar such that if no
1030 other softkeys are found and the top level widget is a QMainWindow containing
1031 a QMenuBar, the menubar actions may appear on one of the softkeys.
1033 Note: Currently softkeys are only supported on the Symbian Platform.
1035 \sa addAction(), QAction, QMenuBar
1039 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
1040 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
1043 /*****************************************************************************
1044 QWidget utility functions
1045 *****************************************************************************/
1047 QRegion qt_dirtyRegion(QWidget *widget)
1052 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
1056 return bs->dirtyRegion(widget);
1059 /*****************************************************************************
1060 QWidget member functions
1061 *****************************************************************************/
1066 \i Qt::WA_WState_Created The widget has a valid winId().
1067 \i Qt::WA_WState_Visible The widget is currently visible.
1068 \i Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
1069 become visible unless you call show() on it. Qt::WA_WState_Hidden
1070 implies !Qt::WA_WState_Visible.
1071 \i Qt::WA_WState_CompressKeys Compress keyboard events.
1072 \i Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
1073 \i Qt::WA_WState_InPaintEvent Currently processing a paint event.
1074 \i Qt::WA_WState_Reparented The widget has been reparented.
1075 \i Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
1076 \i Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
1080 struct QWidgetExceptionCleaner
1082 /* this cleans up when the constructor throws an exception */
1083 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
1085 #ifdef QT_NO_EXCEPTIONS
1089 QWidgetPrivate::allWidgets->remove(that);
1090 if (d->focus_next != that) {
1092 d->focus_next->d_func()->focus_prev = d->focus_prev;
1094 d->focus_prev->d_func()->focus_next = d->focus_next;
1101 Constructs a widget which is a child of \a parent, with widget
1104 If \a parent is 0, the new widget becomes a window. If
1105 \a parent is another widget, this widget becomes a child window
1106 inside \a parent. The new widget is deleted when its \a parent is
1109 The widget flags argument, \a f, is normally 0, but it can be set
1110 to customize the frame of a window (i.e. \a
1111 parent must be 0). To customize the frame, use a value composed
1112 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1114 If you add a child widget to an already visible widget you must
1115 explicitly show the child to make it visible.
1117 Note that the X11 version of Qt may not be able to deliver all
1118 combinations of style flags on all systems. This is because on
1119 X11, Qt can only ask the window manager, and the window manager
1120 can override the application's settings. On Windows, Qt can set
1121 whatever flags you want.
1125 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1126 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1129 d_func()->init(parent, f);
1131 QWidgetExceptionCleaner::cleanup(this, d_func());
1141 QWidget::QWidget(QWidget *parent, const char *name, Qt::WindowFlags f)
1142 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1145 d_func()->init(parent , f);
1146 setObjectName(QString::fromAscii(name));
1148 QWidgetExceptionCleaner::cleanup(this, d_func());
1156 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1157 : QObject(dd, 0), QPaintDevice()
1163 QWidgetExceptionCleaner::cleanup(this, d_func());
1171 int QWidget::devType() const
1173 return QInternal::Widget;
1177 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1178 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1180 bool customize = (flags & (Qt::CustomizeWindowHint
1181 | Qt::FramelessWindowHint
1182 | Qt::WindowTitleHint
1183 | Qt::WindowSystemMenuHint
1184 | Qt::WindowMinimizeButtonHint
1185 | Qt::WindowMaximizeButtonHint
1186 | Qt::WindowCloseButtonHint
1187 | Qt::WindowContextHelpButtonHint));
1189 uint type = (flags & Qt::WindowType_Mask);
1191 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1193 flags |= Qt::Window;
1196 if (flags & Qt::CustomizeWindowHint) {
1197 // modify window flags to make them consistent.
1198 // Only enable this on non-Mac platforms. Since the old way of doing this would
1199 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1200 // we can't just add this in.
1202 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1203 flags |= Qt::WindowSystemMenuHint;
1205 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1206 | Qt::WindowSystemMenuHint)) {
1208 flags |= Qt::WindowTitleHint;
1209 flags &= ~Qt::FramelessWindowHint;
1211 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1212 // if any of the window hints that affect the titlebar are set
1213 // and the window is supposed to have frame, we add a titlebar
1214 // and system menu by default.
1215 flags |= Qt::WindowSystemMenuHint;
1216 flags |= Qt::WindowTitleHint;
1219 ; // don't modify window flags if the user explicitly set them.
1220 else if (type == Qt::Dialog || type == Qt::Sheet)
1222 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1224 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1226 else if (type == Qt::Tool)
1227 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1229 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1234 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1237 if (QApplication::type() == QApplication::Tty)
1238 qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1240 Q_ASSERT(allWidgets);
1242 allWidgets->insert(q);
1244 QWidget *desktopWidget = 0;
1245 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1246 desktopWidget = parentWidget;
1252 #ifndef QT_NO_THREAD
1254 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1255 "Widgets must be created in the GUI thread.");
1259 #if defined(Q_WS_X11)
1260 if (desktopWidget) {
1261 // make sure the widget is created on the same screen as the
1262 // programmer specified desktop widget
1263 xinfo = desktopWidget->d_func()->xinfo;
1265 #elif defined(Q_OS_SYMBIAN)
1266 if (desktopWidget) {
1267 symbianScreenNumber = qt_widget_private(desktopWidget)->symbianScreenNumber;
1269 #elif defined(Q_WS_QPA)
1270 if (desktopWidget) {
1271 int screen = desktopWidget->d_func()->topData()->screenIndex;
1272 q->windowHandle()->setScreen(QGuiApplication::screens().value(screen, 0));
1275 Q_UNUSED(desktopWidget);
1278 data.fstrut_dirty = true;
1281 data.widget_attributes = 0;
1282 data.window_flags = f;
1283 data.window_state = 0;
1284 data.focus_policy = 0;
1285 data.context_menu_policy = Qt::DefaultContextMenu;
1286 data.window_modality = Qt::NonModal;
1288 data.sizehint_forced = 0;
1289 data.is_closing = 0;
1291 data.in_set_window_state = 0;
1292 data.in_destructor = false;
1294 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1295 if (f & Qt::MSWindowsOwnDC)
1296 q->setAttribute(Qt::WA_NativeWindow);
1299 // q->setAttribute(Qt::WA_NativeWindow);
1302 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1303 adjustQuitOnCloseAttribute();
1305 q->setAttribute(Qt::WA_WState_Hidden);
1307 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1310 // Don't waste GPU mem for unnecessary large egl surface until resized by application
1311 data.crect = QRect(0,0,1,1);
1313 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,360,640);
1316 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1319 focus_next = focus_prev = q;
1321 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1323 else if (parentWidget)
1324 q->setParent(parentWidget, data.window_flags);
1326 adjustFlags(data.window_flags, q);
1327 resolveLayoutDirection();
1328 // opaque system background?
1329 const QBrush &background = q->palette().brush(QPalette::Window);
1330 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1332 data.fnt = QFont(data.fnt, q);
1333 #if defined(Q_WS_X11)
1334 data.fnt.x11SetScreen(xinfo.screen());
1337 q->setAttribute(Qt::WA_PendingMoveEvent);
1338 q->setAttribute(Qt::WA_PendingResizeEvent);
1340 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1341 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1343 if (QApplicationPrivate::app_compile_version < 0x040200
1344 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1348 QEvent e(QEvent::Create);
1349 QApplication::sendEvent(q, &e);
1350 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1352 extraPaintEngine = 0;
1354 #ifdef QT_MAC_USE_COCOA
1355 // If we add a child to the unified toolbar, we have to redirect the painting.
1356 if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1357 if (parentWidget->d_func()->unifiedSurface) {
1358 QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1359 parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1362 #endif // QT_MAC_USE_COCOA
1367 void QWidgetPrivate::createRecursively()
1370 q->create(0, true, true);
1371 for (int i = 0; i < children.size(); ++i) {
1372 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1373 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1374 child->d_func()->createRecursively();
1382 Creates a new widget window if \a window is 0, otherwise sets the
1383 widget's window to \a window.
1385 Initializes the window (sets the geometry etc.) if \a
1386 initializeWindow is true. If \a initializeWindow is false, no
1387 initialization is performed. This parameter only makes sense if \a
1388 window is a valid window.
1390 Destroys the old window if \a destroyOldWindow is true. If \a
1391 destroyOldWindow is false, you are responsible for destroying the
1392 window yourself (using platform native code).
1394 The QWidget constructor calls create(0,true,true) to create a
1395 window for this widget.
1398 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1401 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1404 if (d->data.in_destructor)
1407 Qt::WindowType type = windowType();
1408 Qt::WindowFlags &flags = data->window_flags;
1410 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1412 flags |= Qt::Window;
1415 if (QWidget *parent = parentWidget()) {
1416 if (type & Qt::Window) {
1417 if (!parent->testAttribute(Qt::WA_WState_Created))
1418 parent->createWinId();
1419 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1420 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1421 // We're about to create a native child widget that doesn't have a native parent;
1422 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1423 // attribute is set.
1424 d->createWinId(window);
1425 // Nothing more to do.
1426 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1427 Q_ASSERT(internalWinId());
1433 if (flags & Qt::WStaticContents)
1434 setAttribute(Qt::WA_StaticContents);
1435 if (flags & Qt::WDestructiveClose)
1436 setAttribute(Qt::WA_DeleteOnClose);
1437 if (flags & Qt::WShowModal)
1438 setWindowModality(Qt::ApplicationModal);
1439 if (flags & Qt::WMouseNoMask)
1440 setAttribute(Qt::WA_MouseNoMask);
1441 if (flags & Qt::WGroupLeader)
1442 setAttribute(Qt::WA_GroupLeader);
1443 if (flags & Qt::WNoMousePropagation)
1444 setAttribute(Qt::WA_NoMousePropagation);
1447 static int paintOnScreenEnv = -1;
1448 if (paintOnScreenEnv == -1)
1449 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1450 if (paintOnScreenEnv == 1)
1451 setAttribute(Qt::WA_PaintOnScreen);
1453 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1454 setAttribute(Qt::WA_NativeWindow);
1457 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1458 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1461 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1462 // Unregister the dropsite (if already registered) before we
1463 // re-create the widget with a native window.
1464 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1465 && d->extra && d->extra->dropTarget) {
1466 d->registerDropSite(false);
1468 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1470 d->updateIsOpaque();
1472 setAttribute(Qt::WA_WState_Created); // set created flag
1473 d->create_sys(window, initializeWindow, destroyOldWindow);
1475 // a real toplevel window needs a backing store
1476 if (isWindow() && windowType() != Qt::Desktop) {
1477 d->topData()->backingStoreTracker.destroy();
1478 if (hasBackingStoreSupport())
1479 d->topData()->backingStoreTracker.create(this);
1484 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1485 setAttribute(Qt::WA_DropSiteRegistered, true);
1488 extern void qt_eval_init_widget(QWidget *w);
1489 qt_eval_init_widget(this);
1492 // need to force the resting of the icon after changing parents
1493 if (testAttribute(Qt::WA_SetWindowIcon))
1494 d->setWindowIcon_sys(true);
1495 if (isWindow() && !d->topData()->iconText.isEmpty())
1496 d->setWindowIconText_helper(d->topData()->iconText);
1497 if (isWindow() && !d->topData()->caption.isEmpty())
1498 d->setWindowTitle_helper(d->topData()->caption);
1499 if (windowType() != Qt::Desktop) {
1500 d->updateSystemBackground();
1502 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1503 d->setWindowIcon_sys();
1508 Destroys the widget.
1510 All this widget's children are deleted first. The application
1511 exits if this widget is the main widget.
1517 d->data.in_destructor = true;
1519 #if defined (QT_CHECK_STATE)
1520 if (paintingActive())
1521 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1524 #ifndef QT_NO_GESTURES
1525 foreach (Qt::GestureType type, d->gestureContext.keys())
1526 ungrabGesture(type);
1529 // force acceptDrops false before winId is destroyed.
1530 d->registerDropSite(false);
1532 #ifndef QT_NO_ACTION
1533 // remove all actions from this widget
1534 for (int i = 0; i < d->actions.size(); ++i) {
1535 QActionPrivate *apriv = d->actions.at(i)->d_func();
1536 apriv->widgets.removeAll(this);
1541 #ifndef QT_NO_SHORTCUT
1542 // Remove all shortcuts grabbed by this
1543 // widget, unless application is closing
1544 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1545 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1548 // delete layout while we still are a valid widget
1551 // Remove myself from focus list
1553 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1554 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1556 if (d->focus_next != this) {
1557 d->focus_next->d_func()->focus_prev = d->focus_prev;
1558 d->focus_prev->d_func()->focus_next = d->focus_next;
1559 d->focus_next = d->focus_prev = 0;
1563 if (QApplicationPrivate::main_widget == this) { // reset main widget
1564 QApplicationPrivate::main_widget = 0;
1565 QApplication::quit();
1572 // swallow this problem because we are in a destructor
1575 d->setDirtyOpaqueRegion();
1577 if (isWindow() && isVisible() && internalWinId()) {
1579 d->close_helper(QWidgetPrivate::CloseNoEvent);
1581 // if we're out of memory, at least hide the window.
1585 // and if that also doesn't work, then give up
1590 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1591 else if (!internalWinId() && isVisible()) {
1592 qApp->d_func()->sendSyntheticEnterLeave(this);
1594 #elif defined(Q_WS_QPA)
1595 else if (isVisible()) {
1596 qApp->d_func()->sendSyntheticEnterLeave(this);
1601 if (d->extra && d->extra->topextra && d->extra->topextra->backingStore) {
1602 // Okay, we are about to destroy the top-level window that owns
1603 // the backing store. Make sure we delete the backing store right away
1604 // before the window handle is invalid. This is important because
1605 // the backing store will delete its window surface, which may or may
1606 // not have a reference to this widget that will be used later to
1607 // notify the window it no longer has a surface.
1608 d->extra->topextra->backingStore.destroy();
1611 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1612 bs->removeDirtyWidget(this);
1613 if (testAttribute(Qt::WA_StaticContents))
1614 bs->removeStaticWidget(this);
1617 delete d->needsFlush;
1620 // set all QPointers for this object to zero
1622 QObjectPrivate::clearGuards(this);
1624 if (d->declarativeData) {
1625 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1626 d->declarativeData = 0; // don't activate again in ~QObject
1629 #ifdef QT_MAC_USE_COCOA
1630 // QCocoaView holds a pointer back to this widget. Clear it now
1631 // to make sure it's not followed later on. The lifetime of the
1632 // QCocoaView might exceed the lifetime of this widget in cases
1633 // where Cocoa itself holds references to it.
1634 extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1635 qt_mac_clearCocoaViewQWidgetPointers(this);
1638 if (!d->children.isEmpty())
1639 d->deleteChildren();
1641 QApplication::removePostedEvents(this);
1644 destroy(); // platform-dependent cleanup
1646 // if this fails we can't do anything about it but at least we are not allowed to throw.
1648 --QWidgetPrivate::instanceCounter;
1650 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1651 QWidgetPrivate::allWidgets->remove(this);
1654 QEvent e(QEvent::Destroy);
1655 QCoreApplication::sendEvent(this, &e);
1656 } QT_CATCH(const std::exception&) {
1657 // if this fails we can't do anything about it but at least we are not allowed to throw.
1661 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1662 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1664 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1667 // the user might create a widget with Qt::Desktop window
1668 // attribute (or create another QDesktopWidget instance), which
1669 // will have the same windowid (the root window id) as the
1670 // qt_desktopWidget. We should not add the second desktop widget
1672 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1673 if (mapper && data.winid && !userDesktopWidget) {
1674 mapper->remove(data.winid);
1677 const WId oldWinId = data.winid;
1680 #if defined(Q_WS_X11)
1681 hd = id; // X11: hd == ident
1683 if (mapper && id && !userDesktopWidget) {
1684 mapper->insert(data.winid, q);
1687 if(oldWinId != id) {
1688 QEvent e(QEvent::WinIdChange);
1689 QCoreApplication::sendEvent(q, &e);
1693 void QWidgetPrivate::createTLExtra()
1697 if (!extra->topextra) {
1698 QTLWExtra* x = extra->topextra = new QTLWExtra;
1701 x->backingStore = 0;
1702 x->sharedPainter = 0;
1703 x->incw = x->inch = 0;
1704 x->basew = x->baseh = 0;
1705 x->frameStrut.setCoords(0, 0, 0, 0);
1706 x->normalGeometry = QRect(0,0,-1,-1);
1709 x->posFromMove = false;
1710 x->sizeAdjusted = false;
1711 x->inTopLevelResize = false;
1712 x->inRepaint = false;
1715 #ifdef QT_MAC_USE_COCOA
1716 x->wasMaximized = false;
1717 #endif // QT_MAC_USE_COCOA
1720 #ifdef QWIDGET_EXTRA_DEBUG
1721 static int count = 0;
1722 qDebug() << "tlextra" << ++count;
1729 Creates the widget extra data.
1732 void QWidgetPrivate::createExtra()
1734 if (!extra) { // if not exists
1735 extra = new QWExtra;
1736 extra->glContext = 0;
1737 extra->topextra = 0;
1738 #ifndef QT_NO_GRAPHICSVIEW
1739 extra->proxyWidget = 0;
1741 #ifndef QT_NO_CURSOR
1746 extra->maxw = QWIDGETSIZE_MAX;
1747 extra->maxh = QWIDGETSIZE_MAX;
1748 extra->customDpiX = 0;
1749 extra->customDpiY = 0;
1750 extra->explicitMinSize = 0;
1751 extra->explicitMaxSize = 0;
1752 extra->autoFillBackground = 0;
1753 extra->nativeChildrenForced = 0;
1754 extra->inRenderWithPainter = 0;
1757 #ifdef QWIDGET_EXTRA_DEBUG
1758 static int count = 0;
1759 qDebug() << "extra" << ++count;
1767 Deletes the widget extra data.
1770 void QWidgetPrivate::deleteExtra()
1772 if (extra) { // if exists
1773 #ifndef QT_NO_CURSOR
1777 #ifndef QT_NO_STYLE_STYLESHEET
1778 // dereference the stylesheet style
1779 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1782 if (extra->topextra) {
1784 extra->topextra->backingStoreTracker.destroy();
1785 delete extra->topextra->icon;
1786 delete extra->topextra->iconPixmap;
1787 delete extra->topextra->backingStore;
1788 delete extra->topextra;
1791 // extra->xic destroyed in QWidget::destroy()
1797 Returns true if there are widgets above this which overlap with
1798 \a rect, which is in parent's coordinate system (same as crect).
1801 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1805 const QWidget *w = q;
1810 QWidgetPrivate *pd = w->parentWidget()->d_func();
1812 for (int i = 0; i < pd->children.size(); ++i) {
1813 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1814 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1817 above = (sibling == w);
1821 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1822 const QWExtra *siblingExtra = sibling->d_func()->extra;
1823 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1824 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1830 w = w->parentWidget();
1831 r.translate(pd->data.crect.topLeft());
1836 void QWidgetPrivate::syncBackingStore()
1838 if (paintOnScreen()) {
1841 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1846 void QWidgetPrivate::syncBackingStore(const QRegion ®ion)
1848 if (paintOnScreen())
1849 repaint_sys(region);
1850 else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1851 bs->sync(q_func(), region);
1855 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1859 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1860 return; // nothing we can do
1862 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1863 return; // nothing to do
1865 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1869 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1870 for (int i = 0; i < children.size(); ++i) {
1871 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1872 if (w && !w->isWindow() && !w->testAttribute(attribute))
1873 w->d_func()->setUpdatesEnabled_helper(enable);
1880 Propagate this widget's palette to all children, except style sheet
1881 widgets, and windows that don't enable window propagation (palettes don't
1882 normally propagate to windows).
1884 void QWidgetPrivate::propagatePaletteChange()
1887 // Propagate a new inherited mask to all children.
1888 #ifndef QT_NO_GRAPHICSVIEW
1889 if (!q->parentWidget() && extra && extra->proxyWidget) {
1890 QGraphicsProxyWidget *p = extra->proxyWidget;
1891 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1893 #endif //QT_NO_GRAPHICSVIEW
1894 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1895 inheritedPaletteResolveMask = 0;
1897 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1899 QEvent pc(QEvent::PaletteChange);
1900 QApplication::sendEvent(q, &pc);
1901 for (int i = 0; i < children.size(); ++i) {
1902 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1903 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1904 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1905 QWidgetPrivate *wd = w->d_func();
1906 wd->inheritedPaletteResolveMask = mask;
1907 wd->resolvePalette();
1910 #if defined(QT3_SUPPORT)
1911 q->paletteChange(q->palette()); // compatibility
1916 Returns the widget's clipping rectangle.
1918 QRect QWidgetPrivate::clipRect() const
1921 const QWidget * w = q;
1922 if (!w->isVisible())
1924 QRect r = effectiveRectFor(q->rect());
1930 && w->parentWidget()) {
1933 w = w->parentWidget();
1934 r &= QRect(ox, oy, w->width(), w->height());
1940 Returns the widget's clipping region (without siblings).
1942 QRegion QWidgetPrivate::clipRegion() const
1945 if (!q->isVisible())
1947 QRegion r(q->rect());
1948 const QWidget * w = q;
1949 const QWidget *ignoreUpTo;
1955 && w->parentWidget()) {
1959 w = w->parentWidget();
1960 r &= QRegion(ox, oy, w->width(), w->height());
1963 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1965 for ( ; i < w->d_func()->children.size(); ++i) {
1966 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1967 if(sibling->isVisible() && !sibling->isWindow()) {
1968 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1969 sibling->width(), sibling->height());
1970 if (qRectIntersects(siblingRect, q->rect()))
1971 r -= QRegion(siblingRect);
1979 #ifndef QT_NO_GRAPHICSEFFECT
1980 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1985 if (w->graphicsEffect()) {
1986 QWidgetEffectSourcePrivate *sourced =
1987 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1988 if (!sourced->updateDueToGraphicsEffect)
1989 w->graphicsEffect()->source()->d_func()->invalidateCache();
1991 w = w->parentWidget();
1994 #endif //QT_NO_GRAPHICSEFFECT
1996 void QWidgetPrivate::setDirtyOpaqueRegion()
2000 dirtyOpaqueChildren = true;
2002 #ifndef QT_NO_GRAPHICSEFFECT
2003 invalidateGraphicsEffectsRecursively();
2004 #endif //QT_NO_GRAPHICSEFFECT
2009 QWidget *parent = q->parentWidget();
2013 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
2014 QWidgetPrivate *pd = parent->d_func();
2015 if (!pd->dirtyOpaqueChildren)
2016 pd->setDirtyOpaqueRegion();
2019 const QRegion &QWidgetPrivate::getOpaqueChildren() const
2021 if (!dirtyOpaqueChildren)
2022 return opaqueChildren;
2024 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
2025 that->opaqueChildren = QRegion();
2027 for (int i = 0; i < children.size(); ++i) {
2028 QWidget *child = qobject_cast<QWidget *>(children.at(i));
2029 if (!child || !child->isVisible() || child->isWindow())
2032 const QPoint offset = child->geometry().topLeft();
2033 QWidgetPrivate *childd = child->d_func();
2034 QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
2035 if (childd->extra && childd->extra->hasMask)
2036 r &= childd->extra->mask;
2039 r.translate(offset);
2040 that->opaqueChildren += r;
2043 that->opaqueChildren &= q_func()->rect();
2044 that->dirtyOpaqueChildren = false;
2046 return that->opaqueChildren;
2049 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
2051 if (children.isEmpty() || clipRect.isEmpty())
2054 const QRegion &r = getOpaqueChildren();
2056 source -= (r & clipRect);
2059 //subtract any relatives that are higher up than me --- this is too expensive !!!
2060 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
2061 bool alsoNonOpaque) const
2064 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
2065 if (disableSubtractOpaqueSiblings || q->isWindow())
2068 #ifdef QT_MAC_USE_COCOA
2069 if (q->d_func()->isInUnifiedToolbar)
2071 #endif // QT_MAC_USE_COCOA
2073 QRect clipBoundingRect;
2074 bool dirtyClipBoundingRect = true;
2077 bool dirtyParentClip = true;
2079 QPoint parentOffset = data.crect.topLeft();
2081 const QWidget *w = q;
2086 QWidgetPrivate *pd = w->parentWidget()->d_func();
2087 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
2088 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
2089 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
2090 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
2091 if (!sibling || !sibling->isVisible() || sibling->isWindow())
2094 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
2095 if (!qRectIntersects(siblingGeometry, widgetGeometry))
2098 if (dirtyClipBoundingRect) {
2099 clipBoundingRect = sourceRegion.boundingRect();
2100 dirtyClipBoundingRect = false;
2103 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
2106 if (dirtyParentClip) {
2107 parentClip = sourceRegion.translated(parentOffset);
2108 dirtyParentClip = false;
2111 const QPoint siblingPos(sibling->data->crect.topLeft());
2112 const QRect siblingClipRect(sibling->d_func()->clipRect());
2113 QRegion siblingDirty(parentClip);
2114 siblingDirty &= (siblingClipRect.translated(siblingPos));
2115 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
2116 && !sibling->d_func()->graphicsEffect;
2118 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
2119 if (siblingDirty.isEmpty())
2122 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
2124 siblingDirty.translate(-parentOffset);
2125 sourceRegion -= siblingDirty;
2127 sourceRegion -= siblingGeometry.translated(-parentOffset);
2130 if (hasDirtySiblingsAbove)
2131 *hasDirtySiblingsAbove = true;
2132 if (sibling->d_func()->children.isEmpty())
2134 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
2135 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
2136 sourceRegion -= opaqueSiblingChildren;
2138 if (sourceRegion.isEmpty())
2141 dirtyClipBoundingRect = true;
2142 dirtyParentClip = true;
2145 w = w->parentWidget();
2146 parentOffset += pd->data.crect.topLeft();
2147 dirtyParentClip = true;
2151 void QWidgetPrivate::clipToEffectiveMask(QRegion ®ion) const
2155 const QWidget *w = q;
2158 #ifndef QT_NO_GRAPHICSEFFECT
2159 if (graphicsEffect) {
2160 w = q->parentWidget();
2161 offset -= data.crect.topLeft();
2163 #endif //QT_NO_GRAPHICSEFFECT
2166 const QWidgetPrivate *wd = w->d_func();
2167 if (wd->extra && wd->extra->hasMask)
2168 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
2171 offset -= wd->data.crect.topLeft();
2172 w = w->parentWidget();
2176 bool QWidgetPrivate::paintOnScreen() const
2178 #if defined(QT_NO_BACKINGSTORE)
2182 if (q->testAttribute(Qt::WA_PaintOnScreen)
2183 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2187 return !qt_enable_backingstore;
2191 void QWidgetPrivate::updateIsOpaque()
2193 // hw: todo: only needed if opacity actually changed
2194 setDirtyOpaqueRegion();
2196 #ifndef QT_NO_GRAPHICSEFFECT
2197 if (graphicsEffect) {
2198 // ### We should probably add QGraphicsEffect::isOpaque at some point.
2202 #endif //QT_NO_GRAPHICSEFFECT
2206 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2213 if (q->windowType() == Qt::Dialog && q->testAttribute(Qt::WA_TranslucentBackground)
2214 && S60->avkonComponentsSupportTransparency) {
2220 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2225 const QPalette &pal = q->palette();
2227 if (q->autoFillBackground()) {
2228 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2229 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2235 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2236 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2237 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2245 void QWidgetPrivate::setOpaque(bool opaque)
2247 if (isOpaque == opaque)
2251 macUpdateIsOpaque();
2254 x11UpdateIsOpaque();
2257 winUpdateIsOpaque();
2260 s60UpdateIsOpaque();
2264 void QWidgetPrivate::updateIsTranslucent()
2267 macUpdateIsOpaque();
2270 x11UpdateIsOpaque();
2273 winUpdateIsOpaque();
2276 s60UpdateIsOpaque();
2280 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2284 if (brush.style() == Qt::TexturePattern) {
2286 // Optimize pattern filling on mac by using HITheme directly
2287 // when filling with the standard widget background.
2288 // Defined in qmacstyle_mac.cpp
2289 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2290 qt_mac_fill_background(painter, rgn, brush);
2292 #if !defined(QT_NO_STYLE_S60)
2293 // Defined in qs60style.cpp
2294 extern bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2295 if (!qt_s60_fill_background(painter, rgn, brush))
2296 #endif // !defined(QT_NO_STYLE_S60)
2298 const QRect rect(rgn.boundingRect());
2299 painter->setClipRegion(rgn);
2300 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2304 } else if (brush.gradient()
2305 && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2307 painter->setClipRegion(rgn);
2308 painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2311 const QVector<QRect> &rects = rgn.rects();
2312 for (int i = 0; i < rects.size(); ++i)
2313 painter->fillRect(rects.at(i), brush);
2317 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2321 #ifndef QT_NO_SCROLLAREA
2322 bool resetBrushOrigin = false;
2323 QPointF oldBrushOrigin;
2324 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2325 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2326 if (scrollArea && scrollArea->viewport() == q) {
2327 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2328 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2329 oldBrushOrigin = painter->brushOrigin();
2330 resetBrushOrigin = true;
2331 painter->setBrushOrigin(-priv->contentsOffset());
2334 #endif // QT_NO_SCROLLAREA
2336 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2338 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2339 const QBrush bg = q->palette().brush(QPalette::Window);
2340 fillRegion(painter, rgn, bg);
2343 if (q->autoFillBackground())
2344 fillRegion(painter, rgn, autoFillBrush);
2346 if (q->testAttribute(Qt::WA_StyledBackground)) {
2347 painter->setClipRegion(rgn);
2350 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2353 #ifndef QT_NO_SCROLLAREA
2354 if (resetBrushOrigin)
2355 painter->setBrushOrigin(oldBrushOrigin);
2356 #endif // QT_NO_SCROLLAREA
2361 This function is called when a widget is hidden or destroyed.
2362 It resets some application global pointers that should only refer active,
2367 extern QPointer<QWidget> qt_button_down;
2369 extern QWidget *qt_button_down;
2372 void QWidgetPrivate::deactivateWidgetCleanup()
2375 // If this was the active application window, reset it
2376 if (QApplication::activeWindow() == q)
2377 QApplication::setActiveWindow(0);
2378 // If the is the active mouse press widget, reset it
2379 if (q == qt_button_down)
2385 Returns a pointer to the widget with window identifer/handle \a
2388 The window identifier type depends on the underlying window
2389 system, see \c qwindowdefs.h for the actual definition. If there
2390 is no widget with this identifier, 0 is returned.
2393 QWidget *QWidget::find(WId id)
2395 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2401 \fn WId QWidget::internalWinId() const
2403 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2408 \fn WId QWidget::winId() const
2410 Returns the window system identifier of the widget.
2412 Portable in principle, but if you use it you are probably about to
2413 do something non-portable. Be careful.
2415 If a widget is non-native (alien) and winId() is invoked on it, that widget
2416 will be provided a native handle.
2418 On Mac OS X, the type returned depends on which framework Qt was linked
2419 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2420 is using Cocoa, {WId} is a pointer to an NSView.
2422 This value may change at run-time. An event with type QEvent::WinIdChange
2423 will be sent to the widget following a change in window system identifier.
2427 WId QWidget::winId() const
2429 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2431 qDebug() << "QWidget::winId: creating native window for" << this;
2433 QWidget *that = const_cast<QWidget*>(this);
2434 that->setAttribute(Qt::WA_NativeWindow);
2435 that->d_func()->createWinId();
2436 return that->data->winid;
2442 void QWidgetPrivate::createWinId(WId winid)
2447 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2449 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2450 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2451 if (!q->isWindow()) {
2452 QWidget *parent = q->parentWidget();
2453 QWidgetPrivate *pd = parent->d_func();
2454 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2455 parent->setAttribute(Qt::WA_NativeWindow);
2456 if (!parent->internalWinId()) {
2460 for (int i = 0; i < pd->children.size(); ++i) {
2461 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2462 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2463 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2468 // if the window has already been created, we
2469 // need to raise it to its proper stacking position
2484 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2488 void QWidget::createWinId()
2492 qDebug() << "QWidget::createWinId" << this;
2494 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2501 Returns the effective window system identifier of the widget, i.e. the
2502 native parent's window system identifier.
2504 If the widget is native, this function returns the native widget ID.
2505 Otherwise, the window ID of the first native parent widget, i.e., the
2506 top-level widget that contains this widget, is returned.
2508 \note We recommend that you do not store this value as it is likely to
2511 \sa nativeParentWidget()
2513 WId QWidget::effectiveWinId() const
2515 WId id = internalWinId();
2516 if (id || !testAttribute(Qt::WA_WState_Created))
2518 QWidget *realParent = nativeParentWidget();
2519 if (!realParent && d_func()->inSetParent) {
2520 // In transitional state. This is really just a workaround. The real problem
2521 // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2522 // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2523 // attribute to false. The correct way is to do it the other way around, and
2524 // in that case the Qt::WA_WState_Created logic above will kick in and
2525 // return 0 whenever the widget is in a transitional state. However, changing
2526 // the original logic for all platforms is far more intrusive and might
2527 // break existing applications.
2528 // Note: The widget can only be in a transitional state when changing its
2529 // parent -- everything else is an internal error -- hence explicitly checking
2530 // against 'inSetParent' rather than doing an unconditional return whenever
2531 // 'realParent' is 0 (which may cause strange artifacts and headache later).
2534 // This widget *must* have a native parent widget.
2535 Q_ASSERT(realParent);
2536 Q_ASSERT(realParent->internalWinId());
2537 return realParent->internalWinId();
2540 #ifndef QT_NO_STYLE_STYLESHEET
2543 \property QWidget::styleSheet
2544 \brief the widget's style sheet
2547 The style sheet contains a textual description of customizations to the
2548 widget's style, as described in the \l{Qt Style Sheets} document.
2550 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2552 \warning Qt style sheets are currently not supported for custom QStyle
2553 subclasses. We plan to address this in some future release.
2555 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2557 QString QWidget::styleSheet() const
2562 return d->extra->styleSheet;
2565 void QWidget::setStyleSheet(const QString& styleSheet)
2570 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2571 d->extra->styleSheet = styleSheet;
2572 if (styleSheet.isEmpty()) { // stylesheet removed
2580 if (proxy) { // style sheet update
2581 proxy->repolish(this);
2585 if (testAttribute(Qt::WA_SetStyle)) {
2586 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2588 d->setStyle_helper(new QStyleSheetStyle(0), true);
2592 #endif // QT_NO_STYLE_STYLESHEET
2595 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2598 QStyle *QWidget::style() const
2602 if (d->extra && d->extra->style)
2603 return d->extra->style;
2604 return QApplication::style();
2608 Sets the widget's GUI style to \a style. The ownership of the style
2609 object is not transferred.
2611 If no style is set, the widget uses the application's style,
2612 QApplication::style() instead.
2614 Setting a widget's style has no effect on existing or future child
2617 \warning This function is particularly useful for demonstration
2618 purposes, where you want to show Qt's styling capabilities. Real
2619 applications should avoid it and use one consistent GUI style
2622 \warning Qt style sheets are currently not supported for custom QStyle
2623 subclasses. We plan to address this in some future release.
2625 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2628 void QWidget::setStyle(QStyle *style)
2631 setAttribute(Qt::WA_SetStyle, style != 0);
2633 #ifndef QT_NO_STYLE_STYLESHEET
2634 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2635 //if for some reason someone try to set a QStyleSheetStyle, ref it
2636 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2638 d->setStyle_helper(style, false);
2639 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2640 // if we have an application stylesheet or have a proxy already, propagate
2641 d->setStyle_helper(new QStyleSheetStyle(style), true);
2644 d->setStyle_helper(style, false);
2647 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2654 QStyle *oldStyle = q->style();
2655 #ifndef QT_NO_STYLE_STYLESHEET
2656 QWeakPointer<QStyle> origStyle;
2660 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2661 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2662 // set when changing that attribute and passes the widget's CURRENT style.
2663 // therefore no need to do a reassignment.
2669 #ifndef QT_NO_STYLE_STYLESHEET
2670 origStyle = extra->style.data();
2672 extra->style = newStyle;
2676 if (q->windowType() != Qt::Desktop) {
2678 oldStyle->unpolish(q);
2681 macUpdateMetalAttribute();
2683 q->style()->polish(q);
2685 } else if (metalHack) {
2686 macUpdateMetalAttribute();
2692 for (int i = 0; i < children.size(); ++i) {
2693 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2695 c->d_func()->inheritStyle();
2699 #ifndef QT_NO_STYLE_STYLESHEET
2700 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2701 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2702 cssStyle->clearWidgetFont(q);
2707 QEvent e(QEvent::StyleChange);
2708 QApplication::sendEvent(q, &e);
2710 q->styleChange(*oldStyle);
2713 #ifndef QT_NO_STYLE_STYLESHEET
2714 // dereference the old stylesheet style
2715 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2720 // Inherits style from the current parent and propagates it as necessary
2721 void QWidgetPrivate::inheritStyle()
2723 #ifndef QT_NO_STYLE_STYLESHEET
2726 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2728 if (!q->styleSheet().isEmpty()) {
2734 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2735 QWidget *parent = q->parentWidget();
2736 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2737 // If we have stylesheet on app or parent has stylesheet style, we need
2738 // to be running a proxy
2739 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2740 QStyle *newStyle = parentStyle;
2741 if (q->testAttribute(Qt::WA_SetStyle))
2742 newStyle = new QStyleSheetStyle(origStyle);
2743 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2746 setStyle_helper(newStyle, true);
2750 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2751 // we just need our original style back
2752 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2755 // We could have inherited the proxy from our parent (which has a custom style)
2756 // In such a case we need to start following the application style (i.e revert
2757 // the propagation behavior of QStyleSheetStyle)
2758 if (!q->testAttribute(Qt::WA_SetStyle))
2761 setStyle_helper(origStyle, true);
2762 #endif // QT_NO_STYLE_STYLESHEET
2769 Sets the widget's GUI style to \a style using the QStyleFactory.
2771 QStyle* QWidget::setStyle(const QString &style)
2773 QStyle *s = QStyleFactory::create(style);
2780 \fn bool QWidget::isWindow() const
2782 Returns true if the widget is an independent window, otherwise
2785 A window is a widget that isn't visually the child of any other
2786 widget and that usually has a frame and a
2787 \l{QWidget::setWindowTitle()}{window title}.
2789 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2790 It will then be grouped with its parent and deleted when the
2791 parent is deleted, minimized when the parent is minimized etc. If
2792 supported by the window manager, it will also have a common
2793 taskbar entry with its parent.
2795 QDialog and QMainWindow widgets are by default windows, even if a
2796 parent widget is specified in the constructor. This behavior is
2797 specified by the Qt::Window flag.
2799 \sa window(), isModal(), parentWidget()
2803 \property QWidget::modal
2804 \brief whether the widget is a modal widget
2806 This property only makes sense for windows. A modal widget
2807 prevents widgets in all other windows from getting any input.
2809 By default, this property is false.
2811 \sa isWindow(), windowModality, QDialog
2815 \property QWidget::windowModality
2816 \brief which windows are blocked by the modal widget
2819 This property only makes sense for windows. A modal widget
2820 prevents widgets in other windows from getting input. The value of
2821 this property controls which windows are blocked when the widget
2822 is visible. Changing this property while the window is visible has
2823 no effect; you must hide() the widget first, then show() it again.
2825 By default, this property is Qt::NonModal.
2827 \sa isWindow(), QWidget::modal, QDialog
2830 Qt::WindowModality QWidget::windowModality() const
2832 return static_cast<Qt::WindowModality>(data->window_modality);
2835 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2837 data->window_modality = windowModality;
2838 // setModal_sys() will be called by setAttribute()
2839 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2840 setAttribute(Qt::WA_SetWindowModality, true);
2844 \fn bool QWidget::underMouse() const
2846 Returns true if the widget is under the mouse cursor; otherwise
2849 This value is not updated properly during drag and drop
2852 \sa enterEvent(), leaveEvent()
2856 \property QWidget::minimized
2857 \brief whether this widget is minimized (iconified)
2859 This property is only relevant for windows.
2861 By default, this property is false.
2863 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2865 bool QWidget::isMinimized() const
2866 { return data->window_state & Qt::WindowMinimized; }
2869 Shows the widget minimized, as an icon.
2871 Calling this function only affects \l{isWindow()}{windows}.
2873 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2876 void QWidget::showMinimized()
2878 bool isMin = isMinimized();
2879 if (isMin && isVisible())
2885 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
2889 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2894 \property QWidget::maximized
2895 \brief whether this widget is maximized
2897 This property is only relevant for windows.
2899 \note Due to limitations on some window systems, this does not always
2900 report the expected results (e.g., if the user on X11 maximizes the
2901 window via the window manager, Qt has no way of distinguishing this
2902 from any other resize). This is expected to improve as window manager
2905 By default, this property is false.
2907 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2909 bool QWidget::isMaximized() const
2910 { return data->window_state & Qt::WindowMaximized; }
2915 Returns the current window state. The window state is a OR'ed
2916 combination of Qt::WindowState: Qt::WindowMinimized,
2917 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2919 \sa Qt::WindowState setWindowState()
2921 Qt::WindowStates QWidget::windowState() const
2923 return Qt::WindowStates(data->window_state);
2928 The function sets the window state on child widgets similar to
2929 setWindowState(). The difference is that the window state changed
2930 event has the isOverride() flag set. It exists mainly to keep
2931 Q3Workspace working.
2933 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2935 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2936 data->window_state = newstate;
2937 QApplication::sendEvent(this, &e);
2941 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2943 Sets the window state to \a windowState. The window state is a OR'ed
2944 combination of Qt::WindowState: Qt::WindowMinimized,
2945 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2947 If the window is not visible (i.e. isVisible() returns false), the
2948 window state will take effect when show() is called. For visible
2949 windows, the change is immediate. For example, to toggle between
2950 full-screen and normal mode, use the following code:
2952 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2954 In order to restore and activate a minimized window (while
2955 preserving its maximized and/or full-screen state), use the following:
2957 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2959 Calling this function will hide the widget. You must call show() to make
2960 the widget visible again.
2962 \note On some window systems Qt::WindowActive is not immediate, and may be
2963 ignored in certain cases.
2965 When the window state changes, the widget receives a changeEvent()
2966 of type QEvent::WindowStateChange.
2968 \sa Qt::WindowState windowState()
2972 \property QWidget::fullScreen
2973 \brief whether the widget is shown in full screen mode
2975 A widget in full screen mode occupies the whole screen area and does not
2976 display window decorations, such as a title bar.
2978 By default, this property is false.
2980 \sa windowState(), minimized, maximized
2982 bool QWidget::isFullScreen() const
2983 { return data->window_state & Qt::WindowFullScreen; }
2986 Shows the widget in full-screen mode.
2988 Calling this function only affects \l{isWindow()}{windows}.
2990 To return from full-screen mode, call showNormal().
2992 Full-screen mode works fine under Windows, but has certain
2993 problems under X. These problems are due to limitations of the
2994 ICCCM protocol that specifies the communication between X11
2995 clients and the window manager. ICCCM simply does not understand
2996 the concept of non-decorated full-screen windows. Therefore, the
2997 best we can do is to request a borderless window and place and
2998 resize it to fill the entire screen. Depending on the window
2999 manager, this may or may not work. The borderless window is
3000 requested using MOTIF hints, which are at least partially
3001 supported by virtually all modern window managers.
3003 An alternative would be to bypass the window manager entirely and
3004 create a window with the Qt::X11BypassWindowManagerHint flag. This
3005 has other severe problems though, like totally broken keyboard focus
3006 and very strange effects on desktop changes or when the user raises
3009 X11 window managers that follow modern post-ICCCM specifications
3010 support full-screen mode properly.
3012 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
3014 void QWidget::showFullScreen()
3017 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
3018 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
3019 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
3020 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
3021 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
3022 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
3028 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
3031 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
3032 | Qt::WindowFullScreen);
3038 Shows the widget maximized.
3040 Calling this function only affects \l{isWindow()}{windows}.
3042 On X11, this function may not work properly with certain window
3043 managers. See the \l{Window Geometry} documentation for an explanation.
3045 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
3047 void QWidget::showMaximized()
3052 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
3055 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
3056 | Qt::WindowMaximized);
3058 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
3059 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
3062 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
3063 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
3064 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
3065 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
3073 Restores the widget after it has been maximized or minimized.
3075 Calling this function only affects \l{isWindow()}{windows}.
3077 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
3079 void QWidget::showNormal()
3084 QApplication::sendPostedEvents(parent(), QEvent::ChildInserted);
3087 setWindowState(windowState() & ~(Qt::WindowMinimized
3088 | Qt::WindowMaximized
3089 | Qt::WindowFullScreen));
3091 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
3092 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
3095 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
3096 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
3097 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
3098 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
3106 Returns true if this widget would become enabled if \a ancestor is
3107 enabled; otherwise returns false.
3111 This is the case if neither the widget itself nor every parent up
3112 to but excluding \a ancestor has been explicitly disabled.
3114 isEnabledTo(0) is equivalent to isEnabled().
3116 \sa setEnabled() enabled
3119 bool QWidget::isEnabledTo(QWidget* ancestor) const
3121 const QWidget * w = this;
3122 while (!w->testAttribute(Qt::WA_ForceDisabled)
3124 && w->parentWidget()
3125 && w->parentWidget() != ancestor)
3126 w = w->parentWidget();
3127 return !w->testAttribute(Qt::WA_ForceDisabled);
3130 #ifndef QT_NO_ACTION
3132 Appends the action \a action to this widget's list of actions.
3134 All QWidgets have a list of \l{QAction}s, however they can be
3135 represented graphically in many different ways. The default use of
3136 the QAction list (as returned by actions()) is to create a context
3139 A QWidget should only have one of each action and adding an action
3140 it already has will not cause the same action to be in the widget twice.
3142 The ownership of \a action is not transferred to this QWidget.
3144 \sa removeAction(), insertAction(), actions(), QMenu
3146 void QWidget::addAction(QAction *action)
3148 insertAction(0, action);
3152 Appends the actions \a actions to this widget's list of actions.
3154 \sa removeAction(), QMenu, addAction()
3156 void QWidget::addActions(QList<QAction*> actions)
3158 for(int i = 0; i < actions.count(); i++)
3159 insertAction(0, actions.at(i));
3163 Inserts the action \a action to this widget's list of actions,
3164 before the action \a before. It appends the action if \a before is 0 or
3165 \a before is not a valid action for this widget.
3167 A QWidget should only have one of each action.
3169 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
3171 void QWidget::insertAction(QAction *before, QAction *action)
3174 qWarning("QWidget::insertAction: Attempt to insert null action");
3179 if(d->actions.contains(action))
3180 removeAction(action);
3182 int pos = d->actions.indexOf(before);
3185 pos = d->actions.size();
3187 d->actions.insert(pos, action);
3189 QActionPrivate *apriv = action->d_func();
3190 apriv->widgets.append(this);
3192 QActionEvent e(QEvent::ActionAdded, action, before);
3193 QApplication::sendEvent(this, &e);
3197 Inserts the actions \a actions to this widget's list of actions,
3198 before the action \a before. It appends the action if \a before is 0 or
3199 \a before is not a valid action for this widget.
3201 A QWidget can have at most one of each action.
3203 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
3205 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
3207 for(int i = 0; i < actions.count(); ++i)
3208 insertAction(before, actions.at(i));
3212 Removes the action \a action from this widget's list of actions.
3213 \sa insertAction(), actions(), insertAction()
3215 void QWidget::removeAction(QAction *action)
3222 QActionPrivate *apriv = action->d_func();
3223 apriv->widgets.removeAll(this);
3225 if (d->actions.removeAll(action)) {
3226 QActionEvent e(QEvent::ActionRemoved, action);
3227 QApplication::sendEvent(this, &e);
3232 Returns the (possibly empty) list of this widget's actions.
3234 \sa contextMenuPolicy, insertAction(), removeAction()
3236 QList<QAction*> QWidget::actions() const
3241 #endif // QT_NO_ACTION
3244 \fn bool QWidget::isEnabledToTLW() const
3247 This function is deprecated. It is equivalent to isEnabled()
3251 \property QWidget::enabled
3252 \brief whether the widget is enabled
3254 An enabled widget handles keyboard and mouse events; a disabled
3257 Some widgets display themselves differently when they are
3258 disabled. For example a button might draw its label grayed out. If
3259 your widget needs to know when it becomes enabled or disabled, you
3260 can use the changeEvent() with type QEvent::EnabledChange.
3262 Disabling a widget implicitly disables all its children. Enabling
3263 respectively enables all child widgets unless they have been
3264 explicitly disabled.
3266 By default, this property is true.
3268 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3270 void QWidget::setEnabled(bool enable)
3273 setAttribute(Qt::WA_ForceDisabled, !enable);
3274 d->setEnabled_helper(enable);
3277 void QWidgetPrivate::setEnabled_helper(bool enable)
3281 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3282 return; // nothing we can do
3284 if (enable != q->testAttribute(Qt::WA_Disabled))
3285 return; // nothing to do
3287 q->setAttribute(Qt::WA_Disabled, !enable);
3288 updateSystemBackground();
3290 if (!enable && q->window()->focusWidget() == q) {
3291 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3292 if (!parentIsEnabled || !q->focusNextChild())
3296 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3297 for (int i = 0; i < children.size(); ++i) {
3298 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3299 if (w && !w->testAttribute(attribute))
3300 w->d_func()->setEnabled_helper(enable);
3302 #if defined(Q_WS_X11)
3303 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3304 // enforce the windows behavior of clearing the cursor on
3306 qt_x11_enforce_cursor(q);
3308 #elif defined(Q_WS_QPA)
3309 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3310 // enforce the windows behavior of clearing the cursor on
3312 qt_qpa_set_cursor(q, false);
3315 #if defined(Q_WS_MAC)
3316 setEnabled_helper_sys(enable);
3319 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3320 QWidget *focusWidget = effectiveFocusWidget();
3321 QInputContext *qic = focusWidget->d_func()->inputContext();
3323 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3324 qic->setFocusWidget(focusWidget);
3327 qic->setFocusWidget(0);
3331 QEvent e(QEvent::EnabledChange);
3332 QApplication::sendEvent(q, &e);
3334 q->enabledChange(!enable); // compatibility
3339 \property QWidget::acceptDrops
3340 \brief whether drop events are enabled for this widget
3342 Setting this property to true announces to the system that this
3343 widget \e may be able to accept drop events.
3345 If the widget is the desktop (windowType() == Qt::Desktop), this may
3346 fail if another application is using the desktop; you can call
3347 acceptDrops() to test if this occurs.
3349 \warning Do not modify this property in a drag and drop event handler.
3351 By default, this property is false.
3355 bool QWidget::acceptDrops() const
3357 return testAttribute(Qt::WA_AcceptDrops);
3360 void QWidget::setAcceptDrops(bool on)
3362 setAttribute(Qt::WA_AcceptDrops, on);
3367 \fn void QWidget::enabledChange(bool)
3374 \fn void QWidget::paletteChange(const QPalette &)
3381 \fn void QWidget::fontChange(const QFont &)
3388 \fn void QWidget::windowActivationChange(bool)
3395 \fn void QWidget::languageChange()
3401 \fn void QWidget::styleChange(QStyle& style)
3408 Disables widget input events if \a disable is true; otherwise
3409 enables input events.
3411 See the \l enabled documentation for more information.
3413 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3415 void QWidget::setDisabled(bool disable)
3417 setEnabled(!disable);
3421 \property QWidget::frameGeometry
3422 \brief geometry of the widget relative to its parent including any
3425 See the \l{Window Geometry} documentation for an overview of geometry
3426 issues with windows.
3428 By default, this property contains a value that depends on the user's
3429 platform and screen geometry.
3431 \sa geometry() x() y() pos()
3433 QRect QWidget::frameGeometry() const
3436 if (isWindow() && ! (windowType() == Qt::Popup)) {
3437 QRect fs = d->frameStrut();
3438 return QRect(data->crect.x() - fs.left(),
3439 data->crect.y() - fs.top(),
3440 data->crect.width() + fs.left() + fs.right(),
3441 data->crect.height() + fs.top() + fs.bottom());
3447 \property QWidget::x
3449 \brief the x coordinate of the widget relative to its parent including
3452 See the \l{Window Geometry} documentation for an overview of geometry
3453 issues with windows.
3455 By default, this property has a value of 0.
3457 \sa frameGeometry, y, pos
3459 int QWidget::x() const
3462 if (isWindow() && ! (windowType() == Qt::Popup))
3463 return data->crect.x() - d->frameStrut().left();
3464 return data->crect.x();
3468 \property QWidget::y
3469 \brief the y coordinate of the widget relative to its parent and
3470 including any window frame
3472 See the \l{Window Geometry} documentation for an overview of geometry
3473 issues with windows.
3475 By default, this property has a value of 0.
3477 \sa frameGeometry, x, pos
3479 int QWidget::y() const
3482 if (isWindow() && ! (windowType() == Qt::Popup))
3483 return data->crect.y() - d->frameStrut().top();
3484 return data->crect.y();
3488 \property QWidget::pos
3489 \brief the position of the widget within its parent widget
3491 If the widget is a window, the position is that of the widget on
3492 the desktop, including its frame.
3494 When changing the position, the widget, if visible, receives a
3495 move event (moveEvent()) immediately. If the widget is not
3496 currently visible, it is guaranteed to receive an event before it
3499 By default, this property contains a position that refers to the
3502 \warning Calling move() or setGeometry() inside moveEvent() can
3503 lead to infinite recursion.
3505 See the \l{Window Geometry} documentation for an overview of geometry
3506 issues with windows.
3508 \sa frameGeometry, size x(), y()
3510 QPoint QWidget::pos() const
3513 if (isWindow() && ! (windowType() == Qt::Popup)) {
3514 QRect fs = d->frameStrut();
3515 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3517 return data->crect.topLeft();
3521 \property QWidget::geometry
3522 \brief the geometry of the widget relative to its parent and
3523 excluding the window frame
3525 When changing the geometry, the widget, if visible, receives a
3526 move event (moveEvent()) and/or a resize event (resizeEvent())
3527 immediately. If the widget is not currently visible, it is
3528 guaranteed to receive appropriate events before it is shown.
3530 The size component is adjusted if it lies outside the range
3531 defined by minimumSize() and maximumSize().
3533 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3534 can lead to infinite recursion.
3536 See the \l{Window Geometry} documentation for an overview of geometry
3537 issues with windows.
3539 By default, this property contains a value that depends on the user's
3540 platform and screen geometry.
3542 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3543 resizeEvent(), minimumSize(), maximumSize()
3547 \property QWidget::normalGeometry
3549 \brief the geometry of the widget as it will appear when shown as
3550 a normal (not maximized or full screen) top-level widget
3552 For child widgets this property always holds an empty rectangle.
3554 By default, this property contains an empty rectangle.
3556 \sa QWidget::windowState(), QWidget::geometry
3560 \property QWidget::size
3561 \brief the size of the widget excluding any window frame
3563 If the widget is visible when it is being resized, it receives a resize event
3564 (resizeEvent()) immediately. If the widget is not currently
3565 visible, it is guaranteed to receive an event before it is shown.
3567 The size is adjusted if it lies outside the range defined by
3568 minimumSize() and maximumSize().
3570 By default, this property contains a value that depends on the user's
3571 platform and screen geometry.
3573 \warning Calling resize() or setGeometry() inside resizeEvent() can
3574 lead to infinite recursion.
3576 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3577 appear on screen. This also applies to windows.
3579 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3583 \property QWidget::width
3584 \brief the width of the widget excluding any window frame
3586 See the \l{Window Geometry} documentation for an overview of geometry
3587 issues with windows.
3589 \note Do not use this function to find the width of a screen on
3590 a \l{QDesktopWidget}{multiple screen desktop}. Read
3591 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3593 By default, this property contains a value that depends on the user's
3594 platform and screen geometry.
3596 \sa geometry, height, size
3600 \property QWidget::height
3601 \brief the height of the widget excluding any window frame
3603 See the \l{Window Geometry} documentation for an overview of geometry
3604 issues with windows.
3606 \note Do not use this function to find the height of a screen
3607 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3608 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3610 By default, this property contains a value that depends on the user's
3611 platform and screen geometry.
3613 \sa geometry, width, size
3617 \property QWidget::rect
3618 \brief the internal geometry of the widget excluding any window
3621 The rect property equals QRect(0, 0, width(), height()).
3623 See the \l{Window Geometry} documentation for an overview of geometry
3624 issues with windows.
3626 By default, this property contains a value that depends on the user's
3627 platform and screen geometry.
3633 QRect QWidget::normalGeometry() const
3636 if (!d->extra || !d->extra->topextra)
3639 if (!isMaximized() && !isFullScreen())
3642 return d->topData()->normalGeometry;
3647 \property QWidget::childrenRect
3648 \brief the bounding rectangle of the widget's children
3650 Hidden children are excluded.
3652 By default, for a widget with no children, this property contains a
3653 rectangle with zero width and height located at the origin.
3655 \sa childrenRegion() geometry()
3658 QRect QWidget::childrenRect() const
3661 QRect r(0, 0, 0, 0);
3662 for (int i = 0; i < d->children.size(); ++i) {
3663 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3664 if (w && !w->isWindow() && !w->isHidden())
3671 \property QWidget::childrenRegion
3672 \brief the combined region occupied by the widget's children
3674 Hidden children are excluded.
3676 By default, for a widget with no children, this property contains an
3679 \sa childrenRect() geometry() mask()
3682 QRegion QWidget::childrenRegion() const
3686 for (int i = 0; i < d->children.size(); ++i) {
3687 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3688 if (w && !w->isWindow() && !w->isHidden()) {
3689 QRegion mask = w->mask();
3693 r |= mask.translated(w->pos());
3701 \property QWidget::minimumSize
3702 \brief the widget's minimum size
3704 The widget cannot be resized to a smaller size than the minimum
3705 widget size. The widget's size is forced to the minimum size if
3706 the current size is smaller.
3708 The minimum size set by this function will override the minimum size
3709 defined by QLayout. In order to unset the minimum size, use a
3710 value of \c{QSize(0, 0)}.
3712 By default, this property contains a size with zero width and height.
3714 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3717 QSize QWidget::minimumSize() const
3720 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3724 \property QWidget::maximumSize
3725 \brief the widget's maximum size in pixels
3727 The widget cannot be resized to a larger size than the maximum
3730 By default, this property contains a size in which both width and height
3731 have values of 16777215.
3733 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3736 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3739 QSize QWidget::maximumSize() const
3742 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3743 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3748 \property QWidget::minimumWidth
3749 \brief the widget's minimum width in pixels
3751 This property corresponds to the width held by the \l minimumSize property.
3753 By default, this property has a value of 0.
3755 \sa minimumSize, minimumHeight
3759 \property QWidget::minimumHeight
3760 \brief the widget's minimum height in pixels
3762 This property corresponds to the height held by the \l minimumSize property.
3764 By default, this property has a value of 0.
3766 \sa minimumSize, minimumWidth
3770 \property QWidget::maximumWidth
3771 \brief the widget's maximum width in pixels
3773 This property corresponds to the width held by the \l maximumSize property.
3775 By default, this property contains a value of 16777215.
3777 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3780 \sa maximumSize, maximumHeight
3784 \property QWidget::maximumHeight
3785 \brief the widget's maximum height in pixels
3787 This property corresponds to the height held by the \l maximumSize property.
3789 By default, this property contains a value of 16777215.
3791 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3794 \sa maximumSize, maximumWidth
3798 \property QWidget::sizeIncrement
3799 \brief the size increment of the widget
3801 When the user resizes the window, the size will move in steps of
3802 sizeIncrement().width() pixels horizontally and
3803 sizeIncrement.height() pixels vertically, with baseSize() as the
3804 basis. Preferred widget sizes are for non-negative integers \e i
3806 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3808 Note that while you can set the size increment for all widgets, it
3809 only affects windows.
3811 By default, this property contains a size with zero width and height.
3813 \warning The size increment has no effect under Windows, and may
3814 be disregarded by the window manager on X11.
3816 \sa size, minimumSize, maximumSize
3818 QSize QWidget::sizeIncrement() const
3821 return (d->extra && d->extra->topextra)
3822 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3827 \property QWidget::baseSize
3828 \brief the base size of the widget
3830 The base size is used to calculate a proper widget size if the
3831 widget defines sizeIncrement().
3833 By default, for a newly-created widget, this property contains a size with
3834 zero width and height.
3836 \sa setSizeIncrement()
3839 QSize QWidget::baseSize() const
3842 return (d->extra != 0 && d->extra->topextra != 0)
3843 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3847 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3851 int mw = minw, mh = minh;
3852 if (mw == QWIDGETSIZE_MAX)
3854 if (mh == QWIDGETSIZE_MAX)
3856 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3857 qWarning("QWidget::setMinimumSize: (%s/%s) "
3858 "The largest allowed size is (%d,%d)",
3859 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3861 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3862 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3864 if (minw < 0 || minh < 0) {
3865 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3867 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3868 minw = mw = qMax(minw, 0);
3869 minh = mh = qMax(minh, 0);
3872 if (extra->minw == mw && extra->minh == mh)
3876 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3883 This function corresponds to setMinimumSize(QSize(minw, minh)).
3884 Sets the minimum width to \a minw and the minimum height to \a
3888 void QWidget::setMinimumSize(int minw, int minh)
3891 if (!d->setMinimumSize_helper(minw, minh))
3895 d->setConstraints_sys();
3896 if (minw > width() || minh > height()) {
3897 bool resized = testAttribute(Qt::WA_Resized);
3898 bool maximized = isMaximized();
3899 resize(qMax(minw,width()), qMax(minh,height()));
3900 setAttribute(Qt::WA_Resized, resized); //not a user resize
3902 data->window_state = data->window_state | Qt::WindowMaximized;
3904 #ifndef QT_NO_GRAPHICSVIEW
3906 if (d->extra->proxyWidget)
3907 d->extra->proxyWidget->setMinimumSize(minw, minh);
3910 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3913 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3916 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3917 qWarning("QWidget::setMaximumSize: (%s/%s) "
3918 "The largest allowed size is (%d,%d)",
3919 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3921 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3922 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3924 if (maxw < 0 || maxh < 0) {
3925 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3927 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3928 maxw = qMax(maxw, 0);
3929 maxh = qMax(maxh, 0);
3932 if (extra->maxw == maxw && extra->maxh == maxh)
3936 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3937 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3944 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3945 maxh)). Sets the maximum width to \a maxw and the maximum height
3948 void QWidget::setMaximumSize(int maxw, int maxh)
3951 if (!d->setMaximumSize_helper(maxw, maxh))
3955 d->setConstraints_sys();
3956 if (maxw < width() || maxh < height()) {
3957 bool resized = testAttribute(Qt::WA_Resized);
3958 resize(qMin(maxw,width()), qMin(maxh,height()));
3959 setAttribute(Qt::WA_Resized, resized); //not a user resize
3962 #ifndef QT_NO_GRAPHICSVIEW
3964 if (d->extra->proxyWidget)
3965 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3969 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3975 Sets the x (width) size increment to \a w and the y (height) size
3978 void QWidget::setSizeIncrement(int w, int h)
3982 QTLWExtra* x = d->topData();
3983 if (x->incw == w && x->inch == h)
3988 d->setConstraints_sys();
3994 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3995 the widgets base size to width \a basew and height \a baseh.
3997 void QWidget::setBaseSize(int basew, int baseh)
4001 QTLWExtra* x = d->topData();
4002 if (x->basew == basew && x->baseh == baseh)
4007 d->setConstraints_sys();
4011 Sets both the minimum and maximum sizes of the widget to \a s,
4012 thereby preventing it from ever growing or shrinking.
4014 This will override the default size constraints set by QLayout.
4016 To remove constraints, set the size to QWIDGETSIZE_MAX.
4018 Alternatively, if you want the widget to have a
4019 fixed size based on its contents, you can call
4020 QLayout::setSizeConstraint(QLayout::SetFixedSize);
4022 \sa maximumSize, minimumSize
4025 void QWidget::setFixedSize(const QSize & s)
4027 setFixedSize(s.width(), s.height());
4032 \fn void QWidget::setFixedSize(int w, int h)
4035 Sets the width of the widget to \a w and the height to \a h.
4038 void QWidget::setFixedSize(int w, int h)
4041 bool minSizeSet = d->setMinimumSize_helper(w, h);
4042 bool maxSizeSet = d->setMaximumSize_helper(w, h);
4043 if (!minSizeSet && !maxSizeSet)
4047 d->setConstraints_sys();
4049 d->updateGeometry_helper(true);
4051 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
4055 void QWidget::setMinimumWidth(int w)
4059 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
4060 setMinimumSize(w, minimumSize().height());
4061 d->extra->explicitMinSize = expl;
4064 void QWidget::setMinimumHeight(int h)
4068 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
4069 setMinimumSize(minimumSize().width(), h);
4070 d->extra->explicitMinSize = expl;
4073 void QWidget::setMaximumWidth(int w)
4077 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
4078 setMaximumSize(w, maximumSize().height());
4079 d->extra->explicitMaxSize = expl;
4082 void QWidget::setMaximumHeight(int h)
4086 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
4087 setMaximumSize(maximumSize().width(), h);
4088 d->extra->explicitMaxSize = expl;
4092 Sets both the minimum and maximum width of the widget to \a w
4093 without changing the heights. Provided for convenience.
4095 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
4098 void QWidget::setFixedWidth(int w)
4102 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
4103 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
4104 setMinimumSize(w, minimumSize().height());
4105 setMaximumSize(w, maximumSize().height());
4106 d->extra->explicitMinSize = explMin;
4107 d->extra->explicitMaxSize = explMax;
4112 Sets both the minimum and maximum heights of the widget to \a h
4113 without changing the widths. Provided for convenience.
4115 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
4118 void QWidget::setFixedHeight(int h)
4122 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
4123 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
4124 setMinimumSize(minimumSize().width(), h);
4125 setMaximumSize(maximumSize().width(), h);
4126 d->extra->explicitMinSize = explMin;
4127 d->extra->explicitMaxSize = explMax;
4132 Translates the widget coordinate \a pos to the coordinate system
4133 of \a parent. The \a parent must not be 0 and must be a parent
4134 of the calling widget.
4136 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
4139 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
4143 const QWidget * w = this;
4144 while (w != parent) {
4145 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
4146 "parent must be in parent hierarchy");
4147 p = w->mapToParent(p);
4148 w = w->parentWidget();
4156 Translates the widget coordinate \a pos from the coordinate system
4157 of \a parent to this widget's coordinate system. The \a parent
4158 must not be 0 and must be a parent of the calling widget.
4160 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
4163 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
4167 const QWidget * w = this;
4168 while (w != parent) {
4169 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
4170 "parent must be in parent hierarchy");
4172 p = w->mapFromParent(p);
4173 w = w->parentWidget();
4181 Translates the widget coordinate \a pos to a coordinate in the
4184 Same as mapToGlobal() if the widget has no parent.
4186 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
4189 QPoint QWidget::mapToParent(const QPoint &pos) const
4191 return pos + data->crect.topLeft();
4195 Translates the parent widget coordinate \a pos to widget
4198 Same as mapFromGlobal() if the widget has no parent.
4200 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
4203 QPoint QWidget::mapFromParent(const QPoint &pos) const
4205 return pos - data->crect.topLeft();
4210 Returns the window for this widget, i.e. the next ancestor widget
4211 that has (or could have) a window-system frame.
4213 If the widget is a window, the widget itself is returned.
4215 Typical usage is changing the window title:
4217 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
4222 QWidget *QWidget::window() const
4224 QWidget *w = (QWidget *)this;
4225 QWidget *p = w->parentWidget();
4226 while (!w->isWindow() && p) {
4228 p = p->parentWidget();
4236 Returns the native parent for this widget, i.e. the next ancestor widget
4237 that has a system identifier, or 0 if it does not have any native parent.
4239 \sa effectiveWinId()
4241 QWidget *QWidget::nativeParentWidget() const
4243 QWidget *parent = parentWidget();
4244 while (parent && !parent->internalWinId())
4245 parent = parent->parentWidget();
4249 /*! \fn QWidget *QWidget::topLevelWidget() const
4252 Use window() instead.
4257 Returns the color role used for painting the widget's background.
4259 Use QPalette(backgroundRole(()) instead.
4261 Qt::BackgroundMode QWidget::backgroundMode() const
4263 if (testAttribute(Qt::WA_NoSystemBackground))
4264 return Qt::NoBackground;
4265 switch(backgroundRole()) {
4266 case QPalette::WindowText:
4267 return Qt::PaletteForeground;
4268 case QPalette::Button:
4269 return Qt::PaletteButton;
4270 case QPalette::Light:
4271 return Qt::PaletteLight;
4272 case QPalette::Midlight:
4273 return Qt::PaletteMidlight;
4274 case QPalette::Dark:
4275 return Qt::PaletteDark;
4277 return Qt::PaletteMid;
4278 case QPalette::Text:
4279 return Qt::PaletteText;
4280 case QPalette::BrightText:
4281 return Qt::PaletteBrightText;
4282 case QPalette::Base:
4283 return Qt::PaletteBase;
4284 case QPalette::Window:
4285 return Qt::PaletteBackground;
4286 case QPalette::Shadow:
4287 return Qt::PaletteShadow;
4288 case QPalette::Highlight:
4289 return Qt::PaletteHighlight;
4290 case QPalette::HighlightedText:
4291 return Qt::PaletteHighlightedText;
4292 case QPalette::ButtonText:
4293 return Qt::PaletteButtonText;
4294 case QPalette::Link:
4295 return Qt::PaletteLink;
4296 case QPalette::LinkVisited:
4297 return Qt::PaletteLinkVisited;
4301 return Qt::NoBackground;
4305 \fn void QWidget::setBackgroundMode(Qt::BackgroundMode
4306 widgetBackground, Qt::BackgroundMode paletteBackground)
4308 Sets the color role used for painting the widget's background to
4309 background mode \a widgetBackground. The \a paletteBackground mode
4310 parameter is ignored.
4312 void QWidget::setBackgroundMode(Qt::BackgroundMode m, Qt::BackgroundMode)
4315 if(m == Qt::NoBackground) {
4316 setAttribute(Qt::WA_NoSystemBackground, true);
4319 setAttribute(Qt::WA_NoSystemBackground, false);
4320 d->fg_role = QPalette::NoRole;
4321 QPalette::ColorRole role = d->bg_role;
4323 case Qt::FixedColor:
4324 case Qt::FixedPixmap:
4326 case Qt::PaletteForeground:
4327 role = QPalette::WindowText;
4329 case Qt::PaletteButton:
4330 role = QPalette::Button;
4332 case Qt::PaletteLight:
4333 role = QPalette::Light;
4335 case Qt::PaletteMidlight:
4336 role = QPalette::Midlight;
4338 case Qt::PaletteDark:
4339 role = QPalette::Dark;
4341 case Qt::PaletteMid:
4342 role = QPalette::Mid;
4344 case Qt::PaletteText:
4345 role = QPalette::Text;
4347 case Qt::PaletteBrightText:
4348 role = QPalette::BrightText;
4350 case Qt::PaletteBase:
4351 role = QPalette::Base;
4353 case Qt::PaletteBackground:
4354 role = QPalette::Window;
4356 case Qt::PaletteShadow:
4357 role = QPalette::Shadow;
4359 case Qt::PaletteHighlight:
4360 role = QPalette::Highlight;
4362 case Qt::PaletteHighlightedText:
4363 role = QPalette::HighlightedText;
4365 case Qt::PaletteButtonText:
4366 role = QPalette::ButtonText;
4368 case Qt::PaletteLink:
4369 role = QPalette::Link;
4371 case Qt::PaletteLinkVisited:
4372 role = QPalette::LinkVisited;
4374 case Qt::X11ParentRelative:
4375 d->fg_role = role = QPalette::NoRole;
4379 setBackgroundRole(role);
4383 The widget mapper is no longer part of the public API.
4385 QT3_SUPPORT QWidgetMapper *QWidget::wmapper() { return QWidgetPrivate::mapper; }
4391 Returns the background role of the widget.
4393 The background role defines the brush from the widget's \l palette that
4394 is used to render the background.
4396 If no explicit background role is set, the widget inherts its parent
4397 widget's background role.
4399 \sa setBackgroundRole(), foregroundRole()
4401 QPalette::ColorRole QWidget::backgroundRole() const
4404 const QWidget *w = this;
4406 QPalette::ColorRole role = w->d_func()->bg_role;
4407 if (role != QPalette::NoRole)
4409 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4411 w = w->parentWidget();
4413 return QPalette::Window;
4417 Sets the background role of the widget to \a role.
4419 The background role defines the brush from the widget's \l palette that
4420 is used to render the background.
4422 If \a role is QPalette::NoRole, then the widget inherits its
4423 parent's background role.
4425 Note that styles are free to choose any color from the palette.
4426 You can modify the palette or set a style sheet if you don't
4427 achieve the result you want with setBackgroundRole().
4429 \sa backgroundRole(), foregroundRole()
4432 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4436 d->updateSystemBackground();
4437 d->propagatePaletteChange();
4438 d->updateIsOpaque();
4442 Returns the foreground role.
4444 The foreground role defines the color from the widget's \l palette that
4445 is used to draw the foreground.
4447 If no explicit foreground role is set, the function returns a role
4448 that contrasts with the background role.
4450 \sa setForegroundRole(), backgroundRole()
4452 QPalette::ColorRole QWidget::foregroundRole() const
4455 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4456 if (rl != QPalette::NoRole)
4458 QPalette::ColorRole role = QPalette::WindowText;
4459 switch (backgroundRole()) {
4460 case QPalette::Button:
4461 role = QPalette::ButtonText;
4463 case QPalette::Base:
4464 role = QPalette::Text;
4466 case QPalette::Dark:
4467 case QPalette::Shadow:
4468 role = QPalette::Light;
4470 case QPalette::Highlight:
4471 role = QPalette::HighlightedText;
4473 case QPalette::ToolTipBase:
4474 role = QPalette::ToolTipText;
4483 Sets the foreground role of the widget to \a role.
4485 The foreground role defines the color from the widget's \l palette that
4486 is used to draw the foreground.
4488 If \a role is QPalette::NoRole, the widget uses a foreground role
4489 that contrasts with the background role.
4491 Note that styles are free to choose any color from the palette.
4492 You can modify the palette or set a style sheet if you don't
4493 achieve the result you want with setForegroundRole().
4495 \sa foregroundRole(), backgroundRole()
4497 void QWidget::setForegroundRole(QPalette::ColorRole role)
4501 d->updateSystemBackground();
4502 d->propagatePaletteChange();
4506 \property QWidget::palette
4507 \brief the widget's palette
4509 This property describes the widget's palette. The palette is used by the
4510 widget's style when rendering standard components, and is available as a
4511 means to ensure that custom widgets can maintain consistency with the
4512 native platform's look and feel. It's common that different platforms, or
4513 different styles, have different palettes.
4515 When you assign a new palette to a widget, the color roles from this
4516 palette are combined with the widget's default palette to form the
4517 widget's final palette. The palette entry for the widget's background role
4518 is used to fill the widget's background (see QWidget::autoFillBackground),
4519 and the foreground role initializes QPainter's pen.
4521 The default depends on the system environment. QApplication maintains a
4522 system/theme palette which serves as a default for all widgets. There may
4523 also be special palette defaults for certain types of widgets (e.g., on
4524 Windows XP and Vista, all classes that derive from QMenuBar have a special
4525 default palette). You can also define default palettes for widgets
4526 yourself by passing a custom palette and the name of a widget to
4527 QApplication::setPalette(). Finally, the style always has the option of
4528 polishing the palette as it's assigned (see QStyle::polish()).
4530 QWidget propagates explicit palette roles from parent to child. If you
4531 assign a brush or color to a specific role on a palette and assign that
4532 palette to a widget, that role will propagate to all the widget's
4533 children, overriding any system defaults for that role. Note that palettes
4534 by default don't propagate to windows (see isWindow()) unless the
4535 Qt::WA_WindowPropagation attribute is enabled.
4537 QWidget's palette propagation is similar to its font propagation.
4539 The current style, which is used to render the content of all standard Qt
4540 widgets, is free to choose colors and brushes from the widget palette, or
4541 in some cases, to ignore the palette (partially, or completely). In
4542 particular, certain styles like GTK style, Mac style, Windows XP, and
4543 Vista style, depend on third party APIs to render the content of widgets,
4544 and these styles typically do not follow the palette. Because of this,
4545 assigning roles to a widget's palette is not guaranteed to change the
4546 appearance of the widget. Instead, you may choose to apply a \l
4547 styleSheet. You can refer to our Knowledge Base article
4548 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4551 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4552 When using style sheets, the palette of a widget can be customized using
4553 the "color", "background-color", "selection-color",
4554 "selection-background-color" and "alternate-background-color".
4556 \sa QApplication::palette(), QWidget::font()
4558 const QPalette &QWidget::palette() const
4561 data->pal.setCurrentColorGroup(QPalette::Disabled);
4562 } else if ((!isVisible() || isActiveWindow())
4563 #if defined(Q_OS_WIN) && !defined(Q_WS_WINCE)
4564 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4567 data->pal.setCurrentColorGroup(QPalette::Active);
4570 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4571 if (qt_mac_can_clickThrough(this))
4572 data->pal.setCurrentColorGroup(QPalette::Active);
4575 data->pal.setCurrentColorGroup(QPalette::Inactive);
4580 void QWidget::setPalette(const QPalette &palette)
4583 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4585 // Determine which palette is inherited from this widget's ancestors and
4586 // QApplication::palette, resolve this against \a palette (attributes from
4587 // the inherited palette are copied over this widget's palette). Then
4588 // propagate this palette to this widget's children.
4589 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4590 QPalette resolvedPalette = palette.resolve(naturalPalette);
4591 d->setPalette_helper(resolvedPalette);
4597 Returns the palette that the widget \a w inherits from its ancestors and
4598 QApplication::palette. \a inheritedMask is the combination of the widget's
4599 ancestors palette request masks (i.e., which attributes from the parent
4600 widget's palette are implicitly imposed on this widget by the user). Note
4601 that this font does not take into account the palette set on \a w itself.
4603 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4606 QPalette naturalPalette = QApplication::palette(q);
4607 if (!q->testAttribute(Qt::WA_StyleSheet)
4608 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4609 #ifndef QT_NO_GRAPHICSVIEW
4610 || (extra && extra->proxyWidget)
4611 #endif //QT_NO_GRAPHICSVIEW
4613 if (QWidget *p = q->parentWidget()) {
4614 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4615 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4616 QPalette inheritedPalette = p->palette();
4617 inheritedPalette.resolve(inheritedMask);
4618 naturalPalette = inheritedPalette.resolve(naturalPalette);
4620 naturalPalette = p->palette();
4624 #ifndef QT_NO_GRAPHICSVIEW
4625 else if (extra && extra->proxyWidget) {
4626 QPalette inheritedPalette = extra->proxyWidget->palette();
4627 inheritedPalette.resolve(inheritedMask);
4628 naturalPalette = inheritedPalette.resolve(naturalPalette);
4630 #endif //QT_NO_GRAPHICSVIEW
4632 naturalPalette.resolve(0);
4633 return naturalPalette;
4638 Determine which palette is inherited from this widget's ancestors and
4639 QApplication::palette, resolve this against this widget's palette
4640 (attributes from the inherited palette are copied over this widget's
4641 palette). Then propagate this palette to this widget's children.
4643 void QWidgetPrivate::resolvePalette()
4645 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4646 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4647 setPalette_helper(resolvedPalette);
4650 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4653 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4656 updateSystemBackground();
4657 propagatePaletteChange();
4664 \property QWidget::font
4665 \brief the font currently set for the widget
4667 This property describes the widget's requested font. The font is used by
4668 the widget's style when rendering standard components, and is available as
4669 a means to ensure that custom widgets can maintain consistency with the
4670 native platform's look and feel. It's common that different platforms, or
4671 different styles, define different fonts for an application.
4673 When you assign a new font to a widget, the properties from this font are
4674 combined with the widget's default font to form the widget's final
4675 font. You can call fontInfo() to get a copy of the widget's final
4676 font. The final font is also used to initialize QPainter's font.
4678 The default depends on the system environment. QApplication maintains a
4679 system/theme font which serves as a default for all widgets. There may
4680 also be special font defaults for certain types of widgets. You can also
4681 define default fonts for widgets yourself by passing a custom font and the
4682 name of a widget to QApplication::setFont(). Finally, the font is matched
4683 against Qt's font database to find the best match.
4685 QWidget propagates explicit font properties from parent to child. If you
4686 change a specific property on a font and assign that font to a widget,
4687 that property will propagate to all the widget's children, overriding any
4688 system defaults for that property. Note that fonts by default don't
4689 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4690 attribute is enabled.
4692 QWidget's font propagation is similar to its palette propagation.
4694 The current style, which is used to render the content of all standard Qt
4695 widgets, is free to choose to use the widget font, or in some cases, to
4696 ignore it (partially, or completely). In particular, certain styles like
4697 GTK style, Mac style, Windows XP, and Vista style, apply special
4698 modifications to the widget font to match the platform's native look and
4699 feel. Because of this, assigning properties to a widget's font is not
4700 guaranteed to change the appearance of the widget. Instead, you may choose
4701 to apply a \l styleSheet.
4703 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4704 style sheets will take precedence if the settings conflict.
4706 \sa fontInfo(), fontMetrics()
4709 void QWidget::setFont(const QFont &font)
4713 #ifndef QT_NO_STYLE_STYLESHEET
4714 const QStyleSheetStyle* style;
4715 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4716 style->saveWidgetFont(this, font);
4720 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4722 // Determine which font is inherited from this widget's ancestors and
4723 // QApplication::font, resolve this against \a font (attributes from the
4724 // inherited font are copied over). Then propagate this font to this
4725 // widget's children.
4726 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4727 QFont resolvedFont = font.resolve(naturalFont);
4728 d->setFont_helper(resolvedFont);
4734 Returns the font that the widget \a w inherits from its ancestors and
4735 QApplication::font. \a inheritedMask is the combination of the widget's
4736 ancestors font request masks (i.e., which attributes from the parent
4737 widget's font are implicitly imposed on this widget by the user). Note
4738 that this font does not take into account the font set on \a w itself.
4740 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4741 is applied, fonts are not propagated anymore
4743 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4746 QFont naturalFont = QApplication::font(q);
4747 if (!q->testAttribute(Qt::WA_StyleSheet)
4748 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4749 #ifndef QT_NO_GRAPHICSVIEW
4750 || (extra && extra->proxyWidget)
4751 #endif //QT_NO_GRAPHICSVIEW
4753 if (QWidget *p = q->parentWidget()) {
4754 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4755 if (!naturalFont.isCopyOf(QApplication::font())) {
4756 QFont inheritedFont = p->font();
4757 inheritedFont.resolve(inheritedMask);
4758 naturalFont = inheritedFont.resolve(naturalFont);
4760 naturalFont = p->font();
4764 #ifndef QT_NO_GRAPHICSVIEW
4765 else if (extra && extra->proxyWidget) {
4766 QFont inheritedFont = extra->proxyWidget->font();
4767 inheritedFont.resolve(inheritedMask);
4768 naturalFont = inheritedFont.resolve(naturalFont);
4770 #endif //QT_NO_GRAPHICSVIEW
4772 naturalFont.resolve(0);
4779 Determine which font is implicitly imposed on this widget by its ancestors
4780 and QApplication::font, resolve this against its own font (attributes from
4781 the implicit font are copied over). Then propagate this font to this
4784 void QWidgetPrivate::resolveFont()
4786 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4787 QFont resolvedFont = data.fnt.resolve(naturalFont);
4788 setFont_helper(resolvedFont);
4794 Assign \a font to this widget, and propagate it to all children, except
4795 style sheet widgets (handled differently) and windows that don't enable
4796 window propagation. \a implicitMask is the union of all ancestor widgets'
4797 font request masks, and determines which attributes from this widget's
4798 font should propagate.
4800 void QWidgetPrivate::updateFont(const QFont &font)
4803 #ifndef QT_NO_STYLE_STYLESHEET
4804 const QStyleSheetStyle* cssStyle;
4805 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4809 QFont old = data.fnt;
4811 data.fnt = QFont(font, q);
4812 #if defined(Q_WS_X11)
4813 // make sure the font set on this widget is associated with the correct screen
4814 data.fnt.x11SetScreen(xinfo.screen());
4816 // Combine new mask with natural mask and propagate to children.
4817 #ifndef QT_NO_GRAPHICSVIEW
4818 if (!q->parentWidget() && extra && extra->proxyWidget) {
4819 QGraphicsProxyWidget *p = extra->proxyWidget;
4820 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4822 #endif //QT_NO_GRAPHICSVIEW
4823 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4824 inheritedFontResolveMask = 0;
4826 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4828 for (int i = 0; i < children.size(); ++i) {
4829 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4832 #ifndef QT_NO_STYLE_STYLESHEET
4833 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4834 // Style sheets follow a different font propagation scheme.
4836 cssStyle->updateStyleSheetFont(w);
4838 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4839 // Propagate font changes.
4840 QWidgetPrivate *wd = w->d_func();
4841 wd->inheritedFontResolveMask = newMask;
4847 #ifndef QT_NO_STYLE_STYLESHEET
4849 cssStyle->updateStyleSheetFont(q);
4853 QEvent e(QEvent::FontChange);
4854 QApplication::sendEvent(q, &e);
4860 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4864 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4866 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4867 if (!children.isEmpty()) {
4868 for (int i = 0; i < children.size(); ++i) {
4869 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4870 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4871 w->d_func()->setLayoutDirection_helper(direction);
4874 QEvent e(QEvent::LayoutDirectionChange);
4875 QApplication::sendEvent(q, &e);
4878 void QWidgetPrivate::resolveLayoutDirection()
4881 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4882 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4886 \property QWidget::layoutDirection
4888 \brief the layout direction for this widget
4890 By default, this property is set to Qt::LeftToRight.
4892 When the layout direction is set on a widget, it will propagate to
4893 the widget's children, but not to a child that is a window and not
4894 to a child for which setLayoutDirection() has been explicitly
4895 called. Also, child widgets added \e after setLayoutDirection()
4896 has been called for the parent do not inherit the parent's layout
4899 This method no longer affects text layout direction since Qt 4.7.
4901 \sa QApplication::layoutDirection
4903 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4907 if (direction == Qt::LayoutDirectionAuto) {
4908 unsetLayoutDirection();
4912 setAttribute(Qt::WA_SetLayoutDirection);
4913 d->setLayoutDirection_helper(direction);
4916 Qt::LayoutDirection QWidget::layoutDirection() const
4918 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4921 void QWidget::unsetLayoutDirection()
4924 setAttribute(Qt::WA_SetLayoutDirection, false);
4925 d->resolveLayoutDirection();
4929 \fn QFontMetrics QWidget::fontMetrics() const
4931 Returns the font metrics for the widget's current font.
4932 Equivalent to QFontMetrics(widget->font()).
4934 \sa font(), fontInfo(), setFont()
4938 \fn QFontInfo QWidget::fontInfo() const
4940 Returns the font info for the widget's current font.
4941 Equivalent to QFontInto(widget->font()).
4943 \sa font(), fontMetrics(), setFont()
4948 \property QWidget::cursor
4949 \brief the cursor shape for this widget
4951 The mouse cursor will assume this shape when it's over this
4952 widget. See the \link Qt::CursorShape list of predefined cursor
4953 objects\endlink for a range of useful shapes.
4955 An editor widget might use an I-beam cursor:
4956 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4958 If no cursor has been set, or after a call to unsetCursor(), the
4959 parent's cursor is used.
4961 By default, this property contains a cursor with the Qt::ArrowCursor
4964 Some underlying window implementations will reset the cursor if it
4965 leaves a widget even if the mouse is grabbed. If you want to have
4966 a cursor set for all widgets, even when outside the window, consider
4967 QApplication::setOverrideCursor().
4969 \sa QApplication::setOverrideCursor()
4972 #ifndef QT_NO_CURSOR
4973 QCursor QWidget::cursor() const
4976 if (testAttribute(Qt::WA_SetCursor))
4977 return (d->extra && d->extra->curs)
4979 : QCursor(Qt::ArrowCursor);
4980 if (isWindow() || !parentWidget())
4981 return QCursor(Qt::ArrowCursor);
4982 return parentWidget()->cursor();
4985 void QWidget::setCursor(const QCursor &cursor)
4988 // On Mac we must set the cursor even if it is the ArrowCursor.
4989 #if !defined(Q_WS_MAC)
4990 if (cursor.shape() != Qt::ArrowCursor
4991 || (d->extra && d->extra->curs))
4995 QCursor *newCursor = new QCursor(cursor);
4996 delete d->extra->curs;
4997 d->extra->curs = newCursor;
4999 setAttribute(Qt::WA_SetCursor);
5000 d->setCursor_sys(cursor);
5002 QEvent event(QEvent::CursorChange);
5003 QApplication::sendEvent(this, &event);
5006 void QWidget::unsetCursor()
5010 delete d->extra->curs;
5014 setAttribute(Qt::WA_SetCursor, false);
5015 d->unsetCursor_sys();
5017 QEvent event(QEvent::CursorChange);
5018 QApplication::sendEvent(this, &event);
5024 \enum QWidget::RenderFlag
5026 This enum describes how to render the widget when calling QWidget::render().
5028 \value DrawWindowBackground If you enable this option, the widget's background
5029 is rendered into the target even if autoFillBackground is not set. By default,
5030 this option is enabled.
5032 \value DrawChildren If you enable this option, the widget's children
5033 are rendered recursively into the target. By default, this option is enabled.
5035 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
5036 is ignored when rendering into the target. By default, this option is disabled.
5044 Renders the \a sourceRegion of this widget into the \a target
5045 using \a renderFlags to determine how to render. Rendering
5046 starts at \a targetOffset in the \a target. For example:
5048 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
5050 If \a sourceRegion is a null region, this function will use QWidget::rect() as
5051 the region, i.e. the entire widget.
5053 Ensure that you call QPainter::end() for the \a target device's
5054 active painter (if any) before rendering. For example:
5056 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
5058 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
5059 or QGLWidget::renderPixmap() instead.
5061 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
5062 const QRegion &sourceRegion, RenderFlags renderFlags)
5064 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
5070 Renders the widget into the \a painter's QPainter::device().
5072 Transformations and settings applied to the \a painter will be used
5075 \note The \a painter must be active. On Mac OS X the widget will be
5076 rendered into a QPixmap and then drawn by the \a painter.
5078 \sa QPainter::device()
5080 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
5081 const QRegion &sourceRegion, RenderFlags renderFlags)
5084 qWarning("QWidget::render: Null pointer to painter");
5088 if (!painter->isActive()) {
5089 qWarning("QWidget::render: Cannot render with an inactive painter");
5093 const qreal opacity = painter->opacity();
5094 if (qFuzzyIsNull(opacity))
5095 return; // Fully transparent.
5098 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
5099 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
5101 if (toBePainted.isEmpty())
5106 d->extra->inRenderWithPainter = true;
5109 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
5111 QPaintEngine *engine = painter->paintEngine();
5113 QPaintEnginePrivate *enginePriv = engine->d_func();
5114 Q_ASSERT(enginePriv);
5115 QPaintDevice *target = engine->paintDevice();
5118 // Render via a pixmap when dealing with non-opaque painters or printers.
5119 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
5120 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
5121 d->extra->inRenderWithPainter = false;
5125 // Set new shared painter.
5126 QPainter *oldPainter = d->sharedPainter();
5127 d->setSharedPainter(painter);
5129 // Save current system clip, viewport and transform,
5130 const QTransform oldTransform = enginePriv->systemTransform;
5131 const QRegion oldSystemClip = enginePriv->systemClip;
5132 const QRegion oldSystemViewport = enginePriv->systemViewport;
5134 // This ensures that all painting triggered by render() is clipped to the current engine clip.
5135 if (painter->hasClipping()) {
5136 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
5137 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
5139 enginePriv->setSystemViewport(oldSystemClip);
5142 render(target, targetOffset, toBePainted, renderFlags);
5144 // Restore system clip, viewport and transform.
5145 enginePriv->systemClip = oldSystemClip;
5146 enginePriv->setSystemViewport(oldSystemViewport);
5147 enginePriv->setSystemTransform(oldTransform);
5149 // Restore shared painter.
5150 d->setSharedPainter(oldPainter);
5153 d->extra->inRenderWithPainter = false;
5156 static void sendResizeEvents(QWidget *target)
5158 QResizeEvent e(target->size(), QSize());
5159 QApplication::sendEvent(target, &e);
5161 const QObjectList children = target->children();
5162 for (int i = 0; i < children.size(); ++i) {
5163 QWidget *child = static_cast<QWidget*>(children.at(i));
5164 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
5165 sendResizeEvents(child);
5172 Renders the widget into a pixmap restricted by the
5173 given \a rectangle. If the \a widget has any children, then
5174 they are also painted in the appropriate positions.
5176 If no rectangle is specified (the default) the entire widget is
5179 Replacement for Qt 4's QPixmap::grabWidget().
5181 \sa render(), QPixmap
5184 /* INVOKABLE since used by QPixmap::grabWidget(). */
5185 QPixmap QWidget::grab(const QRect &rectangle)
5188 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
5189 sendResizeEvents(this);
5195 r.setWidth(width() - rectangle.x());
5197 r.setHeight(height() - rectangle.y());
5199 if (!r.intersects(rect()))
5202 QPixmap res(r.size());
5204 res.fill(Qt::transparent);
5205 render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
5206 | QWidget::DrawChildren | QWidget::IgnoreMask);
5211 \brief The graphicsEffect function returns a pointer to the
5212 widget's graphics effect.
5214 If the widget has no graphics effect, 0 is returned.
5218 \sa setGraphicsEffect()
5220 #ifndef QT_NO_GRAPHICSEFFECT
5221 QGraphicsEffect *QWidget::graphicsEffect() const
5224 return d->graphicsEffect;
5226 #endif //QT_NO_GRAPHICSEFFECT
5230 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
5232 Sets \a effect as the widget's effect. If there already is an effect installed
5233 on this widget, QWidget will delete the existing effect before installing
5236 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
5237 the effect from the widget and install it on this widget.
5239 QWidget takes ownership of \a effect.
5241 \note This function will apply the effect on itself and all its children.
5245 \sa graphicsEffect()
5247 #ifndef QT_NO_GRAPHICSEFFECT
5248 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
5251 if (d->graphicsEffect == effect)
5254 if (d->graphicsEffect) {
5255 d->invalidateBuffer(rect());
5256 delete d->graphicsEffect;
5257 d->graphicsEffect = 0;
5262 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
5263 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
5264 d->graphicsEffect = effect;
5265 effect->d_func()->setGraphicsEffectSource(source);
5269 d->updateIsOpaque();
5271 #endif //QT_NO_GRAPHICSEFFECT
5273 bool QWidgetPrivate::isAboutToShow() const
5282 // The widget will be shown if any of its ancestors are about to show.
5283 QWidget *parent = q->parentWidget();
5284 return parent ? parent->d_func()->isAboutToShow() : false;
5287 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
5290 const bool isVisible = q->isVisible();
5292 // Make sure the widget is laid out correctly.
5293 if (!isVisible && !isAboutToShow()) {
5294 QWidget *topLevel = q->window();
5295 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
5296 topLevel->ensurePolished();
5298 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
5299 // they're not explicitly hidden.
5300 QWidget *widget = q;
5301 QWidgetList hiddenWidgets;
5303 if (widget->isHidden()) {
5304 widget->setAttribute(Qt::WA_WState_Hidden, false);
5305 hiddenWidgets.append(widget);
5306 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
5307 widget->d_func()->updateGeometry_helper(true);
5309 widget = widget->parentWidget();
5312 // Activate top-level layout.
5313 if (topLevel->d_func()->layout)
5314 topLevel->d_func()->layout->activate();
5316 // Adjust size if necessary.
5317 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
5318 if (topLevelExtra && !topLevelExtra->sizeAdjusted
5319 && !topLevel->testAttribute(Qt::WA_Resized)) {
5320 topLevel->adjustSize();
5321 topLevel->setAttribute(Qt::WA_Resized, false);
5324 // Activate child layouts.
5325 topLevel->d_func()->activateChildLayoutsRecursively();
5327 // We're not cheating with WA_WState_Hidden anymore.
5328 for (int i = 0; i < hiddenWidgets.size(); ++i) {
5329 QWidget *widget = hiddenWidgets.at(i);
5330 widget->setAttribute(Qt::WA_WState_Hidden);
5331 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
5332 widget->parentWidget()->d_func()->layout->invalidate();
5334 } else if (isVisible) {
5335 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
5338 // Calculate the region to be painted.
5339 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
5340 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
5341 toBePainted &= extra->mask;
5345 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
5346 QWidget::RenderFlags renderFlags)
5349 Q_ASSERT(!toBePainted.isEmpty());
5353 const QTransform originalTransform = painter->worldTransform();
5354 const bool useDeviceCoordinates = originalTransform.isScaling();
5355 if (!useDeviceCoordinates) {
5357 // Render via a pixmap.
5358 const QRect rect = toBePainted.boundingRect();
5359 const QSize size = rect.size();
5363 QPixmap pixmap(size);
5364 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
5365 pixmap.fill(Qt::transparent);
5366 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
5368 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
5369 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
5371 painter->drawPixmap(targetOffset, pixmap);
5374 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
5378 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
5379 QTransform transform = originalTransform;
5380 transform.translate(targetOffset.x(), targetOffset.y());
5382 QPaintDevice *device = painter->device();
5385 // Calculate device rect.
5386 const QRectF rect(toBePainted.boundingRect());
5387 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
5388 deviceRect &= QRect(0, 0, device->width(), device->height());
5390 QPixmap pixmap(deviceRect.size());
5391 pixmap.fill(Qt::transparent);
5393 // Create a pixmap device coordinate painter.
5394 QPainter pixmapPainter(&pixmap);
5395 pixmapPainter.setRenderHints(painter->renderHints());
5396 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
5397 pixmapPainter.setTransform(transform);
5399 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
5400 pixmapPainter.end();
5402 // And then draw the pixmap.
5403 painter->setTransform(QTransform());
5404 painter->drawPixmap(deviceRect.topLeft(), pixmap);
5405 painter->setTransform(originalTransform);
5410 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
5411 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5416 #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
5417 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5418 dirtyOnWidget = QRegion();
5420 // We disable the rendering of QToolBar in the backingStore if
5421 // it's supposed to be in the unified toolbar on Mac OS X.
5422 if (backingStore && isInUnifiedToolbar)
5424 #endif // Q_WS_MAC && QT_MAC_USE_COCOA
5428 #ifndef QT_NO_GRAPHICSEFFECT
5429 if (graphicsEffect && graphicsEffect->isEnabled()) {
5430 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5431 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5433 if (!sourced->context) {
5434 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5435 sourced->context = &context;
5436 if (!sharedPainter) {
5437 QPaintEngine *paintEngine = pdev->paintEngine();
5438 paintEngine->d_func()->systemClip = rgn.translated(offset);
5440 p.translate(offset);
5441 context.painter = &p;
5442 graphicsEffect->draw(&p);
5443 paintEngine->d_func()->systemClip = QRegion();
5445 context.painter = sharedPainter;
5446 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5447 sourced->invalidateCache();
5448 sourced->lastEffectTransform = sharedPainter->worldTransform();
5450 sharedPainter->save();
5451 sharedPainter->translate(offset);
5452 graphicsEffect->draw(sharedPainter);
5453 sharedPainter->restore();
5455 sourced->context = 0;
5459 #endif //QT_NO_GRAFFICSEFFECT
5461 const bool asRoot = flags & DrawAsRoot;
5462 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5463 const bool recursive = flags & DrawRecursive;
5464 const bool alsoInvisible = flags & DrawInvisible;
5466 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5468 QRegion toBePainted(rgn);
5469 if (asRoot && !alsoInvisible)
5470 toBePainted &= clipRect(); //(rgn & visibleRegion());
5471 if (!(flags & DontSubtractOpaqueChildren))
5472 subtractOpaqueChildren(toBePainted, q->rect());
5474 if (!toBePainted.isEmpty()) {
5475 bool onScreen = paintOnScreen();
5476 if (!onScreen || alsoOnScreen) {
5477 //update the "in paint event" flag
5478 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5479 qWarning("QWidget::repaint: Recursive repaint detected");
5480 q->setAttribute(Qt::WA_WState_InPaintEvent);
5482 //clip away the new area
5483 #ifndef QT_NO_PAINT_DEBUG
5484 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5486 QPaintEngine *paintEngine = pdev->paintEngine();
5488 setRedirected(pdev, -offset);
5491 // (Alien support) Special case for Mac when redirecting: If the paint device
5492 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5493 // outside the paint event is not supported on QWidgets. The attributeis
5494 // restored further down.
5495 if (pdev->devType() == QInternal::Widget)
5496 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5500 paintEngine->d_func()->systemClip = toBePainted;
5502 paintEngine->d_func()->systemRect = q->data->crect;
5504 //paint the background
5505 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5506 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5508 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5512 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5514 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5516 QColor tint = q->palette().window().color();
5517 tint.setAlphaF(qreal(.6));
5518 p.fillRect(toBePainted.boundingRect(), tint);
5523 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5524 qDebug() << "clipping to" << toBePainted << "location == " << offset
5525 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5528 //actually send the paint event
5529 QPaintEvent e(toBePainted);
5530 QCoreApplication::sendSpontaneousEvent(q, &e);
5531 #if !defined(Q_WS_QPA)
5532 if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
5533 backingStore->markDirtyOnScreen(toBePainted, q, offset);
5539 if (pdev->devType() == QInternal::Widget)
5540 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5542 restoreRedirected();
5544 paintEngine->d_func()->systemRect = QRect();
5546 paintEngine->d_func()->currentClipDevice = 0;
5547 paintEngine->d_func()->systemClip = QRegion();
5549 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5550 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5551 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5553 if (paintEngine && paintEngine->autoDestruct()) {
5557 #ifndef QT_NO_PAINT_DEBUG
5559 QWidgetBackingStore::unflushPaint(q, toBePainted);
5561 } else if (q->isWindow()) {
5562 QPaintEngine *engine = pdev->paintEngine();
5565 p.setClipRegion(toBePainted);
5566 const QBrush bg = q->palette().brush(QPalette::Window);
5567 if (bg.style() == Qt::TexturePattern)
5568 p.drawTiledPixmap(q->rect(), bg.texture());
5570 p.fillRect(q->rect(), bg);
5572 if (engine->autoDestruct())
5578 if (recursive && !children.isEmpty()) {
5579 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5580 , sharedPainter, backingStore);
5584 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5585 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5589 qWarning("QWidget::render: null pointer to paint device");
5593 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5594 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5595 ? prepareToRender(sourceRegion, renderFlags)
5597 if (paintRegion.isEmpty())
5601 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5603 // Use the target's shared painter if set (typically set when doing
5604 // "other->render(widget);" in the widget's paintEvent.
5605 if (target->devType() == QInternal::Widget) {
5606 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5607 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5608 QPainter *targetPainter = targetPrivate->sharedPainter();
5609 if (targetPainter && targetPainter->isActive())
5610 setSharedPainter(targetPainter);
5615 // Use the target's redirected device if set and adjust offset and paint
5616 // region accordingly. This is typically the case when people call render
5617 // from the paintEvent.
5618 QPoint offset = targetOffset;
5619 offset -= paintRegion.boundingRect().topLeft();
5620 QPoint redirectionOffset;
5621 QPaintDevice *redirected = 0;
5623 if (target->devType() == QInternal::Widget)
5624 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5626 redirected = QPainter::redirected(target, &redirectionOffset);
5629 target = redirected;
5630 offset -= redirectionOffset;
5633 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5634 if (QPaintEngine *targetEngine = target->paintEngine()) {
5635 const QRegion targetSystemClip = targetEngine->systemClip();
5636 if (!targetSystemClip.isEmpty())
5637 paintRegion &= targetSystemClip.translated(-offset);
5641 // Set backingstore flags.
5642 int flags = DrawPaintOnScreen | DrawInvisible;
5643 if (renderFlags & QWidget::DrawWindowBackground)
5644 flags |= DrawAsRoot;
5646 if (renderFlags & QWidget::DrawChildren)
5647 flags |= DrawRecursive;
5649 flags |= DontSubtractOpaqueChildren;
5651 if (target->devType() == QInternal::Printer) {
5653 render_helper(&p, targetOffset, paintRegion, renderFlags);
5658 // Render via backingstore.
5659 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5661 // Restore shared painter.
5662 if (oldSharedPainter)
5663 setSharedPainter(oldSharedPainter);
5665 // Render via backingstore (no shared painter).
5666 drawWidget(target, paintRegion, offset, flags, 0);
5670 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5671 const QPoint &offset, int flags
5672 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5676 bool dirtyBoundingRect = true;
5677 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5678 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5681 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5682 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5683 && !(excludeNativeChildren && x->internalWinId())) {
5684 if (dirtyBoundingRect) {
5685 boundingRect = rgn.boundingRect();
5686 dirtyBoundingRect = false;
5689 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5695 } while (index >= 0);
5700 QWidgetPrivate *wd = w->d_func();
5701 const QPoint widgetPos(w->data->crect.topLeft());
5702 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5706 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5707 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5708 , sharedPainter, backingStore);
5711 if (w->updatesEnabled()
5712 #ifndef QT_NO_GRAPHICSVIEW
5713 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5714 #endif //QT_NO_GRAPHICSVIEW
5716 QRegion wRegion(rgn);
5717 wRegion &= wd->effectiveRectFor(w->data->crect);
5718 wRegion.translate(-widgetPos);
5720 wRegion &= wd->extra->mask;
5721 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5725 #ifndef QT_NO_GRAPHICSEFFECT
5726 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5728 if (system != Qt::DeviceCoordinates)
5729 return m_widget->rect();
5732 // Device coordinates without context not yet supported.
5733 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5737 return context->painter->worldTransform().mapRect(m_widget->rect());
5740 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5742 if (!context || context->painter != painter) {
5743 m_widget->render(painter);
5747 // The region saved in the context is neither clipped to the rect
5748 // nor the mask, so we have to clip it here before calling drawWidget.
5749 QRegion toBePainted = context->rgn;
5750 toBePainted &= m_widget->rect();
5751 QWidgetPrivate *wd = qt_widget_private(m_widget);
5752 if (wd->extra && wd->extra->hasMask)
5753 toBePainted &= wd->extra->mask;
5755 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5756 context->sharedPainter, context->backingStore);
5759 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5760 QGraphicsEffect::PixmapPadMode mode) const
5762 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5763 if (!context && deviceCoordinates) {
5764 // Device coordinates without context not yet supported.
5765 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5769 QPoint pixmapOffset;
5770 QRectF sourceRect = m_widget->rect();
5772 if (deviceCoordinates) {
5773 const QTransform &painterTransform = context->painter->worldTransform();
5774 sourceRect = painterTransform.mapRect(sourceRect);
5775 pixmapOffset = painterTransform.map(pixmapOffset);
5780 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5781 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5782 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5783 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5785 effectRect = sourceRect.toAlignedRect();
5788 *offset = effectRect.topLeft();
5790 pixmapOffset -= effectRect.topLeft();
5792 QPixmap pixmap(effectRect.size());
5793 pixmap.fill(Qt::transparent);
5794 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5797 #endif //QT_NO_GRAPHICSEFFECT
5799 #ifndef QT_NO_GRAPHICSVIEW
5803 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5804 widget and its ancestors. The search starts at \a origin (inclusive).
5805 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5808 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5811 QWExtra *extra = origin->d_func()->extra;
5812 if (extra && extra->proxyWidget)
5813 return extra->proxyWidget;
5814 return nearestGraphicsProxyWidget(origin->parentWidget());
5821 \property QWidget::locale
5822 \brief the widget's locale
5825 As long as no special locale has been set, this is either
5826 the parent's locale or (if this widget is a top level widget),
5829 If the widget displays dates or numbers, these should be formatted
5830 using the widget's locale.
5832 \sa QLocale QLocale::setDefault()
5835 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5838 if (locale == loc && !forceUpdate)
5843 if (!children.isEmpty()) {
5844 for (int i = 0; i < children.size(); ++i) {
5845 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5848 if (w->testAttribute(Qt::WA_SetLocale))
5850 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5852 w->d_func()->setLocale_helper(loc, forceUpdate);
5855 QEvent e(QEvent::LocaleChange);
5856 QApplication::sendEvent(q, &e);
5859 void QWidget::setLocale(const QLocale &locale)
5863 setAttribute(Qt::WA_SetLocale);
5864 d->setLocale_helper(locale);
5867 QLocale QWidget::locale() const
5874 void QWidgetPrivate::resolveLocale()
5878 if (!q->testAttribute(Qt::WA_SetLocale)) {
5879 setLocale_helper(q->isWindow()
5881 : q->parentWidget()->locale());
5885 void QWidget::unsetLocale()
5888 setAttribute(Qt::WA_SetLocale, false);
5892 static QString constructWindowTitleFromFilePath(const QString &filePath)
5894 QFileInfo fi(filePath);
5895 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5897 QString appName = QApplication::applicationName();
5898 if (!appName.isEmpty())
5899 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5905 \property QWidget::windowTitle
5906 \brief the window title (caption)
5908 This property only makes sense for top-level widgets, such as
5909 windows and dialogs. If no caption has been set, the title is based of the
5910 \l windowFilePath. If neither of these is set, then the title is
5913 If you use the \l windowModified mechanism, the window title must
5914 contain a "[*]" placeholder, which indicates where the '*' should
5915 appear. Normally, it should appear right after the file name
5916 (e.g., "document1.txt[*] - Text Editor"). If the \l
5917 windowModified property is false (the default), the placeholder
5920 \sa windowIcon, windowIconText, windowModified, windowFilePath
5922 QString QWidget::windowTitle() const
5925 if (d->extra && d->extra->topextra) {
5926 if (!d->extra->topextra->caption.isEmpty())
5927 return d->extra->topextra->caption;
5928 if (!d->extra->topextra->filePath.isEmpty())
5929 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5935 Returns a modified window title with the [*] place holder
5936 replaced according to the rules described in QWidget::setWindowTitle
5938 This function assumes that "[*]" can be quoted by another
5939 "[*]", so it will replace two place holders by one and
5940 a single last one by either "*" or nothing depending on
5945 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5950 extern QString qt_eval_adapt_window_title(const QString &title);
5951 QString cap = qt_eval_adapt_window_title(title);
5953 QString cap = title;
5959 QLatin1String placeHolder("[*]");
5960 int placeHolderLength = 3; // QLatin1String doesn't have length()
5962 int index = cap.indexOf(placeHolder);
5964 // here the magic begins
5965 while (index != -1) {
5966 index += placeHolderLength;
5968 while (cap.indexOf(placeHolder, index) == index) {
5970 index += placeHolderLength;
5973 if (count%2) { // odd number of [*] -> replace last one
5974 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5975 if (widget->isWindowModified()
5976 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5977 cap.replace(lastIndex, 3, QWidget::tr("*"));
5979 cap.remove(lastIndex, 3);
5982 index = cap.indexOf(placeHolder, index);
5985 cap.replace(QLatin1String("[*][*]"), placeHolder);
5990 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5993 if (q->testAttribute(Qt::WA_WState_Created))
5994 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5997 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
6000 if (q->testAttribute(Qt::WA_WState_Created))
6001 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
6004 void QWidget::setWindowIconText(const QString &iconText)
6006 if (QWidget::windowIconText() == iconText)
6010 d->topData()->iconText = iconText;
6011 d->setWindowIconText_helper(iconText);
6013 QEvent e(QEvent::IconTextChange);
6014 QApplication::sendEvent(this, &e);
6017 void QWidget::setWindowTitle(const QString &title)
6019 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
6023 d->topData()->caption = title;
6024 d->setWindowTitle_helper(title);
6026 QEvent e(QEvent::WindowTitleChange);
6027 QApplication::sendEvent(this, &e);
6032 \property QWidget::windowIcon
6033 \brief the widget's icon
6035 This property only makes sense for windows. If no icon
6036 has been set, windowIcon() returns the application icon
6037 (QApplication::windowIcon()).
6039 \sa windowIconText, windowTitle
6041 QIcon QWidget::windowIcon() const
6043 const QWidget *w = this;
6045 const QWidgetPrivate *d = w->d_func();
6046 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
6047 return *d->extra->topextra->icon;
6048 w = w->parentWidget();
6050 return QApplication::windowIcon();
6053 void QWidgetPrivate::setWindowIcon_helper()
6055 QEvent e(QEvent::WindowIconChange);
6056 QApplication::sendEvent(q_func(), &e);
6057 for (int i = 0; i < children.size(); ++i) {
6058 QWidget *w = qobject_cast<QWidget *>(children.at(i));
6059 if (w && !w->isWindow())
6060 QApplication::sendEvent(w, &e);
6064 void QWidget::setWindowIcon(const QIcon &icon)
6068 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
6071 if (!d->extra->topextra->icon)
6072 d->extra->topextra->icon = new QIcon();
6073 *d->extra->topextra->icon = icon;
6075 delete d->extra->topextra->iconPixmap;
6076 d->extra->topextra->iconPixmap = 0;
6078 d->setWindowIcon_sys();
6079 d->setWindowIcon_helper();
6084 \property QWidget::windowIconText
6085 \brief the widget's icon text
6087 This property only makes sense for windows. If no icon
6088 text has been set, this functions returns an empty string.
6090 \sa windowIcon, windowTitle
6093 QString QWidget::windowIconText() const
6096 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
6100 \property QWidget::windowFilePath
6102 \brief the file path associated with a widget
6104 This property only makes sense for windows. It associates a file path with
6105 a window. If you set the file path, but have not set the window title, Qt
6106 sets the window title to contain a string created using the following
6112 \o The file name of the specified path, obtained using QFileInfo::fileName().
6118 \o The file name of the specified path, obtained using QFileInfo::fileName().
6119 \o An optional \c{*} character, if the \l windowModified property is set.
6120 \o The \c{0x2014} unicode character, padded either side by spaces.
6121 \o The application name, obtained from the application's
6122 \l{QCoreApplication::}{applicationName} property.
6125 If the window title is set at any point, then the window title takes precedence and
6126 will be shown instead of the file path string.
6128 Additionally, on Mac OS X, this has an added benefit that it sets the
6129 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
6130 for the window, assuming that the file path exists.
6132 If no file path is set, this property contains an empty string.
6134 By default, this property contains an empty string.
6136 \sa windowTitle, windowIcon
6139 QString QWidget::windowFilePath() const
6142 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
6145 void QWidget::setWindowFilePath(const QString &filePath)
6147 if (filePath == windowFilePath())
6153 d->extra->topextra->filePath = filePath;
6154 d->setWindowFilePath_helper(filePath);
6157 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
6159 if (extra->topextra && extra->topextra->caption.isEmpty()) {
6161 setWindowTitle_helper(QFileInfo(filePath).fileName());
6165 setWindowTitle_helper(q->windowTitle());
6169 setWindowFilePath_sys(filePath);
6174 Returns the window's role, or an empty string.
6176 \sa windowIcon, windowTitle
6179 QString QWidget::windowRole() const
6182 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
6186 Sets the window's role to \a role. This only makes sense for
6189 void QWidget::setWindowRole(const QString &role)
6191 #if defined(Q_WS_X11)
6193 d->topData()->role = role;
6201 \property QWidget::mouseTracking
6202 \brief whether mouse tracking is enabled for the widget
6204 If mouse tracking is disabled (the default), the widget only
6205 receives mouse move events when at least one mouse button is
6206 pressed while the mouse is being moved.
6208 If mouse tracking is enabled, the widget receives mouse move
6209 events even if no buttons are pressed.
6211 \sa mouseMoveEvent()
6216 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
6217 function resets this widget to have no focus proxy.
6219 Some widgets can "have focus", but create a child widget, such as
6220 QLineEdit, to actually handle the focus. In this case, the widget
6221 can set the line edit to be its focus proxy.
6223 setFocusProxy() sets the widget which will actually get focus when
6224 "this widget" gets it. If there is a focus proxy, setFocus() and
6225 hasFocus() operate on the focus proxy.
6230 void QWidget::setFocusProxy(QWidget * w)
6233 if (!w && !d->extra)
6236 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
6238 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
6244 d->extra->focus_proxy = w;
6249 Returns the focus proxy, or 0 if there is no focus proxy.
6254 QWidget * QWidget::focusProxy() const
6257 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
6262 \property QWidget::focus
6263 \brief whether this widget (or its focus proxy) has the keyboard
6266 By default, this property is false.
6268 \note Obtaining the value of this property for a widget is effectively equivalent
6269 to checking whether QApplication::focusWidget() refers to the widget.
6271 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
6273 bool QWidget::hasFocus() const
6275 const QWidget* w = this;
6276 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
6277 w = w->d_func()->extra->focus_proxy;
6278 if (QWidget *window = w->window()) {
6279 #ifndef QT_NO_GRAPHICSVIEW
6280 QWExtra *e = window->d_func()->extra;
6281 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
6285 return (QApplication::focusWidget() == w);
6289 Gives the keyboard input focus to this widget (or its focus
6290 proxy) if this widget or one of its parents is the \link
6291 isActiveWindow() active window\endlink. The \a reason argument will
6292 be passed into any focus event sent from this function, it is used
6293 to give an explanation of what caused the widget to get focus.
6294 If the window is not active, the widget will be given the focus when
6295 the window becomes active.
6297 First, a focus out event is sent to the focus widget (if any) to
6298 tell it that it is about to lose the focus. Then a focus in event
6299 is sent to this widget to tell it that it just received the focus.
6300 (Nothing happens if the focus in and focus out widgets are the
6303 \note On embedded platforms, setFocus() will not cause an input panel
6304 to be opened by the input method. If you want this to happen, you
6305 have to send a QEvent::RequestSoftwareInputPanel event to the
6308 setFocus() gives focus to a widget regardless of its focus policy,
6309 but does not clear any keyboard grab (see grabKeyboard()).
6311 Be aware that if the widget is hidden, it will not accept focus
6314 \warning If you call setFocus() in a function which may itself be
6315 called from focusOutEvent() or focusInEvent(), you may get an
6318 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
6319 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
6320 grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
6323 void QWidget::setFocus(Qt::FocusReason reason)
6329 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
6330 f = f->d_func()->extra->focus_proxy;
6332 if (QApplication::focusWidget() == f
6333 #if defined(Q_WS_WIN)
6334 && GetFocus() == f->internalWinId()
6339 #ifndef QT_NO_GRAPHICSVIEW
6340 QWidget *previousProxyFocus = 0;
6341 if (QWExtra *topData = window()->d_func()->extra) {
6342 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
6343 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
6344 if (previousProxyFocus && previousProxyFocus->focusProxy())
6345 previousProxyFocus = previousProxyFocus->focusProxy();
6346 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
6354 while (w && w->isHidden()) {
6355 w->d_func()->focus_child = f;
6356 w = w->isWindow() ? 0 : w->parentWidget();
6360 w->d_func()->focus_child = f;
6361 w = w->isWindow() ? 0 : w->parentWidget();
6365 #ifndef QT_NO_GRAPHICSVIEW
6366 // Update proxy state
6367 if (QWExtra *topData = window()->d_func()->extra) {
6368 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
6369 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
6370 topData->proxyWidget->setFocus(reason);
6371 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
6376 if (f->isActiveWindow()) {
6377 QApplicationPrivate::setFocusWidget(f, reason);
6378 #ifndef QT_NO_ACCESSIBILITY
6380 // The negation of the condition in setFocus_sys
6381 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
6382 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
6385 // menus update the focus manually and this would create bogus events
6386 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
6388 QAccessible::updateAccessibility(f, 0, QAccessible::Focus);
6390 #ifndef QT_NO_GRAPHICSVIEW
6391 if (QWExtra *topData = window()->d_func()->extra) {
6392 if (topData->proxyWidget) {
6393 if (previousProxyFocus && previousProxyFocus != f) {
6394 // Send event to self
6395 QFocusEvent event(QEvent::FocusOut, reason);
6396 QPointer<QWidget> that = previousProxyFocus;
6397 QApplication::sendEvent(previousProxyFocus, &event);
6399 QApplication::sendEvent(that->style(), &event);
6402 #ifndef QT_NO_GRAPHICSVIEW
6403 // Update proxy state
6404 if (QWExtra *topData = window()->d_func()->extra)
6405 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
6406 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
6408 // Send event to self
6409 QFocusEvent event(QEvent::FocusIn, reason);
6410 QPointer<QWidget> that = f;
6411 QApplication::sendEvent(f, &event);
6413 QApplication::sendEvent(that->style(), &event);
6422 \fn void QWidget::setFocus()
6425 Gives the keyboard input focus to this widget (or its focus
6426 proxy) if this widget or one of its parents is the
6427 \l{isActiveWindow()}{active window}.
6431 Takes keyboard input focus from the widget.
6433 If the widget has active focus, a \link focusOutEvent() focus out
6434 event\endlink is sent to this widget to tell it that it is about
6437 This widget must enable focus setting in order to get the keyboard
6438 input focus, i.e. it must call setFocusPolicy().
6440 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6441 setFocusPolicy(), QApplication::focusWidget()
6444 void QWidget::clearFocus()
6448 if (w->d_func()->focus_child == this)
6449 w->d_func()->focus_child = 0;
6450 w = w->parentWidget();
6452 #ifndef QT_NO_GRAPHICSVIEW
6453 QWExtra *topData = d_func()->extra;
6454 if (topData && topData->proxyWidget)
6455 topData->proxyWidget->clearFocus();
6459 // Update proxy state
6460 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6461 #if defined(Q_WS_WIN)
6462 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6467 #ifndef QT_NO_ACCESSIBILITY
6468 QAccessible::updateAccessibility(this, 0, QAccessible::Focus);
6476 \fn bool QWidget::focusNextChild()
6478 Finds a new widget to give the keyboard focus to, as appropriate
6479 for \key Tab, and returns true if it can find a new widget, or
6482 \sa focusPreviousChild()
6486 \fn bool QWidget::focusPreviousChild()
6488 Finds a new widget to give the keyboard focus to, as appropriate
6489 for \key Shift+Tab, and returns true if it can find a new widget,
6490 or false if it can't.
6492 \sa focusNextChild()
6496 Finds a new widget to give the keyboard focus to, as appropriate
6497 for Tab and Shift+Tab, and returns true if it can find a new
6498 widget, or false if it can't.
6500 If \a next is true, this function searches forward, if \a next
6501 is false, it searches backward.
6503 Sometimes, you will want to reimplement this function. For
6504 example, a web browser might reimplement it to move its "current
6505 active link" forward or backward, and call
6506 focusNextPrevChild() only when it reaches the last or
6507 first link on the "page".
6509 Child widgets call focusNextPrevChild() on their parent widgets,
6510 but only the window that contains the child widgets decides where
6511 to redirect focus. By reimplementing this function for an object,
6512 you thus gain control of focus traversal for all child widgets.
6514 \sa focusNextChild(), focusPreviousChild()
6517 bool QWidget::focusNextPrevChild(bool next)
6520 QWidget* p = parentWidget();
6521 bool isSubWindow = (windowType() == Qt::SubWindow);
6522 if (!isWindow() && !isSubWindow && p)
6523 return p->focusNextPrevChild(next);
6524 #ifndef QT_NO_GRAPHICSVIEW
6525 if (d->extra && d->extra->proxyWidget)
6526 return d->extra->proxyWidget->focusNextPrevChild(next);
6528 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6529 if (!w) return false;
6531 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6536 Returns the last child of this widget that setFocus had been
6537 called on. For top level widgets this is the widget that will get
6538 focus in case this window gets activated
6540 This is not the same as QApplication::focusWidget(), which returns
6541 the focus widget in the currently active window.
6544 QWidget *QWidget::focusWidget() const
6546 return const_cast<QWidget *>(d_func()->focus_child);
6550 Returns the next widget in this widget's focus chain.
6552 \sa previousInFocusChain()
6554 QWidget *QWidget::nextInFocusChain() const
6556 return const_cast<QWidget *>(d_func()->focus_next);
6560 \brief The previousInFocusChain function returns the previous
6561 widget in this widget's focus chain.
6563 \sa nextInFocusChain()
6567 QWidget *QWidget::previousInFocusChain() const
6569 return const_cast<QWidget *>(d_func()->focus_prev);
6573 \property QWidget::isActiveWindow
6574 \brief whether this widget's window is the active window
6576 The active window is the window that contains the widget that has
6577 keyboard focus (The window may still have focus if it has no
6578 widgets or none of its widgets accepts keyboard focus).
6580 When popup windows are visible, this property is true for both the
6581 active window \e and for the popup.
6583 By default, this property is false.
6585 \sa activateWindow(), QApplication::activeWindow()
6587 bool QWidget::isActiveWindow() const
6589 QWidget *tlw = window();
6590 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6593 #ifndef QT_NO_GRAPHICSVIEW
6594 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6595 if (isVisible() && tlwExtra->proxyWidget)
6596 return tlwExtra->proxyWidget->isActiveWindow();
6601 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6602 if(qt_mac_is_macdrawer(tlw) &&
6603 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6606 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6607 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6610 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6611 if(tlw->windowType() == Qt::Tool &&
6613 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6615 QWidget *w = QApplication::activeWindow();
6616 while(w && tlw->windowType() == Qt::Tool &&
6617 !w->isModal() && w->parentWidget()) {
6618 w = w->parentWidget()->window();
6623 #if defined(Q_WS_WIN32)
6624 HWND active = GetActiveWindow();
6625 if (!tlw->testAttribute(Qt::WA_WState_Created))
6627 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6634 Puts the \a second widget after the \a first widget in the focus order.
6636 Note that since the tab order of the \a second widget is changed, you
6637 should order a chain like this:
6639 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6643 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6645 If \a first or \a second has a focus proxy, setTabOrder()
6646 correctly substitutes the proxy.
6648 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6650 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6652 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6655 if (first->window() != second->window()) {
6656 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6660 QWidget *fp = first->focusProxy();
6662 // If first is redirected, set first to the last child of first
6663 // that can take keyboard focus so that second is inserted after
6664 // that last child, and the focus order within first is (more
6665 // likely to be) preserved.
6666 QList<QWidget *> l = first->findChildren<QWidget *>();
6667 for (int i = l.size()-1; i >= 0; --i) {
6668 QWidget * next = l.at(i);
6669 if (next->window() == fp->window()) {
6671 if (fp->focusPolicy() != Qt::NoFocus)
6681 if (QWidget *sp = second->focusProxy())
6684 // QWidget *fp = first->d_func()->focus_prev;
6685 QWidget *fn = first->d_func()->focus_next;
6687 if (fn == second || first == second)
6690 QWidget *sp = second->d_func()->focus_prev;
6691 QWidget *sn = second->d_func()->focus_next;
6693 fn->d_func()->focus_prev = second;
6694 first->d_func()->focus_next = second;
6696 second->d_func()->focus_next = fn;
6697 second->d_func()->focus_prev = first;
6699 sp->d_func()->focus_next = sn;
6700 sn->d_func()->focus_prev = sp;
6703 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6704 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6706 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6707 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6712 Moves the relevant subwidgets of this widget from the \a oldtlw's
6713 tab chain to that of the new parent, if there's anything to move and
6716 This function is called from QWidget::reparent() *after* the widget
6717 has been reparented.
6722 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6725 if (oldtlw == q->window())
6726 return; // nothing to do
6729 focus_child->clearFocus();
6731 // separate the focus chain into new (children of myself) and old (the rest)
6732 QWidget *firstOld = 0;
6733 //QWidget *firstNew = q; //invariant
6734 QWidget *o = 0; // last in the old list
6735 QWidget *n = q; // last in the new list
6737 bool prevWasNew = true;
6738 QWidget *w = focus_next;
6740 //Note: for efficiency, we do not maintain the list invariant inside the loop
6741 //we append items to the relevant list, and we optimize by not changing pointers
6742 //when subsequent items are going into the same list.
6744 bool currentIsNew = q->isAncestorOf(w);
6747 //prev was old -- append to new list
6748 n->d_func()->focus_next = w;
6749 w->d_func()->focus_prev = n;
6754 //prev was new -- append to old list, if there is one
6756 o->d_func()->focus_next = w;
6757 w->d_func()->focus_prev = o;
6759 // "create" the old list
6765 w = w->d_func()->focus_next;
6766 prevWasNew = currentIsNew;
6769 //repair the old list:
6771 o->d_func()->focus_next = firstOld;
6772 firstOld->d_func()->focus_prev = o;
6775 if (!q->isWindow()) {
6776 QWidget *topLevel = q->window();
6777 //insert new chain into toplevel's chain
6779 QWidget *prev = topLevel->d_func()->focus_prev;
6781 topLevel->d_func()->focus_prev = n;
6782 prev->d_func()->focus_next = q;
6785 n->d_func()->focus_next = topLevel;
6787 //repair the new list
6788 n->d_func()->focus_next = q;
6796 Measures the shortest distance from a point to a rect.
6798 This function is called from QDesktopwidget::screen(QPoint) to find the
6799 closest screen for a point.
6800 In directional KeypadNavigation, it is called to find the closest
6801 widget to the current focus widget center.
6803 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6807 if (p.x() < r.left())
6808 dx = r.left() - p.x();
6809 else if (p.x() > r.right())
6810 dx = p.x() - r.right();
6811 if (p.y() < r.top())
6812 dy = r.top() - p.y();
6813 else if (p.y() > r.bottom())
6814 dy = p.y() - r.bottom();
6819 \property QWidget::frameSize
6820 \brief the size of the widget including any window frame
6822 By default, this property contains a value that depends on the user's
6823 platform and screen geometry.
6825 QSize QWidget::frameSize() const
6828 if (isWindow() && !(windowType() == Qt::Popup)) {
6829 QRect fs = d->frameStrut();
6830 return QSize(data->crect.width() + fs.left() + fs.right(),
6831 data->crect.height() + fs.top() + fs.bottom());
6833 return data->crect.size();
6836 /*! \fn void QWidget::move(int x, int y)
6840 This corresponds to move(QPoint(\a x, \a y)).
6843 void QWidget::move(const QPoint &p)
6846 setAttribute(Qt::WA_Moved);
6848 d->topData()->posFromMove = true;
6849 if (testAttribute(Qt::WA_WState_Created)) {
6850 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6851 p.y() + geometry().y() - QWidget::y(),
6852 width(), height(), true);
6853 d->setDirtyOpaqueRegion();
6855 data->crect.moveTopLeft(p); // no frame yet
6856 setAttribute(Qt::WA_PendingMoveEvent);
6860 /*! \fn void QWidget::resize(int w, int h)
6863 This corresponds to resize(QSize(\a w, \a h)).
6866 void QWidget::resize(const QSize &s)
6869 setAttribute(Qt::WA_Resized);
6870 if (testAttribute(Qt::WA_WState_Created)) {
6871 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6872 d->setDirtyOpaqueRegion();
6874 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6875 setAttribute(Qt::WA_PendingResizeEvent);
6879 void QWidget::setGeometry(const QRect &r)
6882 setAttribute(Qt::WA_Resized);
6883 setAttribute(Qt::WA_Moved);
6885 d->topData()->posFromMove = false;
6886 if (testAttribute(Qt::WA_WState_Created)) {
6887 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6888 d->setDirtyOpaqueRegion();
6890 data->crect.setTopLeft(r.topLeft());
6891 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6892 setAttribute(Qt::WA_PendingMoveEvent);
6893 setAttribute(Qt::WA_PendingResizeEvent);
6899 Saves the current geometry and state for top-level widgets.
6901 To save the geometry when the window closes, you can
6902 implement a close event like this:
6904 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6906 See the \l{Window Geometry} documentation for an overview of geometry
6907 issues with windows.
6909 Use QMainWindow::saveState() to save the geometry and the state of
6910 toolbars and dock widgets.
6912 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6914 QByteArray QWidget::saveGeometry() const
6916 #ifdef QT_MAC_USE_COCOA
6917 // We check if the window was maximized during this invocation. If so, we need to record the
6918 // starting position as 0,0.
6920 QRect newFramePosition = frameGeometry();
6921 QRect newNormalPosition = normalGeometry();
6922 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6923 // Change the starting position
6924 newFramePosition.moveTo(0, 0);
6925 newNormalPosition.moveTo(0, 0);
6927 #endif // QT_MAC_USE_COCOA
6929 QDataStream stream(&array, QIODevice::WriteOnly);
6930 stream.setVersion(QDataStream::Qt_4_0);
6931 const quint32 magicNumber = 0x1D9D0CB;
6932 quint16 majorVersion = 1;
6933 quint16 minorVersion = 0;
6934 stream << magicNumber
6937 #ifdef QT_MAC_USE_COCOA
6939 << newNormalPosition
6943 #endif // QT_MAC_USE_COCOA
6944 << qint32(QApplication::desktop()->screenNumber(this))
6945 << quint8(windowState() & Qt::WindowMaximized)
6946 << quint8(windowState() & Qt::WindowFullScreen);
6953 Restores the geometry and state top-level widgets stored in the
6954 byte array \a geometry. Returns true on success; otherwise
6957 If the restored geometry is off-screen, it will be modified to be
6958 inside the available screen geometry.
6960 To restore geometry saved using QSettings, you can use code like
6963 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6965 See the \l{Window Geometry} documentation for an overview of geometry
6966 issues with windows.
6968 Use QMainWindow::restoreState() to restore the geometry and the
6969 state of toolbars and dock widgets.
6971 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6973 bool QWidget::restoreGeometry(const QByteArray &geometry)
6975 if (geometry.size() < 4)
6977 QDataStream stream(geometry);
6978 stream.setVersion(QDataStream::Qt_4_0);
6980 const quint32 magicNumber = 0x1D9D0CB;
6981 quint32 storedMagicNumber;
6982 stream >> storedMagicNumber;
6983 if (storedMagicNumber != magicNumber)
6986 const quint16 currentMajorVersion = 1;
6987 quint16 majorVersion = 0;
6988 quint16 minorVersion = 0;
6990 stream >> majorVersion >> minorVersion;
6992 if (majorVersion != currentMajorVersion)
6994 // (Allow all minor versions.)
6996 QRect restoredFrameGeometry;
6997 QRect restoredNormalGeometry;
6998 qint32 restoredScreenNumber;
7002 stream >> restoredFrameGeometry
7003 >> restoredNormalGeometry
7004 >> restoredScreenNumber
7008 const int frameHeight = 20;
7009 if (!restoredFrameGeometry.isValid())
7010 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
7012 if (!restoredNormalGeometry.isValid())
7013 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
7014 if (!restoredNormalGeometry.isValid()) {
7015 // use the widget's adjustedSize if the sizeHint() doesn't help
7016 restoredNormalGeometry.setSize(restoredNormalGeometry
7018 .expandedTo(d_func()->adjustedSize()));
7021 const QDesktopWidget * const desktop = QApplication::desktop();
7022 if (restoredScreenNumber >= desktop->numScreens())
7023 restoredScreenNumber = desktop->primaryScreen();
7025 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
7027 // Modify the restored geometry if we are about to restore to coordinates
7028 // that would make the window "lost". This happens if:
7029 // - The restored geometry is completely oustside the available geometry
7030 // - The title bar is outside the available geometry.
7031 // - (Mac only) The window is higher than the available geometry. It must
7032 // be possible to bring the size grip on screen by moving the window.
7034 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
7035 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
7038 if (!restoredFrameGeometry.intersects(availableGeometry)) {
7039 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
7040 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
7041 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
7043 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
7045 if (!restoredNormalGeometry.intersects(availableGeometry)) {
7046 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
7047 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
7048 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
7050 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
7052 if (maximized || fullScreen) {
7053 // set geomerty before setting the window state to make
7054 // sure the window is maximized to the right screen.
7055 // Skip on windows: the window is restored into a broken
7056 // half-maximized state.
7058 setGeometry(restoredNormalGeometry);
7060 Qt::WindowStates ws = windowState();
7062 ws |= Qt::WindowMaximized;
7064 ws |= Qt::WindowFullScreen;
7066 d_func()->topData()->normalGeometry = restoredNormalGeometry;
7071 offset = d_func()->topData()->fullScreenOffset;
7073 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
7074 move(restoredFrameGeometry.topLeft() + offset);
7075 resize(restoredNormalGeometry.size());
7080 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
7083 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
7087 Sets the margins around the contents of the widget to have the sizes
7088 \a left, \a top, \a right, and \a bottom. The margins are used by
7089 the layout system, and may be used by subclasses to specify the area
7090 to draw in (e.g. excluding the frame).
7092 Changing the margins will trigger a resizeEvent().
7094 \sa contentsRect(), getContentsMargins()
7096 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
7099 if (left == d->leftmargin && top == d->topmargin
7100 && right == d->rightmargin && bottom == d->bottommargin)
7102 d->leftmargin = left;
7104 d->rightmargin = right;
7105 d->bottommargin = bottom;
7107 if (QLayout *l=d->layout)
7108 l->update(); //force activate; will do updateGeometry
7112 // ### Qt 5: compat, remove
7115 QResizeEvent e(data->crect.size(), data->crect.size());
7116 QApplication::sendEvent(this, &e);
7118 setAttribute(Qt::WA_PendingResizeEvent, true);
7121 QEvent e(QEvent::ContentsRectChange);
7122 QApplication::sendEvent(this, &e);
7129 \brief The setContentsMargins function sets the margins around the
7132 Sets the margins around the contents of the widget to have the
7133 sizes determined by \a margins. The margins are
7134 used by the layout system, and may be used by subclasses to
7135 specify the area to draw in (e.g. excluding the frame).
7137 Changing the margins will trigger a resizeEvent().
7139 \sa contentsRect(), getContentsMargins()
7141 void QWidget::setContentsMargins(const QMargins &margins)
7143 setContentsMargins(margins.left(), margins.top(),
7144 margins.right(), margins.bottom());
7148 Returns the widget's contents margins for \a left, \a top, \a
7149 right, and \a bottom.
7151 \sa setContentsMargins(), contentsRect()
7153 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
7157 *left = d->leftmargin;
7159 *top = d->topmargin;
7161 *right = d->rightmargin;
7163 *bottom = d->bottommargin;
7169 \brief The contentsMargins function returns the widget's contents margins.
7171 \sa getContentsMargins(), setContentsMargins(), contentsRect()
7173 QMargins QWidget::contentsMargins() const
7176 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
7181 Returns the area inside the widget's margins.
7183 \sa setContentsMargins(), getContentsMargins()
7185 QRect QWidget::contentsRect() const
7188 return QRect(QPoint(d->leftmargin, d->topmargin),
7189 QPoint(data->crect.width() - 1 - d->rightmargin,
7190 data->crect.height() - 1 - d->bottommargin));
7197 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
7199 This signal is emitted when the widget's \l contextMenuPolicy is
7200 Qt::CustomContextMenu, and the user has requested a context menu on
7201 the widget. The position \a pos is the position of the context menu
7202 event that the widget receives. Normally this is in widget
7203 coordinates. The exception to this rule is QAbstractScrollArea and
7204 its subclasses that map the context menu event to coordinates of the
7205 \link QAbstractScrollArea::viewport() viewport() \endlink .
7208 \sa mapToGlobal() QMenu contextMenuPolicy
7213 \property QWidget::contextMenuPolicy
7214 \brief how the widget shows a context menu
7216 The default value of this property is Qt::DefaultContextMenu,
7217 which means the contextMenuEvent() handler is called. Other values
7218 are Qt::NoContextMenu, Qt::PreventContextMenu,
7219 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
7220 Qt::CustomContextMenu, the signal customContextMenuRequested() is
7223 \sa contextMenuEvent(), customContextMenuRequested(), actions()
7226 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
7228 return (Qt::ContextMenuPolicy)data->context_menu_policy;
7231 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
7233 data->context_menu_policy = (uint) policy;
7237 \property QWidget::focusPolicy
7238 \brief the way the widget accepts keyboard focus
7240 The policy is Qt::TabFocus if the widget accepts keyboard
7241 focus by tabbing, Qt::ClickFocus if the widget accepts
7242 focus by clicking, Qt::StrongFocus if it accepts both, and
7243 Qt::NoFocus (the default) if it does not accept focus at
7246 You must enable keyboard focus for a widget if it processes
7247 keyboard events. This is normally done from the widget's
7248 constructor. For instance, the QLineEdit constructor calls
7249 setFocusPolicy(Qt::StrongFocus).
7251 If the widget has a focus proxy, then the focus policy will
7252 be propagated to it.
7254 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
7258 Qt::FocusPolicy QWidget::focusPolicy() const
7260 return (Qt::FocusPolicy)data->focus_policy;
7263 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
7265 data->focus_policy = (uint) policy;
7267 if (d->extra && d->extra->focus_proxy)
7268 d->extra->focus_proxy->setFocusPolicy(policy);
7272 \property QWidget::updatesEnabled
7273 \brief whether updates are enabled
7275 An updates enabled widget receives paint events and has a system
7276 background; a disabled widget does not. This also implies that
7277 calling update() and repaint() has no effect if updates are
7280 By default, this property is true.
7282 setUpdatesEnabled() is normally used to disable updates for a
7283 short period of time, for instance to avoid screen flicker during
7284 large changes. In Qt, widgets normally do not generate screen
7285 flicker, but on X11 the server might erase regions on the screen
7286 when widgets get hidden before they can be replaced by other
7287 widgets. Disabling updates solves this.
7290 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
7292 Disabling a widget implicitly disables all its children. Enabling a widget
7293 enables all child widgets \e except top-level widgets or those that
7294 have been explicitly disabled. Re-enabling updates implicitly calls
7295 update() on the widget.
7299 void QWidget::setUpdatesEnabled(bool enable)
7302 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
7303 d->setUpdatesEnabled_helper(enable);
7306 /*! \fn void QWidget::show()
7308 Shows the widget and its child widgets. This function is
7309 equivalent to setVisible(true).
7311 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
7312 showNormal(), isVisible()
7318 Makes the widget visible in the isVisible() meaning of the word.
7319 It is only called for toplevels or widgets with visible parents.
7321 void QWidgetPrivate::show_recursive()
7324 // polish if necessary
7326 if (!q->testAttribute(Qt::WA_WState_Created))
7327 createRecursively();
7328 q->ensurePolished();
7332 QApplication::sendPostedEvents(q, QEvent::ChildInserted);
7334 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
7335 q->parentWidget()->d_func()->layout->activate();
7336 // activate our layout before we and our children become visible
7343 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
7347 disableUpdates = disableUpdates && q->updatesEnabled();
7349 q->setAttribute(Qt::WA_UpdatesDisabled);
7351 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
7352 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
7353 QApplication::sendEvent(q, &e);
7354 q->setAttribute(Qt::WA_PendingMoveEvent, false);
7357 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
7358 QResizeEvent e(data.crect.size(), QSize());
7359 QApplication::sendEvent(q, &e);
7360 q->setAttribute(Qt::WA_PendingResizeEvent, false);
7364 q->setAttribute(Qt::WA_UpdatesDisabled, false);
7369 for (int i = 0; i < children.size(); ++i) {
7370 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
7371 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
7375 void QWidgetPrivate::activateChildLayoutsRecursively()
7377 sendPendingMoveAndResizeEvents(false, true);
7379 for (int i = 0; i < children.size(); ++i) {
7380 QWidget *child = qobject_cast<QWidget *>(children.at(i));
7381 if (!child || child->isHidden() || child->isWindow())
7384 child->ensurePolished();
7386 // Activate child's layout
7387 QWidgetPrivate *childPrivate = child->d_func();
7388 if (childPrivate->layout)
7389 childPrivate->layout->activate();
7391 // Pretend we're visible.
7392 const bool wasVisible = child->isVisible();
7394 child->setAttribute(Qt::WA_WState_Visible);
7396 // Do the same for all my children.
7397 childPrivate->activateChildLayoutsRecursively();
7399 // We're not cheating anymore.
7401 child->setAttribute(Qt::WA_WState_Visible, false);
7405 void QWidgetPrivate::show_helper()
7408 data.in_show = true; // qws optimization
7409 // make sure we receive pending move and resize events
7410 sendPendingMoveAndResizeEvents();
7412 // become visible before showing all children
7413 q->setAttribute(Qt::WA_WState_Visible);
7415 // finally show all children recursively
7416 showChildren(false);
7419 if (q->parentWidget() && sendChildEvents)
7420 QApplication::sendPostedEvents(q->parentWidget(),
7421 QEvent::ChildInserted);
7425 // popup handling: new popups and tools need to be raised, and
7426 // existing popups must be closed. Also propagate the current
7427 // windows's KeyboardFocusChange status.
7428 if (q->isWindow()) {
7429 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7431 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7432 q->setAttribute(Qt::WA_KeyboardFocusChange);
7434 while (QApplication::activePopupWidget()) {
7435 if (!QApplication::activePopupWidget()->close())
7441 // Automatic embedding of child windows of widgets already embedded into
7442 // QGraphicsProxyWidget when they are shown the first time.
7443 bool isEmbedded = false;
7444 #ifndef QT_NO_GRAPHICSVIEW
7445 if (q->isWindow()) {
7446 isEmbedded = q->graphicsProxyWidget() ? true : false;
7447 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7448 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7449 if (ancestorProxy) {
7451 ancestorProxy->d_func()->embedSubWindow(q);
7456 Q_UNUSED(isEmbedded);
7459 // On Windows, show the popup now so that our own focus handling
7460 // stores the correct old focus widget even if it's stolen in the
7462 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
7463 if (!isEmbedded && q->windowType() == Qt::Popup)
7464 qApp->d_func()->openPopup(q);
7467 // send the show event before showing the window
7468 QShowEvent showEvent;
7469 QApplication::sendEvent(q, &showEvent);
7471 if (!isEmbedded && q->isModal() && q->isWindow())
7472 // QApplicationPrivate::enterModal *before* show, otherwise the initial
7473 // stacking might be wrong
7474 QApplicationPrivate::enterModal(q);
7479 #if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN)
7480 if (!isEmbedded && q->windowType() == Qt::Popup)
7481 qApp->d_func()->openPopup(q);
7484 #ifndef QT_NO_ACCESSIBILITY
7485 if (q->windowType() != Qt::ToolTip) // Tooltips are read aloud twice in MS narrator.
7486 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectShow);
7489 if (QApplicationPrivate::hidden_focus_widget == q) {
7490 QApplicationPrivate::hidden_focus_widget = 0;
7491 q->setFocus(Qt::OtherFocusReason);
7494 // Process events when showing a Qt::SplashScreen widget before the event loop
7495 // is spinnning; otherwise it might not show up on particular platforms.
7496 // This makes QSplashScreen behave the same on all platforms.
7497 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7498 QApplication::processEvents();
7500 data.in_show = false; // reset qws optimization
7503 /*! \fn void QWidget::hide()
7505 Hides the widget. This function is equivalent to
7509 \note If you are working with QDialog or its subclasses and you invoke
7510 the show() function after this function, the dialog will be displayed in
7511 its original position.
7513 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7518 void QWidgetPrivate::hide_helper()
7522 bool isEmbedded = false;
7523 #if !defined QT_NO_GRAPHICSVIEW
7524 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7526 Q_UNUSED(isEmbedded);
7529 if (!isEmbedded && (q->windowType() == Qt::Popup))
7530 qApp->d_func()->closePopup(q);
7532 // Move test modal here. Otherwise, a modal dialog could get
7533 // destroyed and we lose all access to its parent because we haven't
7534 // left modality. (Eg. modal Progress Dialog)
7535 if (!isEmbedded && q->isModal() && q->isWindow())
7536 QApplicationPrivate::leaveModal(q);
7538 #if defined(Q_WS_WIN)
7539 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7540 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7541 q->parentWidget()->activateWindow(); // Activate parent
7544 q->setAttribute(Qt::WA_Mapped, false);
7547 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7550 q->setAttribute(Qt::WA_WState_Visible, false);
7554 QHideEvent hideEvent;
7555 QApplication::sendEvent(q, &hideEvent);
7556 hideChildren(false);
7558 // next bit tries to move the focus if the focus widget is now
7561 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7562 qApp->d_func()->sendSyntheticEnterLeave(q);
7565 QWidget *fw = QApplication::focusWidget();
7566 while (fw && !fw->isWindow()) {
7568 q->focusNextPrevChild(true);
7571 fw = fw->parentWidget();
7575 if (QWidgetBackingStore *bs = maybeBackingStore())
7576 bs->removeDirtyWidget(q);
7578 #ifndef QT_NO_ACCESSIBILITY
7580 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectHide);
7585 \fn bool QWidget::isHidden() const
7587 Returns true if the widget is hidden, otherwise returns false.
7589 A hidden widget will only become visible when show() is called on
7590 it. It will not be automatically shown when the parent is shown.
7592 To check visibility, use !isVisible() instead (notice the exclamation mark).
7594 isHidden() implies !isVisible(), but a widget can be not visible
7595 and not hidden at the same time. This is the case for widgets that are children of
7596 widgets that are not visible.
7599 Widgets are hidden if:
7601 \o they were created as independent windows,
7602 \o they were created as children of visible widgets,
7603 \o hide() or setVisible(false) was called.
7608 void QWidget::setVisible(bool visible)
7610 if (visible) { // show
7611 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7616 // Designer uses a trick to make grabWidget work without showing
7617 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7618 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7619 parentWidget()->window()->d_func()->createRecursively();
7621 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7622 //but not children of non-visible parents
7623 QWidget *pw = parentWidget();
7624 if (!testAttribute(Qt::WA_WState_Created)
7625 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7629 #if defined(Q_WS_X11)
7630 if (windowType() == Qt::Window)
7631 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7634 bool wasResized = testAttribute(Qt::WA_Resized);
7635 Qt::WindowStates initialWindowState = windowState();
7637 // polish if necessary
7640 // remember that show was called explicitly
7641 setAttribute(Qt::WA_WState_ExplicitShowHide);
7642 // whether we need to inform the parent widget immediately
7643 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7644 // we are no longer hidden
7645 setAttribute(Qt::WA_WState_Hidden, false);
7647 if (needUpdateGeometry)
7648 d->updateGeometry_helper(true);
7651 QApplication::sendPostedEvents(this, QEvent::ChildInserted);
7653 // activate our layout before we and our children become visible
7655 d->layout->activate();
7658 QWidget *parent = parentWidget();
7659 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7660 parent->d_func()->layout->activate();
7661 if (parent->isWindow())
7663 parent = parent->parentWidget();
7666 parent->d_func()->setDirtyOpaqueRegion();
7669 // adjust size if necessary
7671 && (isWindow() || !parentWidget()->d_func()->layout)) {
7674 if (windowState() != initialWindowState)
7675 setWindowState(initialWindowState);
7679 setAttribute(Qt::WA_Resized, false);
7682 setAttribute(Qt::WA_KeyboardFocusChange, false);
7684 if (isWindow() || parentWidget()->isVisible()) {
7685 // remove posted quit events when showing a new window
7686 QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
7690 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7691 qApp->d_func()->sendSyntheticEnterLeave(this);
7695 QEvent showToParentEvent(QEvent::ShowToParent);
7696 QApplication::sendEvent(this, &showToParentEvent);
7698 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7700 #if defined(Q_WS_WIN)
7701 // reset WS_DISABLED style in a Blocked window
7702 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7703 && QApplicationPrivate::isBlockedByModal(this))
7705 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7706 dwStyle &= ~WS_DISABLED;
7707 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7710 if (QApplicationPrivate::hidden_focus_widget == this)
7711 QApplicationPrivate::hidden_focus_widget = 0;
7715 // hw: The test on getOpaqueRegion() needs to be more intelligent
7716 // currently it doesn't work if the widget is hidden (the region will
7717 // be clipped). The real check should be testing the cached region
7718 // (and dirty flag) directly.
7719 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7720 parentWidget()->d_func()->setDirtyOpaqueRegion();
7722 setAttribute(Qt::WA_WState_Hidden);
7723 setAttribute(Qt::WA_WState_ExplicitShowHide);
7724 if (testAttribute(Qt::WA_WState_Created))
7727 // invalidate layout similar to updateGeometry()
7728 if (!isWindow() && parentWidget()) {
7729 if (parentWidget()->d_func()->layout)
7730 parentWidget()->d_func()->layout->invalidate();
7731 else if (parentWidget()->isVisible())
7732 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7735 QEvent hideToParentEvent(QEvent::HideToParent);
7736 QApplication::sendEvent(this, &hideToParentEvent);
7740 /*!\fn void QWidget::setHidden(bool hidden)
7742 Convenience function, equivalent to setVisible(!\a hidden).
7745 /*!\fn void QWidget::setShown(bool shown)
7747 Use setVisible(\a shown) instead.
7751 void QWidgetPrivate::_q_showIfNotHidden()
7754 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7755 q->setVisible(true);
7758 void QWidgetPrivate::showChildren(bool spontaneous)
7760 QList<QObject*> childList = children;
7761 for (int i = 0; i < childList.size(); ++i) {
7762 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7764 || widget->isWindow()
7765 || widget->testAttribute(Qt::WA_WState_Hidden))
7768 widget->setAttribute(Qt::WA_Mapped);
7769 widget->d_func()->showChildren(true);
7771 QApplication::sendSpontaneousEvent(widget, &e);
7773 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7774 widget->d_func()->show_recursive();
7781 void QWidgetPrivate::hideChildren(bool spontaneous)
7783 QList<QObject*> childList = children;
7784 for (int i = 0; i < childList.size(); ++i) {
7785 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7786 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7788 #ifdef QT_MAC_USE_COCOA
7789 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7790 // When hiding a widget we need to make sure that no mouse_down events are active, because
7791 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7792 // The solution is simple, before going through with this we check if there are any mouse_down events in
7793 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7794 // then we continue.
7795 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7796 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7797 // mouse release event. There are two ways to interpret this:
7798 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7799 // might be waiting for a release event that will never arrive.
7800 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7801 // supposed to trigger because it is not visible.
7802 if(widget == qt_button_down)
7804 #endif // QT_MAC_USE_COCOA
7806 widget->setAttribute(Qt::WA_Mapped, false);
7808 widget->setAttribute(Qt::WA_WState_Visible, false);
7809 widget->d_func()->hideChildren(spontaneous);
7812 QApplication::sendSpontaneousEvent(widget, &e);
7814 QApplication::sendEvent(widget, &e);
7815 if (widget->internalWinId()
7816 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7817 // hide_sys() on an ancestor won't have any affect on this
7818 // widget, so it needs an explicit hide_sys() of its own
7819 widget->d_func()->hide_sys();
7822 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7823 qApp->d_func()->sendSyntheticEnterLeave(widget);
7825 #ifndef QT_NO_ACCESSIBILITY
7827 QAccessible::updateAccessibility(widget, 0, QAccessible::ObjectHide);
7832 bool QWidgetPrivate::close_helper(CloseMode mode)
7834 if (data.is_closing)
7838 data.is_closing = 1;
7840 QPointer<QWidget> that = q;
7841 QPointer<QWidget> parentWidget = q->parentWidget();
7844 bool isMain = (QApplicationPrivate::main_widget == q);
7846 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7847 if (mode != CloseNoEvent) {
7849 if (mode == CloseWithSpontaneousEvent)
7850 QApplication::sendSpontaneousEvent(q, &e);
7852 QApplication::sendEvent(q, &e);
7853 if (!that.isNull() && !e.isAccepted()) {
7854 data.is_closing = 0;
7859 if (!that.isNull() && !q->isHidden())
7864 QApplication::quit();
7866 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7867 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7870 /* if there is no non-withdrawn primary window left (except
7871 the ones without QuitOnClose), we emit the lastWindowClosed
7873 QWidgetList list = QApplication::topLevelWidgets();
7874 bool lastWindowClosed = true;
7875 for (int i = 0; i < list.size(); ++i) {
7876 QWidget *w = list.at(i);
7877 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7879 lastWindowClosed = false;
7882 if (lastWindowClosed)
7883 QApplicationPrivate::emitLastWindowClosed();
7886 if (!that.isNull()) {
7887 data.is_closing = 0;
7888 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7889 q->setAttribute(Qt::WA_DeleteOnClose, false);
7898 Closes this widget. Returns true if the widget was closed;
7899 otherwise returns false.
7901 First it sends the widget a QCloseEvent. The widget is \link
7902 hide() hidden\endlink if it \link QCloseEvent::accept()
7903 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7904 ignores\endlink the event, nothing happens. The default
7905 implementation of QWidget::closeEvent() accepts the close event.
7907 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7908 is also deleted. A close events is delivered to the widget no
7909 matter if the widget is visible or not.
7911 The \l QApplication::lastWindowClosed() signal is emitted when the
7912 last visible primary window (i.e. window with no parent) with the
7913 Qt::WA_QuitOnClose attribute set is closed. By default this
7914 attribute is set for all widgets except transient windows such as
7915 splash screens, tool windows, and popup menus.
7919 bool QWidget::close()
7921 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7925 \property QWidget::visible
7926 \brief whether the widget is visible
7928 Calling setVisible(true) or show() sets the widget to visible
7929 status if all its parent widgets up to the window are visible. If
7930 an ancestor is not visible, the widget won't become visible until
7931 all its ancestors are shown. If its size or position has changed,
7932 Qt guarantees that a widget gets move and resize events just
7933 before it is shown. If the widget has not been resized yet, Qt
7934 will adjust the widget's size to a useful default using
7937 Calling setVisible(false) or hide() hides a widget explicitly. An
7938 explicitly hidden widget will never become visible, even if all
7939 its ancestors become visible, unless you show it.
7941 A widget receives show and hide events when its visibility status
7942 changes. Between a hide and a show event, there is no need to
7943 waste CPU cycles preparing or displaying information to the user.
7944 A video application, for example, might simply stop generating new
7947 A widget that happens to be obscured by other windows on the
7948 screen is considered to be visible. The same applies to iconified
7949 windows and windows that exist on another virtual
7950 desktop (on platforms that support this concept). A widget
7951 receives spontaneous show and hide events when its mapping status
7952 is changed by the window system, e.g. a spontaneous hide event
7953 when the user minimizes the window, and a spontaneous show event
7954 when the window is restored again.
7956 You almost never have to reimplement the setVisible() function. If
7957 you need to change some settings before a widget is shown, use
7958 showEvent() instead. If you need to do some delayed initialization
7959 use the Polish event delivered to the event() function.
7961 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7962 showEvent(), hideEvent()
7967 Returns true if this widget would become visible if \a ancestor is
7968 shown; otherwise returns false.
7970 The true case occurs if neither the widget itself nor any parent
7971 up to but excluding \a ancestor has been explicitly hidden.
7973 This function will still return true if the widget is obscured by
7974 other windows on the screen, but could be physically visible if it
7975 or they were to be moved.
7977 isVisibleTo(0) is identical to isVisible().
7979 \sa show() hide() isVisible()
7982 bool QWidget::isVisibleTo(QWidget* ancestor) const
7986 const QWidget * w = this;
7987 while (!w->isHidden()
7989 && w->parentWidget()
7990 && w->parentWidget() != ancestor)
7991 w = w->parentWidget();
7992 return !w->isHidden();
7997 Use visibleRegion() instead.
7999 QRect QWidget::visibleRect() const
8001 return d_func()->clipRect();
8006 Returns the unobscured region where paint events can occur.
8008 For visible widgets, this is an approximation of the area not
8009 covered by other widgets; otherwise, this is an empty region.
8011 The repaint() function calls this function if necessary, so in
8012 general you do not need to call it.
8015 QRegion QWidget::visibleRegion() const
8019 QRect clipRect = d->clipRect();
8020 if (clipRect.isEmpty())
8022 QRegion r(clipRect);
8023 d->subtractOpaqueChildren(r, clipRect);
8024 d->subtractOpaqueSiblings(r);
8029 QSize QWidgetPrivate::adjustedSize() const
8033 QSize s = q->sizeHint();
8035 if (q->isWindow()) {
8036 Qt::Orientations exp;
8038 if (layout->hasHeightForWidth())
8039 s.setHeight(layout->totalHeightForWidth(s.width()));
8040 exp = layout->expandingDirections();
8043 if (q->sizePolicy().hasHeightForWidth())
8044 s.setHeight(q->heightForWidth(s.width()));
8045 exp = q->sizePolicy().expandingDirections();
8047 if (exp & Qt::Horizontal)
8048 s.setWidth(qMax(s.width(), 200));
8049 if (exp & Qt::Vertical)
8050 s.setHeight(qMax(s.height(), 100));
8051 #if defined(Q_WS_X11)
8052 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
8054 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
8056 #if defined (Q_WS_WINCE) || defined (Q_OS_SYMBIAN)
8057 s.setWidth(qMin(s.width(), screen.width()));
8058 s.setHeight(qMin(s.height(), screen.height()));
8060 s.setWidth(qMin(s.width(), screen.width()*2/3));
8061 s.setHeight(qMin(s.height(), screen.height()*2/3));
8063 if (QTLWExtra *extra = maybeTopData())
8064 extra->sizeAdjusted = true;
8068 QRect r = q->childrenRect(); // get children rectangle
8071 s = r.size() + QSize(2 * r.x(), 2 * r.y());
8078 Adjusts the size of the widget to fit its contents.
8080 This function uses sizeHint() if it is valid, i.e., the size hint's width
8081 and height are \>= 0. Otherwise, it sets the size to the children
8082 rectangle that covers all child widgets (the union of all child widget
8085 For windows, the screen size is also taken into account. If the sizeHint()
8086 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
8087 {expanding}, the window will be at least (200, 100). The maximum size of
8088 a window is 2/3 of the screen's width and height.
8090 \sa sizeHint(), childrenRect()
8093 void QWidget::adjustSize()
8097 QSize s = d->adjustedSize();
8100 d->layout->activate();
8108 \property QWidget::sizeHint
8109 \brief the recommended size for the widget
8111 If the value of this property is an invalid size, no size is
8114 The default implementation of sizeHint() returns an invalid size
8115 if there is no layout for this widget, and returns the layout's
8116 preferred size otherwise.
8118 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
8119 setMinimumSize(), updateGeometry()
8122 QSize QWidget::sizeHint() const
8126 return d->layout->totalSizeHint();
8127 return QSize(-1, -1);
8131 \property QWidget::minimumSizeHint
8132 \brief the recommended minimum size for the widget
8134 If the value of this property is an invalid size, no minimum size
8137 The default implementation of minimumSizeHint() returns an invalid
8138 size if there is no layout for this widget, and returns the
8139 layout's minimum size otherwise. Most built-in widgets reimplement
8142 \l QLayout will never resize a widget to a size smaller than the
8143 minimum size hint unless minimumSize() is set or the size policy is
8144 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
8145 size hint will be ignored.
8147 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
8149 QSize QWidget::minimumSizeHint() const
8153 return d->layout->totalMinimumSize();
8154 return QSize(-1, -1);
8159 \fn QWidget *QWidget::parentWidget() const
8161 Returns the parent of this widget, or 0 if it does not have any
8167 Returns true if this widget is a parent, (or grandparent and so on
8168 to any level), of the given \a child, and both widgets are within
8169 the same window; otherwise returns false.
8172 bool QWidget::isAncestorOf(const QWidget *child) const
8177 if (child->isWindow())
8179 child = child->parentWidget();
8184 #if defined(Q_WS_WIN)
8185 inline void setDisabledStyle(QWidget *w, bool setStyle)
8187 // set/reset WS_DISABLED style.
8188 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
8189 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
8190 LONG newStyle = dwStyle;
8192 newStyle |= WS_DISABLED;
8194 newStyle &= ~WS_DISABLED;
8195 if (newStyle != dwStyle) {
8196 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
8197 // we might need to repaint in some situations (eg. menu)
8204 /*****************************************************************************
8205 QWidget event handling
8206 *****************************************************************************/
8209 This is the main event handler; it handles event \a event. You can
8210 reimplement this function in a subclass, but we recommend using
8211 one of the specialized event handlers instead.
8213 Key press and release events are treated differently from other
8214 events. event() checks for Tab and Shift+Tab and tries to move the
8215 focus appropriately. If there is no widget to move the focus to
8216 (or the key press is not Tab or Shift+Tab), event() calls
8219 Mouse and tablet event handling is also slightly special: only
8220 when the widget is \l enabled, event() will call the specialized
8221 handlers such as mousePressEvent(); otherwise it will discard the
8224 This function returns true if the event was recognized, otherwise
8225 it returns false. If the recognized event was accepted (see \l
8226 QEvent::accepted), any further processing such as event
8227 propagation to the parent widget stops.
8229 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
8230 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
8231 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
8232 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
8233 QObject::event(), QObject::timerEvent()
8236 bool QWidget::event(QEvent *event)
8240 // ignore mouse events when disabled
8242 switch(event->type()) {
8243 case QEvent::TabletPress:
8244 case QEvent::TabletRelease:
8245 case QEvent::TabletMove:
8246 case QEvent::MouseButtonPress:
8247 case QEvent::MouseButtonRelease:
8248 case QEvent::MouseButtonDblClick:
8249 case QEvent::MouseMove:
8250 case QEvent::TouchBegin:
8251 case QEvent::TouchUpdate:
8252 case QEvent::TouchEnd:
8253 case QEvent::ContextMenu:
8254 #ifndef QT_NO_WHEELEVENT
8262 switch (event->type()) {
8263 case QEvent::MouseMove:
8264 mouseMoveEvent((QMouseEvent*)event);
8267 case QEvent::MouseButtonPress:
8268 // Don't reset input context here. Whether reset or not is
8269 // a responsibility of input method. reset() will be
8270 // called by mouseHandler() of input method if necessary
8271 // via mousePressEvent() of text widgets.
8273 resetInputContext();
8275 mousePressEvent((QMouseEvent*)event);
8278 case QEvent::MouseButtonRelease:
8279 mouseReleaseEvent((QMouseEvent*)event);
8282 case QEvent::MouseButtonDblClick:
8283 mouseDoubleClickEvent((QMouseEvent*)event);
8285 #ifndef QT_NO_WHEELEVENT
8287 wheelEvent((QWheelEvent*)event);
8290 #ifndef QT_NO_TABLETEVENT
8291 case QEvent::TabletMove:
8292 case QEvent::TabletPress:
8293 case QEvent::TabletRelease:
8294 tabletEvent((QTabletEvent*)event);
8302 case QEvent::KeyPress: {
8303 QKeyEvent *k = (QKeyEvent *)event;
8305 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
8306 if (k->key() == Qt::Key_Backtab
8307 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
8308 res = focusNextPrevChild(false);
8309 else if (k->key() == Qt::Key_Tab)
8310 res = focusNextPrevChild(true);
8315 #ifdef QT_KEYPAD_NAVIGATION
8316 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
8317 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
8318 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
8319 if (k->key() == Qt::Key_Up)
8320 res = focusNextPrevChild(false);
8321 else if (k->key() == Qt::Key_Down)
8322 res = focusNextPrevChild(true);
8323 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
8324 if (k->key() == Qt::Key_Up)
8325 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
8326 else if (k->key() == Qt::Key_Right)
8327 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
8328 else if (k->key() == Qt::Key_Down)
8329 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
8330 else if (k->key() == Qt::Key_Left)
8331 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
8339 #ifndef QT_NO_WHATSTHIS
8340 if (!k->isAccepted()
8341 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
8342 && d->whatsThis.size()) {
8343 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
8350 case QEvent::KeyRelease:
8351 keyReleaseEvent((QKeyEvent*)event);
8353 case QEvent::ShortcutOverride:
8356 case QEvent::InputMethod:
8357 inputMethodEvent((QInputMethodEvent *) event);
8360 case QEvent::InputMethodQuery:
8361 if (testAttribute(Qt::WA_InputMethodEnabled)) {
8362 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
8363 Qt::InputMethodQueries queries = query->queries();
8364 for (uint i = 0; i < 32; ++i) {
8365 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
8367 QVariant v = inputMethodQuery(q);
8368 query->setValue(q, v);
8375 case QEvent::PolishRequest:
8379 case QEvent::Polish: {
8380 style()->polish(this);
8381 setAttribute(Qt::WA_WState_Polished);
8382 if (!QApplication::font(this).isCopyOf(QApplication::font()))
8384 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
8385 d->resolvePalette();
8387 if(d->sendChildEvents)
8388 QApplication::sendPostedEvents(this, QEvent::ChildInserted);
8393 case QEvent::ApplicationWindowIconChange:
8394 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
8395 d->setWindowIcon_sys();
8396 d->setWindowIcon_helper();
8399 case QEvent::FocusIn:
8400 #ifdef QT_SOFTKEYS_ENABLED
8401 QSoftKeyManager::updateSoftKeys();
8403 focusInEvent((QFocusEvent*)event);
8404 d->updateWidgetTransform();
8407 case QEvent::FocusOut:
8408 focusOutEvent((QFocusEvent*)event);
8412 #ifndef QT_NO_STATUSTIP
8413 if (d->statusTip.size()) {
8414 QStatusTipEvent tip(d->statusTip);
8415 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8422 #ifndef QT_NO_STATUSTIP
8423 if (d->statusTip.size()) {
8425 QStatusTipEvent tip(empty);
8426 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8432 case QEvent::HoverEnter:
8433 case QEvent::HoverLeave:
8438 // At this point the event has to be delivered, regardless
8439 // whether the widget isVisible() or not because it
8440 // already went through the filters
8441 paintEvent((QPaintEvent*)event);
8445 moveEvent((QMoveEvent*)event);
8446 d->updateWidgetTransform();
8449 case QEvent::Resize:
8450 resizeEvent((QResizeEvent*)event);
8451 d->updateWidgetTransform();
8455 closeEvent((QCloseEvent *)event);
8458 #ifndef QT_NO_CONTEXTMENU
8459 case QEvent::ContextMenu:
8460 switch (data->context_menu_policy) {
8461 case Qt::PreventContextMenu:
8463 case Qt::DefaultContextMenu:
8464 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8466 case Qt::CustomContextMenu:
8467 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8470 case Qt::ActionsContextMenu:
8471 if (d->actions.count()) {
8472 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8483 #endif // QT_NO_CONTEXTMENU
8485 #ifndef QT_NO_DRAGANDDROP
8487 dropEvent((QDropEvent*) event);
8490 case QEvent::DragEnter:
8491 dragEnterEvent((QDragEnterEvent*) event);
8494 case QEvent::DragMove:
8495 dragMoveEvent((QDragMoveEvent*) event);
8498 case QEvent::DragLeave:
8499 dragLeaveEvent((QDragLeaveEvent*) event);
8504 showEvent((QShowEvent*) event);
8508 hideEvent((QHideEvent*) event);
8511 case QEvent::ShowWindowRequest:
8516 case QEvent::ApplicationFontChange:
8519 case QEvent::ApplicationPaletteChange:
8520 if (!(windowType() == Qt::Desktop))
8521 d->resolvePalette();
8524 case QEvent::ToolBarChange:
8525 case QEvent::ActivationChange:
8526 case QEvent::EnabledChange:
8527 case QEvent::FontChange:
8528 case QEvent::StyleChange:
8529 case QEvent::PaletteChange:
8530 case QEvent::WindowTitleChange:
8531 case QEvent::IconTextChange:
8532 case QEvent::ModifiedChange:
8533 case QEvent::MouseTrackingChange:
8534 case QEvent::ParentChange:
8535 case QEvent::WindowStateChange:
8536 case QEvent::LocaleChange:
8537 case QEvent::MacSizeChange:
8538 case QEvent::ContentsRectChange:
8542 case QEvent::WindowActivate:
8543 case QEvent::WindowDeactivate: {
8545 windowActivationChange(event->type() != QEvent::WindowActivate);
8547 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8549 QList<QObject*> childList = d->children;
8550 for (int i = 0; i < childList.size(); ++i) {
8551 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8552 if (w && w->isVisible() && !w->isWindow())
8553 QApplication::sendEvent(w, event);
8556 #ifdef QT_SOFTKEYS_ENABLED
8558 QSoftKeyManager::updateSoftKeys();
8563 case QEvent::LanguageChange:
8569 QList<QObject*> childList = d->children;
8570 for (int i = 0; i < childList.size(); ++i) {
8571 QObject *o = childList.at(i);
8573 QApplication::sendEvent(o, event);
8579 case QEvent::ApplicationLayoutDirectionChange:
8580 d->resolveLayoutDirection();
8583 case QEvent::LayoutDirectionChange:
8585 d->layout->invalidate();
8589 case QEvent::UpdateRequest:
8590 d->syncBackingStore();
8592 case QEvent::UpdateLater:
8593 update(static_cast<QUpdateLaterEvent*>(event)->region());
8596 case QEvent::WindowBlocked:
8597 case QEvent::WindowUnblocked:
8599 QList<QObject*> childList = d->children;
8600 for (int i = 0; i < childList.size(); ++i) {
8601 QObject *o = childList.at(i);
8602 if (o && o != QApplication::activeModalWidget()) {
8603 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8604 // do not forward the event to child windows,
8605 // QApplication does this for us
8608 QApplication::sendEvent(o, event);
8611 #if defined(Q_WS_WIN)
8612 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8616 #ifndef QT_NO_TOOLTIP
8617 case QEvent::ToolTip:
8618 if (!d->toolTip.isEmpty())
8619 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8624 #ifndef QT_NO_WHATSTHIS
8625 case QEvent::WhatsThis:
8626 if (d->whatsThis.size())
8627 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8631 case QEvent::QueryWhatsThis:
8632 if (d->whatsThis.isEmpty())
8636 #ifndef QT_NO_ACCESSIBILITY
8637 case QEvent::AccessibilityDescription:
8638 case QEvent::AccessibilityHelp: {
8639 QAccessibleEvent *ev = static_cast<QAccessibleEvent *>(event);
8642 switch (ev->type()) {
8643 #ifndef QT_NO_TOOLTIP
8644 case QEvent::AccessibilityDescription:
8645 ev->setValue(d->toolTip);
8648 #ifndef QT_NO_WHATSTHIS
8649 case QEvent::AccessibilityHelp:
8650 ev->setValue(d->whatsThis);
8658 case QEvent::EmbeddingControl:
8659 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8660 data->fstrut_dirty = false;
8661 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8662 d->topData()->embedded = 1;
8665 #ifndef QT_NO_ACTION
8666 case QEvent::ActionAdded:
8667 case QEvent::ActionRemoved:
8668 case QEvent::ActionChanged:
8669 #ifdef QT_SOFTKEYS_ENABLED
8670 QSoftKeyManager::updateSoftKeys();
8672 actionEvent((QActionEvent*)event);
8676 case QEvent::KeyboardLayoutChange:
8680 // inform children of the change
8681 QList<QObject*> childList = d->children;
8682 for (int i = 0; i < childList.size(); ++i) {
8683 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8684 if (w && w->isVisible() && !w->isWindow())
8685 QApplication::sendEvent(w, event);
8690 case QEvent::MacGLWindowChange:
8691 d->needWindowChange = false;
8694 case QEvent::TouchBegin:
8695 case QEvent::TouchUpdate:
8696 case QEvent::TouchEnd:
8699 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
8700 const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().first();
8701 if (touchPoint.isPrimary() || touchEvent->deviceType() == QTouchEvent::TouchPad)
8704 // fake a mouse event!
8705 QEvent::Type eventType = QEvent::None;
8706 switch (touchEvent->type()) {
8707 case QEvent::TouchBegin:
8708 eventType = QEvent::MouseButtonPress;
8710 case QEvent::TouchUpdate:
8711 eventType = QEvent::MouseMove;
8713 case QEvent::TouchEnd:
8714 eventType = QEvent::MouseButtonRelease;
8720 if (eventType == QEvent::None)
8723 QMouseEvent mouseEvent(eventType,
8725 touchPoint.scenePos(),
8726 touchPoint.screenPos(),
8729 touchEvent->modifiers());
8730 (void) QApplication::sendEvent(this, &mouseEvent);
8734 #ifndef QT_NO_GESTURES
8735 case QEvent::Gesture:
8739 #ifndef QT_NO_PROPERTIES
8740 case QEvent::DynamicPropertyChange: {
8741 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8742 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8743 uint value = property(propName.constData()).toUInt();
8746 const char axis = propName.at(12);
8748 d->extra->customDpiX = value;
8749 else if (axis == 'Y')
8750 d->extra->customDpiY = value;
8751 d->updateFont(d->data.fnt);
8757 return QObject::event(event);
8763 This event handler can be reimplemented to handle state changes.
8765 The state being changed in this event can be retrieved through the \a event
8768 Change events include: QEvent::ToolBarChange,
8769 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8770 QEvent::StyleChange, QEvent::PaletteChange,
8771 QEvent::WindowTitleChange, QEvent::IconTextChange,
8772 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8773 QEvent::ParentChange, QEvent::WindowStateChange,
8774 QEvent::LanguageChange, QEvent::LocaleChange,
8775 QEvent::LayoutDirectionChange.
8778 void QWidget::changeEvent(QEvent * event)
8780 switch(event->type()) {
8781 case QEvent::EnabledChange:
8783 #ifndef QT_NO_ACCESSIBILITY
8784 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
8788 case QEvent::FontChange:
8789 case QEvent::StyleChange: {
8794 d->layout->invalidate();
8798 case QEvent::PaletteChange:
8803 case QEvent::MacSizeChange:
8806 case QEvent::ToolTipChange:
8807 case QEvent::MouseTrackingChange:
8808 qt_mac_update_mouseTracking(this);
8818 This event handler, for event \a event, can be reimplemented in a
8819 subclass to receive mouse move events for the widget.
8821 If mouse tracking is switched off, mouse move events only occur if
8822 a mouse button is pressed while the mouse is being moved. If mouse
8823 tracking is switched on, mouse move events occur even if no mouse
8826 QMouseEvent::pos() reports the position of the mouse cursor,
8827 relative to this widget. For press and release events, the
8828 position is usually the same as the position of the last mouse
8829 move event, but it might be different if the user's hand shakes.
8830 This is a feature of the underlying window system, not Qt.
8832 If you want to show a tooltip immediately, while the mouse is
8833 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8834 and show them as a tooltip), you must first enable mouse tracking
8835 as described above. Then, to ensure that the tooltip is updated
8836 immediately, you must call QToolTip::showText() instead of
8837 setToolTip() in your implementation of mouseMoveEvent().
8839 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8840 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8843 void QWidget::mouseMoveEvent(QMouseEvent *event)
8849 This event handler, for event \a event, can be reimplemented in a
8850 subclass to receive mouse press events for the widget.
8852 If you create new widgets in the mousePressEvent() the
8853 mouseReleaseEvent() may not end up where you expect, depending on
8854 the underlying window system (or X11 window manager), the widgets'
8855 location and maybe more.
8857 The default implementation implements the closing of popup widgets
8858 when you click outside the window. For other widget types it does
8861 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8862 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8865 void QWidget::mousePressEvent(QMouseEvent *event)
8868 if ((windowType() == Qt::Popup)) {
8871 while ((w = QApplication::activePopupWidget()) && w != this){
8873 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8874 w->hide(); // hide at least
8876 if (!rect().contains(event->pos())){
8883 This event handler, for event \a event, can be reimplemented in a
8884 subclass to receive mouse release events for the widget.
8886 \sa mousePressEvent(), mouseDoubleClickEvent(),
8887 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8890 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8896 This event handler, for event \a event, can be reimplemented in a
8897 subclass to receive mouse double click events for the widget.
8899 The default implementation generates a normal mouse press event.
8901 \note The widget will also receive mouse press and mouse release
8902 events in addition to the double click event. It is up to the
8903 developer to ensure that the application interprets these events
8906 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8907 event(), QMouseEvent
8910 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8912 mousePressEvent(event); // try mouse press event
8915 #ifndef QT_NO_WHEELEVENT
8917 This event handler, for event \a event, can be reimplemented in a
8918 subclass to receive wheel events for the widget.
8920 If you reimplement this handler, it is very important that you
8921 \link QWheelEvent ignore()\endlink the event if you do not handle
8922 it, so that the widget's parent can interpret it.
8924 The default implementation ignores the event.
8926 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8930 void QWidget::wheelEvent(QWheelEvent *event)
8934 #endif // QT_NO_WHEELEVENT
8936 #ifndef QT_NO_TABLETEVENT
8938 This event handler, for event \a event, can be reimplemented in a
8939 subclass to receive tablet events for the widget.
8941 If you reimplement this handler, it is very important that you
8942 \link QTabletEvent ignore()\endlink the event if you do not handle
8943 it, so that the widget's parent can interpret it.
8945 The default implementation ignores the event.
8947 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8951 void QWidget::tabletEvent(QTabletEvent *event)
8955 #endif // QT_NO_TABLETEVENT
8958 This event handler, for event \a event, can be reimplemented in a
8959 subclass to receive key press events for the widget.
8961 A widget must call setFocusPolicy() to accept focus initially and
8962 have focus in order to receive a key press event.
8964 If you reimplement this handler, it is very important that you
8965 call the base class implementation if you do not act upon the key.
8967 The default implementation closes popup widgets if the user
8968 presses Esc. Otherwise the event is ignored, so that the widget's
8969 parent can interpret it.
8971 Note that QKeyEvent starts with isAccepted() == true, so you do not
8972 need to call QKeyEvent::accept() - just do not call the base class
8973 implementation if you act upon the key.
8975 \sa keyReleaseEvent(), setFocusPolicy(),
8976 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8979 void QWidget::keyPressEvent(QKeyEvent *event)
8981 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8990 This event handler, for event \a event, can be reimplemented in a
8991 subclass to receive key release events for the widget.
8993 A widget must \link setFocusPolicy() accept focus\endlink
8994 initially and \link hasFocus() have focus\endlink in order to
8995 receive a key release event.
8997 If you reimplement this handler, it is very important that you
8998 call the base class implementation if you do not act upon the key.
9000 The default implementation ignores the event, so that the widget's
9001 parent can interpret it.
9003 Note that QKeyEvent starts with isAccepted() == true, so you do not
9004 need to call QKeyEvent::accept() - just do not call the base class
9005 implementation if you act upon the key.
9007 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
9008 focusInEvent(), focusOutEvent(), event(), QKeyEvent
9011 void QWidget::keyReleaseEvent(QKeyEvent *event)
9017 \fn void QWidget::focusInEvent(QFocusEvent *event)
9019 This event handler can be reimplemented in a subclass to receive
9020 keyboard focus events (focus received) for the widget. The event
9021 is passed in the \a event parameter
9023 A widget normally must setFocusPolicy() to something other than
9024 Qt::NoFocus in order to receive focus events. (Note that the
9025 application programmer can call setFocus() on any widget, even
9026 those that do not normally accept focus.)
9028 The default implementation updates the widget (except for windows
9029 that do not specify a focusPolicy()).
9031 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
9032 keyReleaseEvent(), event(), QFocusEvent
9035 void QWidget::focusInEvent(QFocusEvent *)
9037 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
9043 \fn void QWidget::focusOutEvent(QFocusEvent *event)
9045 This event handler can be reimplemented in a subclass to receive
9046 keyboard focus events (focus lost) for the widget. The events is
9047 passed in the \a event parameter.
9049 A widget normally must setFocusPolicy() to something other than
9050 Qt::NoFocus in order to receive focus events. (Note that the
9051 application programmer can call setFocus() on any widget, even
9052 those that do not normally accept focus.)
9054 The default implementation updates the widget (except for windows
9055 that do not specify a focusPolicy()).
9057 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
9058 keyReleaseEvent(), event(), QFocusEvent
9061 void QWidget::focusOutEvent(QFocusEvent *)
9063 if (focusPolicy() != Qt::NoFocus || !isWindow())
9068 \fn void QWidget::enterEvent(QEvent *event)
9070 This event handler can be reimplemented in a subclass to receive
9071 widget enter events which are passed in the \a event parameter.
9073 An event is sent to the widget when the mouse cursor enters the
9076 \sa leaveEvent(), mouseMoveEvent(), event()
9079 void QWidget::enterEvent(QEvent *)
9084 \fn void QWidget::leaveEvent(QEvent *event)
9086 This event handler can be reimplemented in a subclass to receive
9087 widget leave events which are passed in the \a event parameter.
9089 A leave event is sent to the widget when the mouse cursor leaves
9092 \sa enterEvent(), mouseMoveEvent(), event()
9095 void QWidget::leaveEvent(QEvent *)
9100 \fn void QWidget::paintEvent(QPaintEvent *event)
9102 This event handler can be reimplemented in a subclass to receive paint
9103 events passed in \a event.
9105 A paint event is a request to repaint all or part of a widget. It can
9106 happen for one of the following reasons:
9109 \o repaint() or update() was invoked,
9110 \o the widget was obscured and has now been uncovered, or
9111 \o many other reasons.
9114 Many widgets can simply repaint their entire surface when asked to, but
9115 some slow widgets need to optimize by painting only the requested region:
9116 QPaintEvent::region(). This speed optimization does not change the result,
9117 as painting is clipped to that region during event processing. QListView
9118 and QTableView do this, for example.
9120 Qt also tries to speed up painting by merging multiple paint events into
9121 one. When update() is called several times or the window system sends
9122 several paint events, Qt merges these events into one event with a larger
9123 region (see QRegion::united()). The repaint() function does not permit this
9124 optimization, so we suggest using update() whenever possible.
9126 When the paint event occurs, the update region has normally been erased, so
9127 you are painting on the widget's background.
9129 The background can be set using setBackgroundRole() and setPalette().
9131 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
9132 is no need to write double-buffering code in paintEvent() to avoid flicker.
9134 \bold{Note for the X11 platform}: It is possible to toggle global double
9135 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
9137 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
9139 \note Generally, you should refrain from calling update() or repaint()
9140 \bold{inside} a paintEvent(). For example, calling update() or repaint() on
9141 children inside a paintevent() results in undefined behavior; the child may
9142 or may not get a paint event.
9144 \warning If you are using a custom paint engine without Qt's backingstore,
9145 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
9146 never be called; the backingstore will be used instead.
9148 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
9149 {Analog Clock Example}
9152 void QWidget::paintEvent(QPaintEvent *)
9158 \fn void QWidget::moveEvent(QMoveEvent *event)
9160 This event handler can be reimplemented in a subclass to receive
9161 widget move events which are passed in the \a event parameter.
9162 When the widget receives this event, it is already at the new
9165 The old position is accessible through QMoveEvent::oldPos().
9167 \sa resizeEvent(), event(), move(), QMoveEvent
9170 void QWidget::moveEvent(QMoveEvent *)
9176 This event handler can be reimplemented in a subclass to receive
9177 widget resize events which are passed in the \a event parameter.
9178 When resizeEvent() is called, the widget already has its new
9179 geometry. The old size is accessible through
9180 QResizeEvent::oldSize().
9182 The widget will be erased and receive a paint event immediately
9183 after processing the resize event. No drawing need be (or should
9184 be) done inside this handler.
9187 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
9191 void QWidget::resizeEvent(QResizeEvent * /* event */)
9195 #ifndef QT_NO_ACTION
9197 \fn void QWidget::actionEvent(QActionEvent *event)
9199 This event handler is called with the given \a event whenever the
9200 widget's actions are changed.
9202 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
9204 void QWidget::actionEvent(QActionEvent *)
9211 This event handler is called with the given \a event when Qt receives a window
9212 close request for a top-level widget from the window system.
9214 By default, the event is accepted and the widget is closed. You can reimplement
9215 this function to change the way the widget responds to window close requests.
9216 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
9219 Main window applications typically use reimplementations of this function to check
9220 whether the user's work has been saved and ask for permission before closing.
9221 For example, the \l{Application Example} uses a helper function to determine whether
9222 or not to close the window:
9224 \snippet mainwindows/application/mainwindow.cpp 3
9225 \snippet mainwindows/application/mainwindow.cpp 4
9227 \sa event(), hide(), close(), QCloseEvent, {Application Example}
9230 void QWidget::closeEvent(QCloseEvent *event)
9235 #ifndef QT_NO_CONTEXTMENU
9237 This event handler, for event \a event, can be reimplemented in a
9238 subclass to receive widget context menu events.
9240 The handler is called when the widget's \l contextMenuPolicy is
9241 Qt::DefaultContextMenu.
9243 The default implementation ignores the context event.
9244 See the \l QContextMenuEvent documentation for more details.
9246 \sa event(), QContextMenuEvent customContextMenuRequested()
9249 void QWidget::contextMenuEvent(QContextMenuEvent *event)
9253 #endif // QT_NO_CONTEXTMENU
9257 This event handler, for event \a event, can be reimplemented in a
9258 subclass to receive Input Method composition events. This handler
9259 is called when the state of the input method changes.
9261 Note that when creating custom text editing widgets, the
9262 Qt::WA_InputMethodEnabled window attribute must be set explicitly
9263 (using the setAttribute() function) in order to receive input
9266 The default implementation calls event->ignore(), which rejects the
9267 Input Method event. See the \l QInputMethodEvent documentation for more
9270 \sa event(), QInputMethodEvent
9272 void QWidget::inputMethodEvent(QInputMethodEvent *event)
9278 This method is only relevant for input widgets. It is used by the
9279 input method to query a set of properties of the widget to be
9280 able to support complex input method operations as support for
9281 surrounding text and reconversions.
9283 \a query specifies which property is queried.
9285 \sa inputMethodEvent(), QInputMethodEvent, QInputContext, inputMethodHints
9287 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
9290 case Qt::ImCursorRectangle:
9291 return QRect(width()/2, 0, 1, height());
9294 case Qt::ImAnchorPosition:
9296 return inputMethodQuery(Qt::ImCursorPosition);
9298 return (int)inputMethodHints();
9305 \property QWidget::inputMethodHints
9306 \brief What input method specific hints the widget has.
9308 This is only relevant for input widgets. It is used by
9309 the input method to retrieve hints as to how the input method
9310 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
9311 is set, the input method may change its visual components to reflect
9312 that only numbers can be entered.
9314 \note The flags are only hints, so the particular input method
9315 implementation is free to ignore them. If you want to be
9316 sure that a certain type of characters are entered,
9317 you should also set a QValidator on the widget.
9319 The default value is Qt::ImhNone.
9323 \sa inputMethodQuery(), QInputContext
9325 Qt::InputMethodHints QWidget::inputMethodHints() const
9328 const QWidgetPrivate *priv = d_func();
9329 while (priv->inheritsInputMethodHints) {
9330 priv = priv->q_func()->parentWidget()->d_func();
9333 return priv->imHints;
9339 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
9344 // Optimization to update input context only it has already been created.
9345 if (d->ic || qApp->d_func()->inputContext) {
9346 QInputContext *ic = inputContext();
9354 #ifndef QT_NO_DRAGANDDROP
9357 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
9359 This event handler is called when a drag is in progress and the
9360 mouse enters this widget. The event is passed in the \a event parameter.
9362 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
9365 See the \link dnd.html Drag-and-drop documentation\endlink for an
9366 overview of how to provide drag-and-drop in your application.
9368 \sa QDrag, QDragEnterEvent
9370 void QWidget::dragEnterEvent(QDragEnterEvent *)
9375 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
9377 This event handler is called if a drag is in progress, and when
9378 any of the following conditions occur: the cursor enters this widget,
9379 the cursor moves within this widget, or a modifier key is pressed on
9380 the keyboard while this widget has the focus. The event is passed
9381 in the \a event parameter.
9383 See the \link dnd.html Drag-and-drop documentation\endlink for an
9384 overview of how to provide drag-and-drop in your application.
9386 \sa QDrag, QDragMoveEvent
9388 void QWidget::dragMoveEvent(QDragMoveEvent *)
9393 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
9395 This event handler is called when a drag is in progress and the
9396 mouse leaves this widget. The event is passed in the \a event
9399 See the \link dnd.html Drag-and-drop documentation\endlink for an
9400 overview of how to provide drag-and-drop in your application.
9402 \sa QDrag, QDragLeaveEvent
9404 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
9409 \fn void QWidget::dropEvent(QDropEvent *event)
9411 This event handler is called when the drag is dropped on this
9412 widget. The event is passed in the \a event parameter.
9414 See the \link dnd.html Drag-and-drop documentation\endlink for an
9415 overview of how to provide drag-and-drop in your application.
9417 \sa QDrag, QDropEvent
9419 void QWidget::dropEvent(QDropEvent *)
9423 #endif // QT_NO_DRAGANDDROP
9426 \fn void QWidget::showEvent(QShowEvent *event)
9428 This event handler can be reimplemented in a subclass to receive
9429 widget show events which are passed in the \a event parameter.
9431 Non-spontaneous show events are sent to widgets immediately
9432 before they are shown. The spontaneous show events of windows are
9433 delivered afterwards.
9435 Note: A widget receives spontaneous show and hide events when its
9436 mapping status is changed by the window system, e.g. a spontaneous
9437 hide event when the user minimizes the window, and a spontaneous
9438 show event when the window is restored again. After receiving a
9439 spontaneous hide event, a widget is still considered visible in
9440 the sense of isVisible().
9442 \sa visible, event(), QShowEvent
9444 void QWidget::showEvent(QShowEvent *)
9449 \fn void QWidget::hideEvent(QHideEvent *event)
9451 This event handler can be reimplemented in a subclass to receive
9452 widget hide events. The event is passed in the \a event parameter.
9454 Hide events are sent to widgets immediately after they have been
9457 Note: A widget receives spontaneous show and hide events when its
9458 mapping status is changed by the window system, e.g. a spontaneous
9459 hide event when the user minimizes the window, and a spontaneous
9460 show event when the window is restored again. After receiving a
9461 spontaneous hide event, a widget is still considered visible in
9462 the sense of isVisible().
9464 \sa visible, event(), QHideEvent
9466 void QWidget::hideEvent(QHideEvent *)
9471 \fn QWidget::x11Event(MSG *)
9473 This special event handler can be reimplemented in a subclass to receive
9476 In your reimplementation of this function, if you want to stop Qt from
9477 handling the event, return true. If you return false, this native event
9478 is passed back to Qt, which translates it into a Qt event and sends it to
9481 \note Events are only delivered to this event handler if the widget is
9484 \warning This function is not portable.
9486 \sa QApplication::x11EventFilter(), QWidget::winId()
9490 #if defined(Q_WS_MAC)
9493 \fn bool QWidget::macEvent(EventHandlerCallRef caller, EventRef event)
9495 This special event handler can be reimplemented in a subclass to
9496 receive native Macintosh events.
9498 The parameters are a bit different depending if Qt is build against Carbon
9499 or Cocoa. In Carbon, \a caller and \a event are the corresponding
9500 EventHandlerCallRef and EventRef that correspond to the Carbon event
9501 handlers that are installed. In Cocoa, \a caller is always 0 and the
9502 EventRef is the EventRef generated from the NSEvent.
9504 In your reimplementation of this function, if you want to stop the
9505 event being handled by Qt, return true. If you return false, this
9506 native event is passed back to Qt, which translates the event into
9507 a Qt event and sends it to the widget.
9509 \warning This function is not portable.
9511 \warning This function was not called inside of Qt until Qt 4.4.
9512 If you need compatibility with earlier versions of Qt, consider QApplication::macEventFilter() instead.
9514 \sa QApplication::macEventFilter()
9517 bool QWidget::macEvent(EventHandlerCallRef, EventRef)
9523 #if defined(Q_WS_WIN)
9526 This special event handler can be reimplemented in a subclass to
9527 receive native Windows events which are passed in the \a message
9530 In your reimplementation of this function, if you want to stop the
9531 event being handled by Qt, return true and set \a result to the value
9532 that the window procedure should return. If you return false, this
9533 native event is passed back to Qt, which translates the event into
9534 a Qt event and sends it to the widget.
9536 \warning This function is not portable.
9538 \sa QApplication::winEventFilter()
9540 bool QWidget::winEvent(MSG *message, long *result)
9548 #if defined(Q_WS_X11)
9551 \fn bool QWidget::x11Event(XEvent *event)
9553 This special event handler can be reimplemented in a subclass to receive
9554 native X11 events passed in the \a event parameter.
9556 In your reimplementation of this function, if you want to stop Qt from
9557 handling the event, return true. If you return false, this native event
9558 is passed back to Qt, which translates it into a Qt event and sends it to
9561 \note Events are only delivered to this event handler if the widget is
9564 \warning This function is not portable.
9566 \sa QApplication::x11EventFilter(), QWidget::winId()
9568 bool QWidget::x11Event(XEvent *)
9576 Ensures that the widget has been polished by QStyle (i.e., has a
9577 proper font and palette).
9579 QWidget calls this function after it has been fully constructed
9580 but before it is shown the very first time. You can call this
9581 function if you want to ensure that the widget is polished before
9582 doing an operation, e.g., the correct font size might be needed in
9583 the widget's sizeHint() reimplementation. Note that this function
9584 \e is called from the default implementation of sizeHint().
9586 Polishing is useful for final initialization that must happen after
9587 all constructors (from base classes as well as from subclasses)
9590 If you need to change some settings when a widget is polished,
9591 reimplement event() and handle the QEvent::Polish event type.
9593 \bold{Note:} The function is declared const so that it can be called from
9594 other const functions (e.g., sizeHint()).
9598 void QWidget::ensurePolished() const
9602 const QMetaObject *m = metaObject();
9603 if (m == d->polished)
9607 QEvent e(QEvent::Polish);
9608 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9610 // polish children after 'this'
9611 QList<QObject*> children = d->children;
9612 for (int i = 0; i < children.size(); ++i) {
9613 QObject *o = children.at(i);
9614 if(!o->isWidgetType())
9616 if (QWidget *w = qobject_cast<QWidget *>(o))
9617 w->ensurePolished();
9620 if (d->parent && d->sendChildEvents) {
9621 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9622 QCoreApplication::sendEvent(d->parent, &e);
9625 if (d->extra && d->extra->topextra && d->extra->topextra->window
9626 && d->extra->topextra->window->objectName().isEmpty()) {
9627 QString on = objectName();
9629 on = QString::fromUtf8(metaObject()->className());
9630 on += QLatin1String("Class");
9632 on += QLatin1String("Window");
9633 d->extra->topextra->window->setObjectName(on);
9639 Returns the mask currently set on a widget. If no mask is set the
9640 return value will be an empty region.
9642 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9644 QRegion QWidget::mask() const
9647 return d->extra ? d->extra->mask : QRegion();
9651 Returns the layout manager that is installed on this widget, or 0
9652 if no layout manager is installed.
9654 The layout manager sets the geometry of the widget's children
9655 that have been added to the layout.
9657 \sa setLayout(), sizePolicy(), {Layout Management}
9659 QLayout *QWidget::layout() const
9661 return d_func()->layout;
9666 \fn void QWidget::setLayout(QLayout *layout)
9668 Sets the layout manager for this widget to \a layout.
9670 If there already is a layout manager installed on this widget,
9671 QWidget won't let you install another. You must first delete the
9672 existing layout manager (returned by layout()) before you can
9673 call setLayout() with the new layout.
9675 If \a layout is the layout manger on a different widget, setLayout()
9676 will reparent the layout and make it the layout manager for this widget.
9680 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9682 An alternative to calling this function is to pass this widget to
9683 the layout's constructor.
9685 The QWidget will take ownership of \a layout.
9687 \sa layout(), {Layout Management}
9690 void QWidget::setLayout(QLayout *l)
9693 qWarning("QWidget::setLayout: Cannot set layout to 0");
9698 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9699 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9700 objectName().toLocal8Bit().data());
9704 QObject *oldParent = l->parent();
9705 if (oldParent && oldParent != this) {
9706 if (oldParent->isWidgetType()) {
9707 // Steal the layout off a widget parent. Takes effect when
9708 // morphing laid-out container widgets in Designer.
9709 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9710 oldParentWidget->takeLayout();
9712 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9713 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9714 objectName().toLocal8Bit().data());
9720 l->d_func()->topLevel = true;
9722 if (oldParent != this) {
9724 l->d_func()->reparentChildWidgets(this);
9728 if (isWindow() && d->maybeTopData())
9729 d->topData()->sizeAdjusted = false;
9733 \fn QLayout *QWidget::takeLayout()
9735 Remove the layout from the widget.
9739 QLayout *QWidget::takeLayout()
9742 QLayout *l = layout();
9751 \property QWidget::sizePolicy
9752 \brief the default layout behavior of the widget
9754 If there is a QLayout that manages this widget's children, the
9755 size policy specified by that layout is used. If there is no such
9756 QLayout, the result of this function is used.
9758 The default policy is Preferred/Preferred, which means that the
9759 widget can be freely resized, but prefers to be the size
9760 sizeHint() returns. Button-like widgets set the size policy to
9761 specify that they may stretch horizontally, but are fixed
9762 vertically. The same applies to lineedit controls (such as
9763 QLineEdit, QSpinBox or an editable QComboBox) and other
9764 horizontally orientated widgets (such as QProgressBar).
9765 QToolButton's are normally square, so they allow growth in both
9766 directions. Widgets that support different directions (such as
9767 QSlider, QScrollBar or QHeader) specify stretching in the
9768 respective direction only. Widgets that can provide scroll bars
9769 (usually subclasses of QScrollArea) tend to specify that they can
9770 use additional space, and that they can make do with less than
9773 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9775 QSizePolicy QWidget::sizePolicy() const
9778 return d->size_policy;
9781 void QWidget::setSizePolicy(QSizePolicy policy)
9784 setAttribute(Qt::WA_WState_OwnSizePolicy);
9785 if (policy == d->size_policy)
9787 d->size_policy = policy;
9789 #ifndef QT_NO_GRAPHICSVIEW
9790 if (QWExtra *extra = d->extra) {
9791 if (extra->proxyWidget)
9792 extra->proxyWidget->setSizePolicy(policy);
9798 if (isWindow() && d->maybeTopData())
9799 d->topData()->sizeAdjusted = false;
9803 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9806 Sets the size policy of the widget to \a horizontal and \a
9807 vertical, with standard stretch and no height-for-width.
9809 \sa QSizePolicy::QSizePolicy()
9813 Returns the preferred height for this widget, given the width \a w.
9815 If this widget has a layout, the default implementation returns
9816 the layout's preferred height. if there is no layout, the default
9817 implementation returns -1 indicating that the preferred height
9818 does not depend on the width.
9821 int QWidget::heightForWidth(int w) const
9823 if (layout() && layout()->hasHeightForWidth())
9824 return layout()->totalHeightForWidth(w);
9834 This is a bit hackish, but ideally we would have created a virtual function
9835 in the public API (however, too late...) so that subclasses could reimplement
9837 Instead we add a virtual function to QWidgetPrivate.
9838 ### Qt5: move to public class and make virtual
9840 bool QWidgetPrivate::hasHeightForWidth() const
9842 return layout ? layout->hasHeightForWidth() : size_policy.hasHeightForWidth();
9846 \fn QWidget *QWidget::childAt(int x, int y) const
9848 Returns the visible child widget at the position (\a{x}, \a{y})
9849 in the widget's coordinate system. If there is no visible child
9850 widget at the specified position, the function returns 0.
9856 Returns the visible child widget at point \a p in the widget's own
9860 QWidget *QWidget::childAt(const QPoint &p) const
9862 return d_func()->childAt_helper(p, false);
9865 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9867 if (children.isEmpty())
9872 // Unified tool bars on the Mac require special handling since they live outside
9873 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9874 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9875 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9877 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9880 if (!pointInsideRectAndMask(p))
9882 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9885 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9888 Q_UNUSED(includeFrame);
9890 for (int i = children.size() - 1; i >= 0; --i) {
9891 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9892 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9893 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9897 // Map the point 'p' from parent coordinates to child coordinates.
9898 QPoint childPoint = p;
9900 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9901 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9902 // QWidget::mapFromParent won't do the trick.
9903 if (includeFrame && qobject_cast<QToolBar *>(child))
9904 childPoint = qt_mac_nativeMapFromParent(child, p);
9907 childPoint -= child->data->crect.topLeft();
9909 // Check if the point hits the child.
9910 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9913 // Do the same for the child's descendants.
9914 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9917 // We have found our target; namely the child at position 'p'.
9923 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9927 widgetItem->invalidateSizeCache();
9929 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9930 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9931 if (parent->d_func()->layout)
9932 parent->d_func()->layout->invalidate();
9933 else if (parent->isVisible())
9934 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9940 Notifies the layout system that this widget has changed and may
9941 need to change geometry.
9943 Call this function if the sizeHint() or sizePolicy() have changed.
9945 For explicitly hidden widgets, updateGeometry() is a no-op. The
9946 layout system will be notified as soon as the widget is shown.
9949 void QWidget::updateGeometry()
9952 d->updateGeometry_helper(false);
9955 /*! \property QWidget::windowFlags
9957 Window flags are a combination of a type (e.g. Qt::Dialog) and
9958 zero or more hints to the window system (e.g.
9959 Qt::FramelessWindowHint).
9961 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9962 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9963 0) on the desktop. If the widget is a window and becomes a
9964 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9965 relative to its parent widget.
9967 \note This function calls setParent() when changing the flags for
9968 a window, causing the widget to be hidden. You must call show() to make
9969 the widget visible again..
9971 \sa windowType(), {Window Flags Example}
9973 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9975 if (data->window_flags == flags)
9980 if ((data->window_flags | flags) & Qt::Window) {
9981 // the old type was a window and/or the new type is a window
9982 QPoint oldPos = pos();
9983 bool visible = isVisible();
9984 setParent(parentWidget(), flags);
9986 // if both types are windows or neither of them are, we restore
9988 if (!((data->window_flags ^ flags) & Qt::Window)
9989 && (visible || testAttribute(Qt::WA_Moved))) {
9992 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9993 d->adjustQuitOnCloseAttribute();
9995 data->window_flags = flags;
10000 Sets the window flags for the widget to \a flags,
10001 \e without telling the window system.
10003 \warning Do not call this function unless you really know what
10006 \sa setWindowFlags()
10008 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
10010 data->window_flags = flags;
10014 \fn Qt::WindowType QWidget::windowType() const
10016 Returns the window type of this widget. This is identical to
10017 windowFlags() & Qt::WindowType_Mask.
10023 Sets the parent of the widget to \a parent, and resets the window
10024 flags. The widget is moved to position (0, 0) in its new parent.
10026 If the new parent widget is in a different window, the
10027 reparented widget and its children are appended to the end of the
10028 \l{setFocusPolicy()}{tab chain} of the new parent
10029 widget, in the same internal order as before. If one of the moved
10030 widgets had keyboard focus, setParent() calls clearFocus() for that
10033 If the new parent widget is in the same window as the
10034 old parent, setting the parent doesn't change the tab order or
10037 If the "new" parent widget is the old parent widget, this function
10040 \note The widget becomes invisible as part of changing its parent,
10041 even if it was previously visible. You must call show() to make the
10042 widget visible again.
10044 \warning It is very unlikely that you will ever need this
10045 function. If you have a widget that changes its content
10046 dynamically, it is far easier to use \l QStackedWidget.
10048 \sa setWindowFlags()
10050 void QWidget::setParent(QWidget *parent)
10052 if (parent == parentWidget())
10054 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
10060 This function also takes widget flags, \a f as an argument.
10063 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
10066 d->inSetParent = true;
10067 bool resized = testAttribute(Qt::WA_Resized);
10068 bool wasCreated = testAttribute(Qt::WA_WState_Created);
10069 QWidget *oldtlw = window();
10071 QWidget *desktopWidget = 0;
10072 if (parent && parent->windowType() == Qt::Desktop)
10073 desktopWidget = parent;
10074 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
10076 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
10077 if (newParent && parent && !desktopWidget) {
10078 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
10079 #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
10080 // On Mac, toolbars inside the unified title bar will never overlap with
10081 // siblings in the content view. So we skip enforce native siblings in that case
10082 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
10083 #endif // Q_WS_MAC && QT_MAC_USE_COCOA
10085 parent->d_func()->enforceNativeChildren();
10086 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
10087 setAttribute(Qt::WA_NativeWindow);
10092 if (!testAttribute(Qt::WA_WState_Hidden)) {
10094 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
10097 QEvent e(QEvent::ParentAboutToChange);
10098 QApplication::sendEvent(this, &e);
10101 if (newParent && isAncestorOf(focusWidget()))
10102 focusWidget()->clearFocus();
10104 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
10105 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
10107 d->setParent_sys(parent, f);
10109 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
10110 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
10111 if (oldBsTracker && oldBsTracker != bsTracker)
10112 oldBsTracker->unregisterWidgetSubtree(this);
10117 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
10119 oldBs->removeDirtyWidget(this);
10120 // Move the widget and all its static children from
10121 // the old backing store to the new one.
10122 oldBs->moveStaticWidgets(this);
10125 if ((QApplicationPrivate::app_compile_version < 0x040200
10126 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
10127 && !testAttribute(Qt::WA_WState_Created))
10130 d->reparentFocusWidgets(oldtlw);
10131 setAttribute(Qt::WA_Resized, resized);
10132 if (!testAttribute(Qt::WA_StyleSheet)
10133 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
10135 d->resolvePalette();
10137 d->resolveLayoutDirection();
10138 d->resolveLocale();
10140 // Note: GL widgets under WGL or EGL will always need a ParentChange
10141 // event to handle recreation/rebinding of the GL context, hence the
10142 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
10145 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
10146 || (f & Qt::MSWindowsOwnDC)
10149 // propagate enabled updates enabled state to non-windows
10151 if (!testAttribute(Qt::WA_ForceDisabled))
10152 d->setEnabled_helper(parent ? parent->isEnabled() : true);
10153 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
10154 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
10158 // send and post remaining QObject events
10159 if (parent && d->sendChildEvents) {
10160 QChildEvent e(QEvent::ChildAdded, this);
10161 QApplication::sendEvent(parent, &e);
10163 if (parent->d_func()->pendingChildInsertedEvents.isEmpty()) {
10164 QApplication::postEvent(parent,
10165 new QEvent(QEvent::ChildInsertedRequest),
10166 Qt::HighEventPriority);
10168 parent->d_func()->pendingChildInsertedEvents.append(this);
10172 //### already hidden above ---> must probably do something smart on the mac
10174 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
10175 // if(!qt_mac_is_macdrawer(q)) //special case
10176 // q->setAttribute(Qt::WA_WState_Hidden);
10178 // q->setAttribute(Qt::WA_WState_Hidden);
10181 if (parent && d->sendChildEvents && d->polished) {
10182 QChildEvent e(QEvent::ChildPolished, this);
10183 QCoreApplication::sendEvent(parent, &e);
10186 QEvent e(QEvent::ParentChange);
10187 QApplication::sendEvent(this, &e);
10191 if (isWindow() || parentWidget()->isVisible())
10192 setAttribute(Qt::WA_WState_Hidden, true);
10193 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
10194 setAttribute(Qt::WA_WState_Hidden, false);
10197 d->updateIsOpaque();
10199 #ifndef QT_NO_GRAPHICSVIEW
10200 // Embed the widget into a proxy if the parent is embedded.
10201 // ### Doesn't handle reparenting out of an embedded widget.
10202 if (oldtlw->graphicsProxyWidget()) {
10203 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
10204 ancestorProxy->d_func()->unembedSubWindow(this);
10206 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
10207 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
10208 ancestorProxy->d_func()->embedSubWindow(this);
10212 d->inSetParent = false;
10216 Scrolls the widget including its children \a dx pixels to the
10217 right and \a dy downward. Both \a dx and \a dy may be negative.
10219 After scrolling, the widgets will receive paint events for
10220 the areas that need to be repainted. For widgets that Qt knows to
10221 be opaque, this is only the newly exposed parts.
10222 For example, if an opaque widget is scrolled 8 pixels to the left,
10223 only an 8-pixel wide stripe at the right edge needs updating.
10225 Since widgets propagate the contents of their parents by default,
10226 you need to set the \l autoFillBackground property, or use
10227 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
10230 For widgets that use contents propagation, a scroll will cause an
10231 update of the entire scroll area.
10233 \sa {Transparency and Double Buffering}
10236 void QWidget::scroll(int dx, int dy)
10238 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
10240 if (dx == 0 && dy == 0)
10243 #ifndef QT_NO_GRAPHICSVIEW
10244 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
10245 // Graphics View maintains its own dirty region as a list of rects;
10246 // until we can connect item updates directly to the view, we must
10247 // separately add a translated dirty region.
10248 if (!d->dirty.isEmpty()) {
10249 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
10250 proxy->update(rect);
10252 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
10256 d->setDirtyOpaqueRegion();
10257 d->scroll_sys(dx, dy);
10263 This version only scrolls \a r and does not move the children of
10266 If \a r is empty or invalid, the result is undefined.
10270 void QWidget::scroll(int dx, int dy, const QRect &r)
10273 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
10275 if (dx == 0 && dy == 0)
10278 #ifndef QT_NO_GRAPHICSVIEW
10279 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
10280 // Graphics View maintains its own dirty region as a list of rects;
10281 // until we can connect item updates directly to the view, we must
10282 // separately add a translated dirty region.
10283 if (!d->dirty.isEmpty()) {
10284 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
10285 proxy->update(rect);
10287 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
10291 d->scroll_sys(dx, dy, r);
10295 Repaints the widget directly by calling paintEvent() immediately,
10296 unless updates are disabled or the widget is hidden.
10298 We suggest only using repaint() if you need an immediate repaint,
10299 for example during animation. In almost all circumstances update()
10300 is better, as it permits Qt to optimize for speed and minimize
10303 \warning If you call repaint() in a function which may itself be
10304 called from paintEvent(), you may get infinite recursion. The
10305 update() function never causes recursion.
10307 \sa update(), paintEvent(), setUpdatesEnabled()
10310 void QWidget::repaint()
10317 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
10320 If \a w is negative, it is replaced with \c{width() - x}, and if
10321 \a h is negative, it is replaced width \c{height() - y}.
10323 void QWidget::repaint(int x, int y, int w, int h)
10325 if (x > data->crect.width() || y > data->crect.height())
10329 w = data->crect.width() - x;
10331 h = data->crect.height() - y;
10333 repaint(QRect(x, y, w, h));
10338 This version repaints a rectangle \a rect inside the widget.
10340 void QWidget::repaint(const QRect &rect)
10344 if (testAttribute(Qt::WA_WState_ConfigPending)) {
10349 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
10352 if (hasBackingStoreSupport()) {
10353 #ifdef QT_MAC_USE_COCOA
10354 if (qt_widget_private(this)->isInUnifiedToolbar) {
10355 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10358 #endif // QT_MAC_USE_COCOA
10359 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10360 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
10361 tlwExtra->inRepaint = true;
10362 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
10363 tlwExtra->inRepaint = false;
10366 d->repaint_sys(rect);
10373 This version repaints a region \a rgn inside the widget.
10375 void QWidget::repaint(const QRegion &rgn)
10379 if (testAttribute(Qt::WA_WState_ConfigPending)) {
10384 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
10387 if (hasBackingStoreSupport()) {
10388 #ifdef QT_MAC_USE_COCOA
10389 if (qt_widget_private(this)->isInUnifiedToolbar) {
10390 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10393 #endif // QT_MAC_USE_COCOA
10394 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10395 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
10396 tlwExtra->inRepaint = true;
10397 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
10398 tlwExtra->inRepaint = false;
10401 d->repaint_sys(rgn);
10406 Updates the widget unless updates are disabled or the widget is
10409 This function does not cause an immediate repaint; instead it
10410 schedules a paint event for processing when Qt returns to the main
10411 event loop. This permits Qt to optimize for more speed and less
10412 flicker than a call to repaint() does.
10414 Calling update() several times normally results in just one
10417 Qt normally erases the widget's area before the paintEvent() call.
10418 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
10419 responsible for painting all its pixels with an opaque color.
10421 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
10423 void QWidget::update()
10428 /*! \fn void QWidget::update(int x, int y, int w, int h)
10431 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
10438 This version updates a rectangle \a rect inside the widget.
10440 void QWidget::update(const QRect &rect)
10442 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
10445 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
10446 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
10450 if (hasBackingStoreSupport()) {
10451 #ifdef QT_MAC_USE_COCOA
10452 if (qt_widget_private(this)->isInUnifiedToolbar) {
10453 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10456 #endif // QT_MAC_USE_COCOA
10457 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10458 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
10459 tlwExtra->backingStoreTracker->markDirty(rect, this);
10461 d_func()->repaint_sys(rect);
10468 This version repaints a region \a rgn inside the widget.
10470 void QWidget::update(const QRegion &rgn)
10472 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
10475 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
10476 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
10480 if (hasBackingStoreSupport()) {
10481 #ifdef QT_MAC_USE_COCOA
10482 if (qt_widget_private(this)->isInUnifiedToolbar) {
10483 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10486 #endif // QT_MAC_USE_COCOA
10487 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10488 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
10489 tlwExtra->backingStoreTracker->markDirty(rgn, this);
10491 d_func()->repaint_sys(rgn);
10497 Clear the rectangle at point (\a x, \a y) of width \a w and height
10500 \warning This is best done in a paintEvent().
10502 void QWidget::erase_helper(int x, int y, int w, int h)
10504 if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible))
10507 w = data->crect.width() - x;
10509 h = data->crect.height() - y;
10510 if (w != 0 && h != 0) {
10512 p.eraseRect(QRect(x, y, w, h));
10519 Clear the given region, \a rgn.
10521 Drawing may only take place in a QPaintEvent. Overload
10522 paintEvent() to do your erasing and call update() to schedule a
10523 replaint whenever necessary. See also QPainter.
10525 void QWidget::erase(const QRegion& rgn)
10527 if (testAttribute(Qt::WA_NoSystemBackground) || testAttribute(Qt::WA_UpdatesDisabled) || !testAttribute(Qt::WA_WState_Visible))
10531 p.setClipRegion(rgn);
10532 p.eraseRect(rgn.boundingRect());
10535 void QWidget::drawText_helper(int x, int y, const QString &str)
10537 if(!testAttribute(Qt::WA_WState_Visible))
10539 QPainter paint(this);
10540 paint.drawText(x, y, str);
10547 Use the no-argument overload instead.
10549 bool QWidget::close(bool alsoDelete)
10551 QPointer<QWidget> that = this;
10552 bool accepted = close();
10553 if (alsoDelete && accepted && that)
10558 void QWidget::setIcon(const QPixmap &i)
10564 Return's the widget's icon.
10566 Use windowIcon() instead.
10568 const QPixmap *QWidget::icon() const
10570 Q_D(const QWidget);
10571 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconPixmap : 0;
10574 #endif // QT3_SUPPORT
10579 This just sets the corresponding attribute bit to 1 or 0
10581 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
10584 if (attribute < int(8*sizeof(uint))) {
10586 data->widget_attributes |= (1<<attribute);
10588 data->widget_attributes &= ~(1<<attribute);
10590 const int x = attribute - 8*sizeof(uint);
10591 const int int_off = x / (8*sizeof(uint));
10593 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
10595 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
10600 Sets the attribute \a attribute on this widget if \a on is true;
10601 otherwise clears the attribute.
10603 \sa testAttribute()
10605 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
10607 if (testAttribute(attribute) == on)
10611 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
10612 "QWidget::setAttribute(WidgetAttribute, bool)",
10613 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
10615 // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
10616 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
10617 // see qwidget_win.cpp, ::paintEngine for details
10619 if (d->noPaintOnScreen)
10624 setAttribute_internal(attribute, on, data, d);
10626 switch (attribute) {
10628 #ifndef QT_NO_DRAGANDDROP
10629 case Qt::WA_AcceptDrops: {
10630 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
10631 setAttribute(Qt::WA_DropSiteRegistered, true);
10632 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
10633 setAttribute(Qt::WA_DropSiteRegistered, false);
10634 QEvent e(QEvent::AcceptDropsChange);
10635 QApplication::sendEvent(this, &e);
10638 case Qt::WA_DropSiteRegistered: {
10639 d->registerDropSite(on);
10640 for (int i = 0; i < d->children.size(); ++i) {
10641 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
10642 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
10643 w->setAttribute(Qt::WA_DropSiteRegistered, on);
10649 case Qt::WA_NoChildEventsForParent:
10650 d->sendChildEvents = !on;
10652 case Qt::WA_NoChildEventsFromChildren:
10653 d->receiveChildEvents = !on;
10655 case Qt::WA_MacBrushedMetal:
10657 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
10658 // fall through since changing the metal attribute affects the opaque size grip.
10659 case Qt::WA_MacOpaqueSizeGrip:
10660 d->macUpdateOpaqueSizeGrip();
10662 case Qt::WA_MacShowFocusRect:
10669 qt_mac_update_mouseTracking(this);
10672 case Qt::WA_MacAlwaysShowToolWindow:
10674 d->macUpdateHideOnSuspend();
10677 case Qt::WA_MacNormalSize:
10678 case Qt::WA_MacSmallSize:
10679 case Qt::WA_MacMiniSize:
10682 // We can only have one of these set at a time
10683 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10684 Qt::WA_MacMiniSize };
10685 for (int i = 0; i < 3; ++i) {
10686 if (MacSizes[i] != attribute)
10687 setAttribute_internal(MacSizes[i], false, data, d);
10689 d->macUpdateSizeAttribute();
10693 case Qt::WA_ShowModal:
10696 QApplicationPrivate::leaveModal(this);
10697 // reset modality type to Modeless when clearing WA_ShowModal
10698 data->window_modality = Qt::NonModal;
10699 } else if (data->window_modality == Qt::NonModal) {
10700 // determine the modality type if it hasn't been set prior
10701 // to setting WA_ShowModal. set the default to WindowModal
10702 // if we are the child of a group leader; otherwise use
10703 // ApplicationModal.
10704 QWidget *w = parentWidget();
10707 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10708 w = w->parentWidget();
10712 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10714 : Qt::ApplicationModal;
10715 // Some window managers does not allow us to enter modal after the
10716 // window is showing. Therefore, to be consistent, we cannot call
10717 // QApplicationPrivate::enterModal(this) here. The window must be
10718 // hidden before changing modality.
10720 if (testAttribute(Qt::WA_WState_Created)) {
10721 // don't call setModal_sys() before create_sys()
10725 case Qt::WA_MouseTracking: {
10726 QEvent e(QEvent::MouseTrackingChange);
10727 QApplication::sendEvent(this, &e);
10729 case Qt::WA_NativeWindow: {
10730 #if defined(Q_WS_QPA)
10731 d->createTLExtra();
10734 QWidget *focusWidget = d->effectiveFocusWidget();
10735 QInputContext *ic = 0;
10736 if (on && !internalWinId() && hasFocus()
10737 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10738 ic = focusWidget->d_func()->inputContext();
10741 ic->setFocusWidget(0);
10744 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10745 #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
10746 // On Mac, toolbars inside the unified title bar will never overlap with
10747 // siblings in the content view. So we skip enforce native siblings in that case
10748 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10749 #endif // Q_WS_MAC && QT_MAC_USE_COCOA
10751 parentWidget()->d_func()->enforceNativeChildren();
10752 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10754 if (ic && isEnabled() && focusWidget->isEnabled()
10755 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10756 ic->setFocusWidget(focusWidget);
10761 case Qt::WA_PaintOnScreen:
10762 d->updateIsOpaque();
10763 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
10764 // Recreate the widget if it's already created as an alien widget and
10765 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10766 // So must their children.
10768 setAttribute(Qt::WA_NativeWindow);
10769 d->enforceNativeChildren();
10773 case Qt::WA_OpaquePaintEvent:
10774 d->updateIsOpaque();
10776 case Qt::WA_NoSystemBackground:
10777 d->updateIsOpaque();
10779 case Qt::WA_UpdatesDisabled:
10780 d->updateSystemBackground();
10782 case Qt::WA_TransparentForMouseEvents:
10784 d->macUpdateIgnoreMouseEvents();
10787 case Qt::WA_InputMethodEnabled: {
10789 QWidget *focusWidget = d->effectiveFocusWidget();
10790 QInputContext *ic = focusWidget->d_func()->assignedInputContext();
10791 if (!ic && (!on || hasFocus()))
10792 ic = focusWidget->d_func()->inputContext();
10794 if (on && hasFocus() && ic->focusWidget() != focusWidget && isEnabled()
10795 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10796 ic->setFocusWidget(focusWidget);
10797 } else if (!on && ic->focusWidget() == focusWidget) {
10799 ic->setFocusWidget(0);
10805 case Qt::WA_WindowPropagation:
10806 d->resolvePalette();
10808 d->resolveLocale();
10811 case Qt::WA_NoX11EventCompression:
10814 d->extra->compress_events = on;
10816 case Qt::WA_X11OpenGLOverlay:
10817 d->updateIsOpaque();
10819 case Qt::WA_X11DoNotAcceptFocus:
10820 if (testAttribute(Qt::WA_WState_Created))
10821 d->updateX11AcceptFocus();
10824 case Qt::WA_DontShowOnScreen: {
10825 if (on && isVisible()) {
10826 // Make sure we keep the current state and only hide the widget
10827 // from the desktop. show_sys will only update platform specific
10828 // attributes at this point.
10836 case Qt::WA_X11NetWmWindowTypeDesktop:
10837 case Qt::WA_X11NetWmWindowTypeDock:
10838 case Qt::WA_X11NetWmWindowTypeToolBar:
10839 case Qt::WA_X11NetWmWindowTypeMenu:
10840 case Qt::WA_X11NetWmWindowTypeUtility:
10841 case Qt::WA_X11NetWmWindowTypeSplash:
10842 case Qt::WA_X11NetWmWindowTypeDialog:
10843 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10844 case Qt::WA_X11NetWmWindowTypePopupMenu:
10845 case Qt::WA_X11NetWmWindowTypeToolTip:
10846 case Qt::WA_X11NetWmWindowTypeNotification:
10847 case Qt::WA_X11NetWmWindowTypeCombo:
10848 case Qt::WA_X11NetWmWindowTypeDND:
10849 if (testAttribute(Qt::WA_WState_Created))
10850 d->setNetWmWindowTypes();
10854 case Qt::WA_StaticContents:
10855 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10857 bs->addStaticWidget(this);
10859 bs->removeStaticWidget(this);
10862 case Qt::WA_TranslucentBackground:
10864 setAttribute(Qt::WA_NoSystemBackground);
10865 d->updateIsTranslucent();
10869 case Qt::WA_AcceptTouchEvents:
10870 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
10872 d->registerTouchWindow();
10875 case Qt::WA_LockPortraitOrientation:
10876 case Qt::WA_LockLandscapeOrientation:
10877 case Qt::WA_AutoOrientation: {
10878 const Qt::WidgetAttribute orientations[3] = {
10879 Qt::WA_LockPortraitOrientation,
10880 Qt::WA_LockLandscapeOrientation,
10881 Qt::WA_AutoOrientation
10885 // We can only have one of these set at a time
10886 for (int i = 0; i < 3; ++i) {
10887 if (orientations[i] != attribute)
10888 setAttribute_internal(orientations[i], false, data, d);
10893 CAknAppUiBase* appUi = static_cast<CAknAppUiBase*>(CEikonEnv::Static()->EikAppUi());
10894 const CAknAppUiBase::TAppUiOrientation s60orientations[] = {
10895 CAknAppUiBase::EAppUiOrientationPortrait,
10896 CAknAppUiBase::EAppUiOrientationLandscape,
10897 CAknAppUiBase::EAppUiOrientationAutomatic
10899 CAknAppUiBase::TAppUiOrientation s60orientation = CAknAppUiBase::EAppUiOrientationUnspecified;
10900 for (int i = 0; i < 3; ++i) {
10901 if (testAttribute(orientations[i])) {
10902 s60orientation = s60orientations[i];
10906 QT_TRAP_THROWING(appUi->SetOrientationL(s60orientation));
10907 S60->orientationSet = true;
10908 QSymbianControl *window = static_cast<QSymbianControl *>(internalWinId());
10910 window->ensureFixNativeOrientation();
10919 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10921 Returns true if attribute \a attribute is set on this widget;
10922 otherwise returns false.
10926 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10928 Q_D(const QWidget);
10929 const int x = attribute - 8*sizeof(uint);
10930 const int int_off = x / (8*sizeof(uint));
10931 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10935 \property QWidget::windowOpacity
10937 \brief The level of opacity for the window.
10939 The valid range of opacity is from 1.0 (completely opaque) to
10940 0.0 (completely transparent).
10942 By default the value of this property is 1.0.
10944 This feature is available on Embedded Linux, Mac OS X, Windows,
10945 and X11 platforms that support the Composite extension.
10947 This feature is not available on Windows CE.
10949 Note that under X11 you need to have a composite manager running,
10950 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10951 supported by the window manager you are using.
10953 \warning Changing this property from opaque to transparent might issue a
10954 paint event that needs to be processed before the window is displayed
10955 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10956 that semi-transparent windows update and resize significantly slower than
10961 qreal QWidget::windowOpacity() const
10963 Q_D(const QWidget);
10964 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10967 void QWidget::setWindowOpacity(qreal opacity)
10973 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10974 QTLWExtra *extra = d->topData();
10975 extra->opacity = uint(opacity * 255);
10976 setAttribute(Qt::WA_WState_WindowOpacitySet);
10978 if (!testAttribute(Qt::WA_WState_Created))
10981 #ifndef QT_NO_GRAPHICSVIEW
10982 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10983 // Avoid invalidating the cache if set.
10984 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10986 else if (QGraphicsScene *scene = proxy->scene())
10987 scene->update(proxy->sceneBoundingRect());
10992 d->setWindowOpacity_sys(opacity);
10996 \property QWidget::windowModified
10997 \brief whether the document shown in the window has unsaved changes
10999 A modified window is a window whose content has changed but has
11000 not been saved to disk. This flag will have different effects
11001 varied by the platform. On Mac OS X the close button will have a
11002 modified look; on other platforms, the window title will have an
11005 The window title must contain a "[*]" placeholder, which
11006 indicates where the '*' should appear. Normally, it should appear
11007 right after the file name (e.g., "document1.txt[*] - Text
11008 Editor"). If the window isn't modified, the placeholder is simply
11011 Note that if a widget is set as modified, all its ancestors will
11012 also be set as modified. However, if you call \c
11013 {setWindowModified(false)} on a widget, this will not propagate to
11014 its parent because other children of the parent might have been
11017 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
11019 bool QWidget::isWindowModified() const
11021 return testAttribute(Qt::WA_WindowModified);
11024 void QWidget::setWindowModified(bool mod)
11027 setAttribute(Qt::WA_WindowModified, mod);
11030 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
11031 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
11033 d->setWindowTitle_helper(windowTitle());
11034 d->setWindowIconText_helper(windowIconText());
11036 d->setWindowModified_sys(mod);
11039 QEvent e(QEvent::ModifiedChange);
11040 QApplication::sendEvent(this, &e);
11043 #ifndef QT_NO_TOOLTIP
11045 \property QWidget::toolTip
11047 \brief the widget's tooltip
11049 Note that by default tooltips are only shown for widgets that are
11050 children of the active window. You can change this behavior by
11051 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
11052 not on the widget with the tooltip.
11054 If you want to control a tooltip's behavior, you can intercept the
11055 event() function and catch the QEvent::ToolTip event (e.g., if you
11056 want to customize the area for which the tooltip should be shown).
11058 By default, this property contains an empty string.
11060 \sa QToolTip statusTip whatsThis
11062 void QWidget::setToolTip(const QString &s)
11067 QEvent event(QEvent::ToolTipChange);
11068 QApplication::sendEvent(this, &event);
11071 QString QWidget::toolTip() const
11073 Q_D(const QWidget);
11076 #endif // QT_NO_TOOLTIP
11079 #ifndef QT_NO_STATUSTIP
11081 \property QWidget::statusTip
11082 \brief the widget's status tip
11084 By default, this property contains an empty string.
11086 \sa toolTip whatsThis
11088 void QWidget::setStatusTip(const QString &s)
11094 QString QWidget::statusTip() const
11096 Q_D(const QWidget);
11097 return d->statusTip;
11099 #endif // QT_NO_STATUSTIP
11101 #ifndef QT_NO_WHATSTHIS
11103 \property QWidget::whatsThis
11105 \brief the widget's What's This help text.
11107 By default, this property contains an empty string.
11109 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
11111 void QWidget::setWhatsThis(const QString &s)
11117 QString QWidget::whatsThis() const
11119 Q_D(const QWidget);
11120 return d->whatsThis;
11122 #endif // QT_NO_WHATSTHIS
11124 #ifndef QT_NO_ACCESSIBILITY
11126 \property QWidget::accessibleName
11128 \brief the widget's name as seen by assistive technologies
11130 This property is used by accessible clients to identify, find, or announce
11131 the widget for accessible clients.
11133 By default, this property contains an empty string.
11135 \sa QAccessibleInterface::text()
11137 void QWidget::setAccessibleName(const QString &name)
11140 d->accessibleName = name;
11141 QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged);
11144 QString QWidget::accessibleName() const
11146 Q_D(const QWidget);
11147 return d->accessibleName;
11151 \property QWidget::accessibleDescription
11153 \brief the widget's description as seen by assistive technologies
11155 By default, this property contains an empty string.
11157 \sa QAccessibleInterface::text()
11159 void QWidget::setAccessibleDescription(const QString &description)
11162 d->accessibleDescription = description;
11163 QAccessible::updateAccessibility(this, 0, QAccessible::DescriptionChanged);
11166 QString QWidget::accessibleDescription() const
11168 Q_D(const QWidget);
11169 return d->accessibleDescription;
11171 #endif // QT_NO_ACCESSIBILITY
11173 #ifndef QT_NO_SHORTCUT
11175 Adds a shortcut to Qt's shortcut system that watches for the given
11176 \a key sequence in the given \a context. If the \a context is
11177 Qt::ApplicationShortcut, the shortcut applies to the application as a
11178 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
11179 or to the window itself, Qt::WindowShortcut.
11181 If the same \a key sequence has been grabbed by several widgets,
11182 when the \a key sequence occurs a QEvent::Shortcut event is sent
11183 to all the widgets to which it applies in a non-deterministic
11184 order, but with the ``ambiguous'' flag set to true.
11186 \warning You should not normally need to use this function;
11187 instead create \l{QAction}s with the shortcut key sequences you
11188 require (if you also want equivalent menu options and toolbar
11189 buttons), or create \l{QShortcut}s if you just need key sequences.
11190 Both QAction and QShortcut handle all the event filtering for you,
11191 and provide signals which are triggered when the user triggers the
11192 key sequence, so are much easier to use than this low-level
11195 \sa releaseShortcut() setShortcutEnabled()
11197 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
11202 setAttribute(Qt::WA_GrabbedShortcut);
11203 return qApp->d_func()->shortcutMap.addShortcut(this, key, context);
11207 Removes the shortcut with the given \a id from Qt's shortcut
11208 system. The widget will no longer receive QEvent::Shortcut events
11209 for the shortcut's key sequence (unless it has other shortcuts
11210 with the same key sequence).
11212 \warning You should not normally need to use this function since
11213 Qt's shortcut system removes shortcuts automatically when their
11214 parent widget is destroyed. It is best to use QAction or
11215 QShortcut to handle shortcuts, since they are easier to use than
11216 this low-level function. Note also that this is an expensive
11219 \sa grabShortcut() setShortcutEnabled()
11221 void QWidget::releaseShortcut(int id)
11225 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
11229 If \a enable is true, the shortcut with the given \a id is
11230 enabled; otherwise the shortcut is disabled.
11232 \warning You should not normally need to use this function since
11233 Qt's shortcut system enables/disables shortcuts automatically as
11234 widgets become hidden/visible and gain or lose focus. It is best
11235 to use QAction or QShortcut to handle shortcuts, since they are
11236 easier to use than this low-level function.
11238 \sa grabShortcut() releaseShortcut()
11240 void QWidget::setShortcutEnabled(int id, bool enable)
11244 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
11250 If \a enable is true, auto repeat of the shortcut with the
11251 given \a id is enabled; otherwise it is disabled.
11253 \sa grabShortcut() releaseShortcut()
11255 void QWidget::setShortcutAutoRepeat(int id, bool enable)
11259 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
11261 #endif // QT_NO_SHORTCUT
11263 Updates the widget's micro focus.
11267 void QWidget::updateMicroFocus()
11270 // and optimization to update input context only it has already been created.
11271 if (d->assignedInputContext() || qApp->d_func()->inputContext) {
11272 QInputContext *ic = inputContext();
11276 #ifndef QT_NO_ACCESSIBILITY
11278 // ##### is this correct
11279 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
11285 #if defined (Q_WS_WIN)
11287 Returns the window system handle of the widget, for low-level
11288 access. Using this function is not portable.
11290 An HDC acquired with getDC() has to be released with releaseDC().
11292 \warning Using this function is not portable.
11294 HDC QWidget::getDC() const
11296 Q_D(const QWidget);
11298 return (HDC) d->hd;
11299 return GetDC(winId());
11303 Releases the HDC \a hdc acquired by a previous call to getDC().
11305 \warning Using this function is not portable.
11307 void QWidget::releaseDC(HDC hdc) const
11309 Q_D(const QWidget);
11310 // If its the widgets own dc, it will be released elsewhere. If
11311 // its a different HDC we release it and issue a warning if it
11313 if (hdc != d->hd && !ReleaseDC(winId(), hdc))
11314 qErrnoWarning("QWidget::releaseDC(): failed to release HDC");
11318 Returns the window system handle of the widget, for low-level
11319 access. Using this function is not portable.
11321 The HANDLE type varies with platform; see \c qwindowdefs.h for
11324 Qt::HANDLE QWidget::handle() const
11326 Q_D(const QWidget);
11327 if (!internalWinId() && testAttribute(Qt::WA_WState_Created))
11328 (void)winId(); // enforce native window
11335 Raises this widget to the top of the parent widget's stack.
11337 After this call the widget will be visually in front of any
11338 overlapping sibling widgets.
11340 \note When using activateWindow(), you can call this function to
11341 ensure that the window is stacked on top.
11343 \sa lower(), stackUnder()
11346 void QWidget::raise()
11350 QWidget *p = parentWidget();
11351 const int parentChildCount = p->d_func()->children.size();
11352 if (parentChildCount < 2)
11354 const int from = p->d_func()->children.indexOf(this);
11355 Q_ASSERT(from >= 0);
11356 // Do nothing if the widget is already in correct stacking order _and_ created.
11357 if (from != parentChildCount -1)
11358 p->d_func()->children.move(from, parentChildCount - 1);
11359 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
11361 else if (from == parentChildCount - 1)
11364 QRegion region(rect());
11365 d->subtractOpaqueSiblings(region);
11366 d->invalidateBuffer(region);
11368 if (testAttribute(Qt::WA_WState_Created))
11371 QEvent e(QEvent::ZOrderChange);
11372 QApplication::sendEvent(this, &e);
11376 Lowers the widget to the bottom of the parent widget's stack.
11378 After this call the widget will be visually behind (and therefore
11379 obscured by) any overlapping sibling widgets.
11381 \sa raise(), stackUnder()
11384 void QWidget::lower()
11388 QWidget *p = parentWidget();
11389 const int parentChildCount = p->d_func()->children.size();
11390 if (parentChildCount < 2)
11392 const int from = p->d_func()->children.indexOf(this);
11393 Q_ASSERT(from >= 0);
11394 // Do nothing if the widget is already in correct stacking order _and_ created.
11396 p->d_func()->children.move(from, 0);
11397 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
11399 else if (from == 0)
11402 if (testAttribute(Qt::WA_WState_Created))
11405 QEvent e(QEvent::ZOrderChange);
11406 QApplication::sendEvent(this, &e);
11411 Places the widget under \a w in the parent widget's stack.
11413 To make this work, the widget itself and \a w must be siblings.
11415 \sa raise(), lower()
11417 void QWidget::stackUnder(QWidget* w)
11420 QWidget *p = parentWidget();
11421 if (!w || isWindow() || p != w->parentWidget() || this == w)
11424 int from = p->d_func()->children.indexOf(this);
11425 int to = p->d_func()->children.indexOf(w);
11426 Q_ASSERT(from >= 0);
11430 // Do nothing if the widget is already in correct stacking order _and_ created.
11432 p->d_func()->children.move(from, to);
11433 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
11435 else if (from == to)
11438 if (testAttribute(Qt::WA_WState_Created))
11439 d->stackUnder_sys(w);
11441 QEvent e(QEvent::ZOrderChange);
11442 QApplication::sendEvent(this, &e);
11445 void QWidget::styleChange(QStyle&) { }
11446 void QWidget::enabledChange(bool) { } // compat
11447 void QWidget::paletteChange(const QPalette &) { } // compat
11448 void QWidget::fontChange(const QFont &) { } // compat
11449 void QWidget::windowActivationChange(bool) { } // compat
11450 void QWidget::languageChange() { } // compat
11454 \enum QWidget::BackgroundOrigin
11458 \value WidgetOrigin
11459 \value ParentOrigin
11460 \value WindowOrigin
11461 \value AncestorOrigin
11466 \fn bool QWidget::isVisibleToTLW() const
11468 Use isVisible() instead.
11472 \fn void QWidget::iconify()
11474 Use showMinimized() instead.
11478 \fn void QWidget::constPolish() const
11480 Use ensurePolished() instead.
11484 \fn void QWidget::reparent(QWidget *parent, Qt::WindowFlags f, const QPoint &p, bool showIt)
11486 Use setParent() to change the parent or the widget's widget flags;
11487 use move() to move the widget, and use show() to show the widget.
11491 \fn void QWidget::reparent(QWidget *parent, const QPoint &p, bool showIt)
11493 Use setParent() to change the parent; use move() to move the
11494 widget, and use show() to show the widget.
11498 \fn void QWidget::recreate(QWidget *parent, Qt::WindowFlags f, const QPoint & p, bool showIt)
11500 Use setParent() to change the parent or the widget's widget flags;
11501 use move() to move the widget, and use show() to show the widget.
11505 \fn bool QWidget::hasMouse() const
11507 Use testAttribute(Qt::WA_UnderMouse) instead.
11511 \fn bool QWidget::ownCursor() const
11513 Use testAttribute(Qt::WA_SetCursor) instead.
11517 \fn bool QWidget::ownFont() const
11519 Use testAttribute(Qt::WA_SetFont) instead.
11523 \fn void QWidget::unsetFont()
11525 Use setFont(QFont()) instead.
11529 \fn bool QWidget::ownPalette() const
11531 Use testAttribute(Qt::WA_SetPalette) instead.
11535 \fn void QWidget::unsetPalette()
11537 Use setPalette(QPalette()) instead.
11541 \fn void QWidget::setEraseColor(const QColor &color)
11543 Use the palette instead.
11546 widget->setEraseColor(color);
11549 palette.setColor(widget->backgroundRole(), color);
11550 widget->setPalette(palette);
11555 \fn void QWidget::setErasePixmap(const QPixmap &pixmap)
11557 Use the palette instead.
11560 widget->setErasePixmap(pixmap);
11563 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11564 widget->setPalette(palette);
11569 \fn void QWidget::setPaletteForegroundColor(const QColor &color)
11571 Use the palette directly.
11574 widget->setPaletteForegroundColor(color);
11577 palette.setColor(widget->foregroundRole(), color);
11578 widget->setPalette(palette);
11583 \fn void QWidget::setPaletteBackgroundColor(const QColor &color)
11585 Use the palette directly.
11588 widget->setPaletteBackgroundColor(color);
11591 palette.setColor(widget->backgroundRole(), color);
11592 widget->setPalette(palette);
11597 \fn void QWidget::setPaletteBackgroundPixmap(const QPixmap &pixmap)
11599 Use the palette directly.
11602 widget->setPaletteBackgroundPixmap(pixmap);
11605 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11606 widget->setPalette(palette);
11611 \fn void QWidget::setBackgroundPixmap(const QPixmap &pixmap)
11613 Use the palette instead.
11616 widget->setBackgroundPixmap(pixmap);
11619 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11620 widget->setPalette(palette);
11625 \fn void QWidget::setBackgroundColor(const QColor &color)
11627 Use the palette instead.
11630 widget->setBackgroundColor(color);
11633 palette.setColor(widget->backgroundRole(), color);
11634 widget->setPalette(palette);
11640 \fn QWidget *QWidget::parentWidget(bool sameWindow) const
11642 Use the no-argument overload instead.
11646 \fn void QWidget::setKeyCompression(bool b)
11648 Use setAttribute(Qt::WA_KeyCompression, b) instead.
11652 \fn void QWidget::setFont(const QFont &f, bool b)
11654 Use the single-argument overload instead.
11658 \fn void QWidget::setPalette(const QPalette &p, bool b)
11660 Use the single-argument overload instead.
11664 \fn void QWidget::setBackgroundOrigin(BackgroundOrigin background)
11670 \fn BackgroundOrigin QWidget::backgroundOrigin() const
11674 Always returns \c WindowOrigin.
11678 \fn QPoint QWidget::backgroundOffset() const
11682 Always returns QPoint().
11686 \fn void QWidget::repaint(bool b)
11688 The boolean parameter \a b is ignored. Use the no-argument overload instead.
11692 \fn void QWidget::repaint(int x, int y, int w, int h, bool b)
11694 The boolean parameter \a b is ignored. Use the four-argument overload instead.
11698 \fn void QWidget::repaint(const QRect &r, bool b)
11700 The boolean parameter \a b is ignored. Use the single rect-argument overload instead.
11704 \fn void QWidget::repaint(const QRegion &rgn, bool b)
11706 The boolean parameter \a b is ignored. Use the single region-argument overload instead.
11710 \fn void QWidget::erase()
11712 Drawing may only take place in a QPaintEvent. Overload
11713 paintEvent() to do your erasing and call update() to schedule a
11714 replaint whenever necessary. See also QPainter.
11718 \fn void QWidget::erase(int x, int y, int w, int h)
11720 Drawing may only take place in a QPaintEvent. Overload
11721 paintEvent() to do your erasing and call update() to schedule a
11722 replaint whenever necessary. See also QPainter.
11726 \fn void QWidget::erase(const QRect &rect)
11728 Drawing may only take place in a QPaintEvent. Overload
11729 paintEvent() to do your erasing and call update() to schedule a
11730 replaint whenever necessary. See also QPainter.
11734 \fn void QWidget::drawText(const QPoint &p, const QString &s)
11736 Drawing may only take place in a QPaintEvent. Overload
11737 paintEvent() to do your drawing and call update() to schedule a
11738 replaint whenever necessary. See also QPainter.
11742 \fn void QWidget::drawText(int x, int y, const QString &s)
11744 Drawing may only take place in a QPaintEvent. Overload
11745 paintEvent() to do your drawing and call update() to schedule a
11746 replaint whenever necessary. See also QPainter.
11750 \fn QWidget *QWidget::childAt(const QPoint &p, bool includeThis) const
11752 Use the single point argument overload instead.
11756 \fn void QWidget::setCaption(const QString &c)
11758 Use setWindowTitle() instead.
11762 \fn void QWidget::setIcon(const QPixmap &i)
11764 Use setWindowIcon() instead.
11768 \fn void QWidget::setIconText(const QString &it)
11770 Use setWindowIconText() instead.
11774 \fn QString QWidget::caption() const
11776 Use windowTitle() instead.
11780 \fn QString QWidget::iconText() const
11782 Use windowIconText() instead.
11786 \fn bool QWidget::isTopLevel() const
11789 Use isWindow() instead.
11793 \fn bool QWidget::isRightToLeft() const
11798 \fn bool QWidget::isLeftToRight() const
11803 \fn void QWidget::setInputMethodEnabled(bool enabled)
11805 Use setAttribute(Qt::WA_InputMethodEnabled, \a enabled) instead.
11809 \fn bool QWidget::isInputMethodEnabled() const
11811 Use testAttribute(Qt::WA_InputMethodEnabled) instead.
11815 \fn void QWidget::setActiveWindow()
11817 Use activateWindow() instead.
11821 \fn bool QWidget::isShown() const
11823 Use !isHidden() instead (notice the exclamation mark), or use isVisible() to check whether the widget is visible.
11827 \fn bool QWidget::isDialog() const
11829 Use windowType() == Qt::Dialog instead.
11833 \fn bool QWidget::isPopup() const
11835 Use windowType() == Qt::Popup instead.
11839 \fn bool QWidget::isDesktop() const
11841 Use windowType() == Qt::Desktop instead.
11845 \fn void QWidget::polish()
11847 Use ensurePolished() instead.
11851 \fn QWidget *QWidget::childAt(int x, int y, bool includeThis) const
11853 Use the childAt() overload that doesn't have an \a includeThis parameter.
11856 return widget->childAt(x, y, true);
11858 QWidget *child = widget->childAt(x, y, true);
11861 if (widget->rect().contains(x, y))
11867 \fn void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw)
11870 Use the \l sizePolicy property and heightForWidth() function instead.
11874 \fn bool QWidget::isUpdatesEnabled() const
11877 Use the \l updatesEnabled property instead.
11881 \macro QWIDGETSIZE_MAX
11884 Defines the maximum size for a QWidget object.
11886 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
11887 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
11889 \sa QWidget::setMaximumSize()
11893 \fn QWidget::setupUi(QWidget *widget)
11895 Sets up the user interface for the specified \a widget.
11897 \note This function is available with widgets that derive from user
11898 interface descriptions created using \l{uic}.
11900 \sa {Using a Designer UI File in Your Application}
11903 QRect QWidgetPrivate::frameStrut() const
11905 Q_Q(const QWidget);
11906 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
11907 // x2 = x1 + w - 1, so w/h = 1
11908 return QRect(0, 0, 1, 1);
11911 if (data.fstrut_dirty
11913 // ### Fix properly for 4.3
11916 && q->testAttribute(Qt::WA_WState_Created))
11917 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
11919 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
11922 #ifdef QT_KEYPAD_NAVIGATION
11926 Changes the focus from the current focusWidget to a widget in
11929 Returns true, if there was a widget in that direction
11931 bool QWidgetPrivate::navigateToDirection(Direction direction)
11933 QWidget *targetWidget = widgetInNavigationDirection(direction);
11935 targetWidget->setFocus();
11936 return (targetWidget != 0);
11942 Searches for a widget that is positioned in the \a direction, starting
11943 from the current focusWidget.
11945 Returns the pointer to a found widget or 0, if there was no widget in
11948 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
11950 const QWidget *sourceWidget = QApplication::focusWidget();
11953 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
11954 const int sourceX =
11955 (direction == DirectionNorth || direction == DirectionSouth) ?
11956 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
11957 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
11958 const int sourceY =
11959 (direction == DirectionEast || direction == DirectionWest) ?
11960 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
11961 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
11962 const QPoint sourcePoint(sourceX, sourceY);
11963 const QPoint sourceCenter = sourceRect.center();
11964 const QWidget *sourceWindow = sourceWidget->window();
11966 QWidget *targetWidget = 0;
11967 int shortestDistance = INT_MAX;
11968 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
11970 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
11972 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
11973 // but the owner of the proxy cannot.
11974 // Additionally, empty widgets should be ignored.
11975 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
11978 // Only navigate to a target widget that...
11979 if ( targetCandidate != sourceWidget
11980 // ...takes the focus,
11981 && targetCandidate->focusPolicy() & Qt::TabFocus
11982 // ...is above if DirectionNorth,
11983 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
11984 // ...is on the right if DirectionEast,
11985 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
11986 // ...is below if DirectionSouth,
11987 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
11988 // ...is on the left if DirectionWest,
11989 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
11991 && targetCandidate->isEnabled()
11993 && targetCandidate->isVisible()
11994 // ...is in the same window,
11995 && targetCandidate->window() == sourceWindow) {
11996 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
11997 if (targetCandidateDistance < shortestDistance) {
11998 shortestDistance = targetCandidateDistance;
11999 targetWidget = targetCandidate;
12003 return targetWidget;
12009 Tells us if it there is currently a reachable widget by keypad navigation in
12010 a certain \a orientation.
12011 If no navigation is possible, occurring key events in that \a orientation may
12012 be used to interact with the value in the focused widget, even though it
12013 currently has not the editFocus.
12015 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
12017 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
12019 return orientation == Qt::Horizontal?
12020 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
12021 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
12022 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
12023 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
12028 Checks, if the \a widget is inside a QTabWidget. If is is inside
12029 one, left/right key events will be used to switch between tabs in keypad
12030 navigation. If there is no QTabWidget, the horizontal key events can be used
12032 interact with the value in the focused widget, even though it currently has
12035 \sa QWidget::hasEditFocus()
12037 bool QWidgetPrivate::inTabWidget(QWidget *widget)
12039 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
12040 if (qobject_cast<const QTabWidget*>(tabWidget))
12050 Sets the backing store to be the \a store specified.
12051 The QWidget will take ownership of the \a store.
12053 void QWidget::setBackingStore(QBackingStore *store)
12055 // ### createWinId() ??
12062 QTLWExtra *topData = d->topData();
12063 if (topData->backingStore == store)
12066 QBackingStore *oldStore = topData->backingStore;
12067 delete topData->backingStore;
12068 topData->backingStore = store;
12070 QWidgetBackingStore *bs = d->maybeBackingStore();
12074 if (isTopLevel()) {
12075 if (bs->store != oldStore && bs->store != store)
12084 Returns the QBackingStore this widget will be drawn into.
12086 QBackingStore *QWidget::backingStore() const
12088 Q_D(const QWidget);
12089 QTLWExtra *extra = d->maybeTopData();
12090 if (extra && extra->backingStore)
12091 return extra->backingStore;
12093 QWidgetBackingStore *bs = d->maybeBackingStore();
12095 return bs ? bs->store : 0;
12098 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
12101 *left = (int)leftLayoutItemMargin;
12103 *top = (int)topLayoutItemMargin;
12105 *right = (int)rightLayoutItemMargin;
12107 *bottom = (int)bottomLayoutItemMargin;
12110 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
12112 if (leftLayoutItemMargin == left
12113 && topLayoutItemMargin == top
12114 && rightLayoutItemMargin == right
12115 && bottomLayoutItemMargin == bottom)
12119 leftLayoutItemMargin = (signed char)left;
12120 topLayoutItemMargin = (signed char)top;
12121 rightLayoutItemMargin = (signed char)right;
12122 bottomLayoutItemMargin = (signed char)bottom;
12123 q->updateGeometry();
12126 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
12129 QStyleOption myOpt;
12132 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
12136 QRect liRect = q->style()->subElementRect(element, opt, q);
12137 if (liRect.isValid()) {
12138 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
12139 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
12140 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
12141 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
12143 leftLayoutItemMargin = 0;
12144 topLayoutItemMargin = 0;
12145 rightLayoutItemMargin = 0;
12146 bottomLayoutItemMargin = 0;
12149 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
12150 void QWidgetPrivate::adjustQuitOnCloseAttribute()
12154 if (!q->parentWidget()) {
12155 Qt::WindowType type = q->windowType();
12156 if (type == Qt::Widget || type == Qt::SubWindow)
12158 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
12159 q->setAttribute(Qt::WA_QuitOnClose, false);
12165 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
12167 return widget->data;
12170 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
12172 return widget->d_func();
12176 #ifndef QT_NO_GRAPHICSVIEW
12180 Returns the proxy widget for the corresponding embedded widget in a graphics
12181 view; otherwise returns 0.
12183 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
12184 QGraphicsScene::addWidget()
12186 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
12188 Q_D(const QWidget);
12190 return d->extra->proxyWidget;
12198 \typedef QWidgetList
12201 Synonym for QList<QWidget *>.
12204 #ifndef QT_NO_GESTURES
12206 Subscribes the widget to a given \a gesture with specific \a flags.
12208 \sa ungrabGesture(), QGestureEvent
12211 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
12214 d->gestureContext.insert(gesture, flags);
12215 (void)QGestureManager::instance(); // create a gesture manager
12219 Unsubscribes the widget from a given \a gesture type
12221 \sa grabGesture(), QGestureEvent
12224 void QWidget::ungrabGesture(Qt::GestureType gesture)
12227 if (d->gestureContext.remove(gesture)) {
12228 if (QGestureManager *manager = QGestureManager::instance())
12229 manager->cleanupCachedGestures(this, gesture);
12232 #endif // QT_NO_GESTURES
12238 Platform dependent window identifier.
12242 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
12244 Frees up window system resources. Destroys the widget window if \a
12245 destroyWindow is true.
12247 destroy() calls itself recursively for all the child widgets,
12248 passing \a destroySubWindows for the \a destroyWindow parameter.
12249 To have more control over destruction of subwidgets, destroy
12250 subwidgets selectively first.
12252 This function is usually called from the QWidget destructor.
12256 \fn QPaintEngine *QWidget::paintEngine() const
12258 Returns the widget's paint engine.
12260 Note that this function should not be called explicitly by the
12261 user, since it's meant for reimplementation purposes only. The
12262 function is called by Qt internally, and the default
12263 implementation may not always return a valid pointer.
12267 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
12269 Translates the widget coordinate \a pos to global screen
12270 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
12271 the global coordinates of the top-left pixel of the widget.
12273 \sa mapFromGlobal() mapTo() mapToParent()
12277 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
12279 Translates the global screen coordinate \a pos to widget
12282 \sa mapToGlobal() mapFrom() mapFromParent()
12286 \fn void QWidget::grabMouse()
12288 Grabs the mouse input.
12290 This widget receives all mouse events until releaseMouse() is
12291 called; other widgets get no mouse events at all. Keyboard
12292 events are not affected. Use grabKeyboard() if you want to grab
12295 \warning Bugs in mouse-grabbing applications very often lock the
12296 terminal. Use this function with extreme caution, and consider
12297 using the \c -nograb command line option while debugging.
12299 It is almost never necessary to grab the mouse when using Qt, as
12300 Qt grabs and releases it sensibly. In particular, Qt grabs the
12301 mouse when a mouse button is pressed and keeps it until the last
12302 button is released.
12304 \note Only visible widgets can grab mouse input. If isVisible()
12305 returns false for a widget, that widget cannot call grabMouse().
12307 \note \bold{(Mac OS X developers)} For \e Cocoa, calling
12308 grabMouse() on a widget only works when the mouse is inside the
12309 frame of that widget. For \e Carbon, it works outside the widget's
12310 frame as well, like for Windows and X11.
12312 \sa releaseMouse() grabKeyboard() releaseKeyboard()
12316 \fn void QWidget::grabMouse(const QCursor &cursor)
12317 \overload grabMouse()
12319 Grabs the mouse input and changes the cursor shape.
12321 The cursor will assume shape \a cursor (for as long as the mouse
12322 focus is grabbed) and this widget will be the only one to receive
12323 mouse events until releaseMouse() is called().
12325 \warning Grabbing the mouse might lock the terminal.
12327 \note \bold{(Mac OS X developers)} See the note in QWidget::grabMouse().
12329 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
12333 \fn void QWidget::releaseMouse()
12335 Releases the mouse grab.
12337 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
12341 \fn void QWidget::grabKeyboard()
12343 Grabs the keyboard input.
12345 This widget receives all keyboard events until releaseKeyboard()
12346 is called; other widgets get no keyboard events at all. Mouse
12347 events are not affected. Use grabMouse() if you want to grab that.
12349 The focus widget is not affected, except that it doesn't receive
12350 any keyboard events. setFocus() moves the focus as usual, but the
12351 new focus widget receives keyboard events only after
12352 releaseKeyboard() is called.
12354 If a different widget is currently grabbing keyboard input, that
12355 widget's grab is released first.
12357 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
12361 \fn void QWidget::releaseKeyboard()
12363 Releases the keyboard grab.
12365 \sa grabKeyboard(), grabMouse(), releaseMouse()
12369 \fn QWidget *QWidget::mouseGrabber()
12371 Returns the widget that is currently grabbing the mouse input.
12373 If no widget in this application is currently grabbing the mouse,
12376 \sa grabMouse(), keyboardGrabber()
12380 \fn QWidget *QWidget::keyboardGrabber()
12382 Returns the widget that is currently grabbing the keyboard input.
12384 If no widget in this application is currently grabbing the
12385 keyboard, 0 is returned.
12387 \sa grabMouse(), mouseGrabber()
12391 \fn void QWidget::activateWindow()
12393 Sets the top-level widget containing this widget to be the active
12396 An active window is a visible top-level window that has the
12397 keyboard input focus.
12399 This function performs the same operation as clicking the mouse on
12400 the title bar of a top-level window. On X11, the result depends on
12401 the Window Manager. If you want to ensure that the window is
12402 stacked on top as well you should also call raise(). Note that the
12403 window must be visible, otherwise activateWindow() has no effect.
12405 On Windows, if you are calling this when the application is not
12406 currently the active one then it will not make it the active
12407 window. It will change the color of the taskbar entry to indicate
12408 that the window has changed in some way. This is because Microsoft
12409 does not allow an application to interrupt what the user is currently
12410 doing in another application.
12412 \sa isActiveWindow(), window(), show()
12416 \fn int QWidget::metric(PaintDeviceMetric m) const
12418 Internal implementation of the virtual QPaintDevice::metric()
12421 \a m is the metric to get.
12424 void QWidget::init(QPainter *painter) const
12426 const QPalette &pal = palette();
12427 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
12428 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
12429 QFont f(font(), const_cast<QWidget *>(this));
12430 painter->d_func()->state->deviceFont = f;
12431 painter->d_func()->state->font = f;
12434 QPaintDevice *QWidget::redirected(QPoint *offset) const
12436 return d_func()->redirected(offset);
12439 QPainter *QWidget::sharedPainter() const
12441 // Someone sent a paint event directly to the widget
12442 if (!d_func()->redirectDev)
12445 QPainter *sp = d_func()->sharedPainter();
12446 if (!sp || !sp->isActive())
12449 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
12456 \fn void QWidget::setMask(const QRegion ®ion)
12459 Causes only the parts of the widget which overlap \a region to be
12460 visible. If the region includes pixels outside the rect() of the
12461 widget, window system controls in that area may or may not be
12462 visible, depending on the platform.
12464 Note that this effect can be slow if the region is particularly
12469 void QWidget::setMask(const QRegion &newMask)
12474 if (newMask == d->extra->mask)
12477 #ifndef QT_NO_BACKINGSTORE
12478 const QRegion oldMask(d->extra->mask);
12481 d->extra->mask = newMask;
12482 d->extra->hasMask = !newMask.isEmpty();
12484 #ifndef QT_MAC_USE_COCOA
12485 if (!testAttribute(Qt::WA_WState_Created))
12489 d->setMask_sys(newMask);
12491 #ifndef QT_NO_BACKINGSTORE
12495 if (!d->extra->hasMask) {
12496 // Mask was cleared; update newly exposed area.
12497 QRegion expose(rect());
12499 if (!expose.isEmpty()) {
12500 d->setDirtyOpaqueRegion();
12507 // Update newly exposed area on the parent widget.
12508 QRegion parentExpose(rect());
12509 parentExpose -= newMask;
12510 if (!parentExpose.isEmpty()) {
12511 d->setDirtyOpaqueRegion();
12512 parentExpose.translate(data->crect.topLeft());
12513 parentWidget()->update(parentExpose);
12516 // Update newly exposed area on this widget
12517 if (!oldMask.isEmpty())
12518 update(newMask - oldMask);
12524 \fn void QWidget::setMask(const QBitmap &bitmap)
12526 Causes only the pixels of the widget for which \a bitmap has a
12527 corresponding 1 bit to be visible. If the region includes pixels
12528 outside the rect() of the widget, window system controls in that
12529 area may or may not be visible, depending on the platform.
12531 Note that this effect can be slow if the region is particularly
12534 The following code shows how an image with an alpha channel can be
12535 used to generate a mask for a widget:
12537 \snippet doc/src/snippets/widget-mask/main.cpp 0
12539 The label shown by this code is masked using the image it contains,
12540 giving the appearance that an irregularly-shaped image is being drawn
12541 directly onto the screen.
12543 Masked widgets receive mouse events only on their visible
12546 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
12548 void QWidget::setMask(const QBitmap &bitmap)
12550 setMask(QRegion(bitmap));
12554 \fn void QWidget::clearMask()
12556 Removes any mask set by setMask().
12560 void QWidget::clearMask()
12562 setMask(QRegion());
12565 /*! \fn const QX11Info &QWidget::x11Info() const
12566 Returns information about the configuration of the X display used to display
12569 \warning This function is only available on X11.
12572 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
12573 Returns the X11 Picture handle of the widget for XRender
12574 support. Use of this function is not portable. This function will
12575 return 0 if XRender support is not compiled into Qt, if the
12576 XRender extension is not supported on the X11 display, or if the
12577 handle could not be created.
12580 #ifdef Q_OS_SYMBIAN
12581 void QWidgetPrivate::_q_delayedDestroy(WId winId)
12587 #if QT_MAC_USE_COCOA
12588 void QWidgetPrivate::syncUnifiedMode() {
12589 // The whole purpose of this method is to keep the unifiedToolbar in sync.
12590 // That means making sure we either exchange the drawing methods or we let
12591 // the toolbar know that it does not require to draw the baseline.
12593 // This function makes sense only if this is a top level
12596 OSWindowRef window = qt_mac_window_for(q);
12597 if(changeMethods) {
12598 // Ok, we are in documentMode.
12599 if(originalDrawMethod)
12600 qt_mac_replaceDrawRect(window, this);
12602 if(!originalDrawMethod)
12603 qt_mac_replaceDrawRectOriginal(window, this);
12607 #endif // QT_MAC_USE_COCOA
12611 #include "moc_qwidget.cpp"