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::inputContext() const
378 return qApp->inputContext();
385 This function returns the QInputContext for this widget. By
386 default the input context is inherited from the widgets
387 parent. For toplevels it is inherited from QApplication.
389 You can override this and set a special input context for this
390 widget by using the setInputContext() method.
392 \sa setInputContext()
394 QInputContext *QWidget::inputContext()
397 if (!testAttribute(Qt::WA_InputMethodEnabled))
400 return d->inputContext();
403 #ifdef QT_KEYPAD_NAVIGATION
404 QPointer<QWidget> QWidgetPrivate::editingWidget;
407 Returns true if this widget currently has edit focus; otherwise false.
409 This feature is only available in Qt for Embedded Linux.
411 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
413 bool QWidget::hasEditFocus() const
415 const QWidget* w = this;
416 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
417 w = w->d_func()->extra->focus_proxy;
418 return QWidgetPrivate::editingWidget == w;
422 \fn void QWidget::setEditFocus(bool enable)
424 If \a enable is true, make this widget have edit focus, in which
425 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
426 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
429 This feature is only available in Qt for Embedded Linux and Qt
432 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
434 void QWidget::setEditFocus(bool on)
437 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
438 f = f->d_func()->extra->focus_proxy;
440 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
441 QWidgetPrivate::editingWidget->setEditFocus(false);
443 if (on && !f->hasFocus())
446 if ((!on && !QWidgetPrivate::editingWidget)
447 || (on && QWidgetPrivate::editingWidget == f)) {
451 if (!on && QWidgetPrivate::editingWidget == f) {
452 QWidgetPrivate::editingWidget = 0;
453 QEvent event(QEvent::LeaveEditFocus);
454 QApplication::sendEvent(f, &event);
455 QApplication::sendEvent(f->style(), &event);
457 QWidgetPrivate::editingWidget = f;
458 QEvent event(QEvent::EnterEditFocus);
459 QApplication::sendEvent(f, &event);
460 QApplication::sendEvent(f->style(), &event);
466 \property QWidget::autoFillBackground
467 \brief whether the widget background is filled automatically
470 If enabled, this property will cause Qt to fill the background of the
471 widget before invoking the paint event. The color used is defined by the
472 QPalette::Window color role from the widget's \l{QPalette}{palette}.
474 In addition, Windows are always filled with QPalette::Window, unless the
475 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
477 This property cannot be turned off (i.e., set to false) if a widget's
478 parent has a static gradient for its background.
480 \warning Use this property with caution in conjunction with
481 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
482 background or a border-image, this property is automatically disabled.
484 By default, this property is false.
486 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
487 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
489 bool QWidget::autoFillBackground() const
492 return d->extra && d->extra->autoFillBackground;
495 void QWidget::setAutoFillBackground(bool enabled)
500 if (d->extra->autoFillBackground == enabled)
503 d->extra->autoFillBackground = enabled;
511 \brief The QWidget class is the base class of all user interface objects.
513 \ingroup basicwidgets
515 The widget is the atom of the user interface: it receives mouse, keyboard
516 and other events from the window system, and paints a representation of
517 itself on the screen. Every widget is rectangular, and they are sorted in a
518 Z-order. A widget is clipped by its parent and by the widgets in front of
521 A widget that is not embedded in a parent widget is called a window.
522 Usually, windows have a frame and a title bar, although it is also possible
523 to create windows without such decoration using suitable
524 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
525 subclasses of QDialog are the most common window types.
527 Every widget's constructor accepts one or two standard arguments:
530 \i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
531 (the default), the new widget will be a window. If not, it will be
532 a child of \e parent, and be constrained by \e parent's geometry
533 (unless you specify Qt::Window as window flag).
534 \i \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
535 the default is suitable for almost all widgets, but to get, for
536 example, a window without a window system frame, you must use
540 QWidget has many member functions, but some of them have little direct
541 functionality; for example, QWidget has a font property, but never uses
542 this itself. There are many subclasses which provide real functionality,
543 such as QLabel, QPushButton, QListWidget, and QTabWidget.
546 \section1 Top-Level and Child Widgets
548 A widget without a parent widget is always an independent window (top-level
549 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
550 title bar and icon respectively.
552 Non-window widgets are child widgets, displayed within their parent
553 widgets. Most widgets in Qt are mainly useful as child widgets. For
554 example, it is possible to display a button as a top-level window, but most
555 people prefer to put their buttons inside other widgets, such as QDialog.
557 \image parent-child-widgets.png A parent widget containing various child widgets.
559 The diagram above shows a QGroupBox widget being used to hold various child
560 widgets in a layout provided by QGridLayout. The QLabel child widgets have
561 been outlined to indicate their full sizes.
563 If you want to use a QWidget to hold child widgets you will usually want to
564 add a layout to the parent QWidget. See \l{Layout Management} for more
568 \section1 Composite Widgets
570 When a widget is used as a container to group a number of child widgets, it
571 is known as a composite widget. These can be created by constructing a
572 widget with the required visual properties - a QFrame, for example - and
573 adding child widgets to it, usually managed by a layout. The above diagram
574 shows such a composite widget that was created using \l{Qt Designer}.
576 Composite widgets can also be created by subclassing a standard widget,
577 such as QWidget or QFrame, and adding the necessary layout and child
578 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
579 {examples provided with Qt} use this approach, and it is also covered in
580 the Qt \l{Tutorials}.
583 \section1 Custom Widgets and Painting
585 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
586 display custom content that is composed using a series of painting
587 operations with an instance of the QPainter class. This approach contrasts
588 with the canvas-style approach used by the \l{Graphics View}
589 {Graphics View Framework} where items are added to a scene by the
590 application and are rendered by the framework itself.
592 Each widget performs all painting operations from within its paintEvent()
593 function. This is called whenever the widget needs to be redrawn, either
594 as a result of some external change or when requested by the application.
596 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
597 can handle paint events.
600 \section1 Size Hints and Size Policies
602 When implementing a new widget, it is almost always useful to reimplement
603 sizeHint() to provide a reasonable default size for the widget and to set
604 the correct size policy with setSizePolicy().
606 By default, composite widgets which do not provide a size hint will be
607 sized according to the space requirements of their child widgets.
609 The size policy lets you supply good default behavior for the layout
610 management system, so that other widgets can contain and manage yours
611 easily. The default size policy indicates that the size hint represents
612 the preferred size of the widget, and this is often good enough for many
615 \note The size of top-level widgets are constrained to 2/3 of the desktop's
616 height and width. You can resize() the widget manually if these bounds are
622 Widgets respond to events that are typically caused by user actions. Qt
623 delivers events to widgets by calling specific event handler functions with
624 instances of QEvent subclasses containing information about each event.
626 If your widget only contains child widgets, you probably do not need to
627 implement any event handlers. If you want to detect a mouse click in a
628 child widget call the child's underMouse() function inside the widget's
631 The \l{widgets/scribble}{Scribble example} implements a wider set of
632 events to handle mouse movement, button presses, and window resizing.
634 You will need to supply the behavior and content for your own widgets, but
635 here is a brief overview of the events that are relevant to QWidget,
636 starting with the most common ones:
639 \i paintEvent() is called whenever the widget needs to be repainted.
640 Every widget displaying custom content must implement it. Painting
641 using a QPainter can only take place in a paintEvent() or a
642 function called by a paintEvent().
643 \i resizeEvent() is called when the widget has been resized.
644 \i mousePressEvent() is called when a mouse button is pressed while
645 the mouse cursor is inside the widget, or when the widget has
646 grabbed the mouse using grabMouse(). Pressing the mouse without
647 releasing it is effectively the same as calling grabMouse().
648 \i mouseReleaseEvent() is called when a mouse button is released. A
649 widget receives mouse release events when it has received the
650 corresponding mouse press event. This means that if the user
651 presses the mouse inside \e your widget, then drags the mouse
652 somewhere else before releasing the mouse button, \e your widget
653 receives the release event. There is one exception: if a popup menu
654 appears while the mouse button is held down, this popup immediately
655 steals the mouse events.
656 \i mouseDoubleClickEvent() is called when the user double-clicks in
657 the widget. If the user double-clicks, the widget receives a mouse
658 press event, a mouse release event and finally this event instead
659 of a second mouse press event. (Some mouse move events may also be
660 received if the mouse is not held steady during this operation.) It
661 is \e{not possible} to distinguish a click from a double-click
662 until the second click arrives. (This is one reason why most GUI
663 books recommend that double-clicks be an extension of
664 single-clicks, rather than trigger a different action.)
667 Widgets that accept keyboard input need to reimplement a few more event
671 \i keyPressEvent() is called whenever a key is pressed, and again when
672 a key has been held down long enough for it to auto-repeat. The
673 \key Tab and \key Shift+Tab keys are only passed to the widget if
674 they are not used by the focus-change mechanisms. To force those
675 keys to be processed by your widget, you must reimplement
677 \i focusInEvent() is called when the widget gains keyboard focus
678 (assuming you have called setFocusPolicy()). Well-behaved widgets
679 indicate that they own the keyboard focus in a clear but discreet
681 \i focusOutEvent() is called when the widget loses keyboard focus.
684 You may be required to also reimplement some of the less common event
688 \i mouseMoveEvent() is called whenever the mouse moves while a mouse
689 button is held down. This can be useful during drag and drop
690 operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
691 you get mouse move events even when no buttons are held down.
692 (See also the \l{Drag and Drop} guide.)
693 \i keyReleaseEvent() is called whenever a key is released and while it
694 is held down (if the key is auto-repeating). In that case, the
695 widget will receive a pair of key release and key press event for
696 every repeat. The \key Tab and \key Shift+Tab keys are only passed
697 to the widget if they are not used by the focus-change mechanisms.
698 To force those keys to be processed by your widget, you must
699 reimplement QWidget::event().
700 \i wheelEvent() is called whenever the user turns the mouse wheel
701 while the widget has the focus.
702 \i enterEvent() is called when the mouse enters the widget's screen
703 space. (This excludes screen space owned by any of the widget's
705 \i leaveEvent() is called when the mouse leaves the widget's screen
706 space. If the mouse enters a child widget it will not cause a
708 \i moveEvent() is called when the widget has been moved relative to
710 \i closeEvent() is called when the user closes the widget (or when
714 There are also some rather obscure events described in the documentation
715 for QEvent::Type. To handle these events, you need to reimplement event()
718 The default implementation of event() handles \key Tab and \key Shift+Tab
719 (to move the keyboard focus), and passes on most of the other events to
720 one of the more specialized handlers above.
722 Events and the mechanism used to deliver them are covered in
723 \l{The Event System}.
725 \section1 Groups of Functions and Properties
728 \header \i Context \i Functions and Properties
730 \row \i Window functions \i
737 \row \i Top-level windows \i
738 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
739 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
740 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
743 \row \i Window contents \i
749 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
750 \l sizePolicy, sizeHint(), minimumSizeHint(),
751 updateGeometry(), layout(),
752 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
754 mapFromGlobal(), mapToGlobal(),
755 mapFromParent(), mapToParent(),
756 \l maximumSize, \l minimumSize, \l sizeIncrement,
757 \l baseSize, setFixedSize()
760 \l visible, isVisibleTo(),
761 \l enabled, isEnabledTo(),
768 \row \i Look and feel \i
775 backgroundRole(), setBackgroundRole(),
776 fontInfo(), fontMetrics().
778 \row \i Keyboard focus functions \i
779 \l focus, \l focusPolicy,
780 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
781 focusNextChild(), focusPreviousChild().
783 \row \i Mouse and keyboard grabbing \i
784 grabMouse(), releaseMouse(),
785 grabKeyboard(), releaseKeyboard(),
786 mouseGrabber(), keyboardGrabber().
788 \row \i Event handlers \i
792 mouseDoubleClickEvent(),
815 \row \i System functions \i
816 parentWidget(), window(), setParent(), winId(),
819 \row \i Interactive help \i
820 setToolTip(), setWhatsThis()
825 \section1 Widget Style Sheets
827 In addition to the standard widget styles for each platform, widgets can
828 also be styled according to rules specified in a \l{styleSheet}
829 {style sheet}. This feature enables you to customize the appearance of
830 specific widgets to provide visual cues to users about their purpose. For
831 example, a button could be styled in a particular way to indicate that it
832 performs a destructive action.
834 The use of widget style sheets is described in more detail in the
835 \l{Qt Style Sheets} document.
838 \section1 Transparency and Double Buffering
840 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
841 is no need to write double-buffering code in paintEvent() to avoid
844 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
845 deprecated. Instead, the contents of parent widgets are propagated by
846 default to each of their children as long as Qt::WA_PaintOnScreen is not
847 set. Custom widgets can be written to take advantage of this feature by
848 updating irregular regions (to create non-rectangular child widgets), or
849 painting with colors that have less than full alpha component. The
850 following diagram shows how attributes and properties of a custom widget
851 can be fine-tuned to achieve different effects.
853 \image propagation-custom.png
855 In the above diagram, a semi-transparent rectangular child widget with an
856 area removed is constructed and added to a parent widget (a QLabel showing
857 a pixmap). Then, different properties and widget attributes are set to
858 achieve different effects:
861 \i The left widget has no additional properties or widget attributes
862 set. This default state suits most custom widgets using
863 transparency, are irregularly-shaped, or do not paint over their
864 entire area with an opaque brush.
865 \i The center widget has the \l autoFillBackground property set. This
866 property is used with custom widgets that rely on the widget to
867 supply a default background, and do not paint over their entire
868 area with an opaque brush.
869 \i The right widget has the Qt::WA_OpaquePaintEvent widget attribute
870 set. This indicates that the widget will paint over its entire area
871 with opaque colors. The widget's area will initially be
872 \e{uninitialized}, represented in the diagram with a red diagonal
873 grid pattern that shines through the overpainted area. The
874 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
875 paint their own specialized contents quickly and do not need a
876 default filled background.
879 To rapidly update custom widgets with simple background colors, such as
880 real-time plotting or graphing widgets, it is better to define a suitable
881 background color (using setBackgroundRole() with the
882 QPalette::Window role), set the \l autoFillBackground property, and only
883 implement the necessary drawing functionality in the widget's paintEvent().
885 To rapidly update custom widgets that constantly paint over their entire
886 areas with opaque content, e.g., video streaming widgets, it is better to
887 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
888 associated with repainting the widget's background.
890 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
891 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
892 attribute takes precedence. Depending on your requirements, you should
893 choose either one of them.
895 Since Qt 4.1, the contents of parent widgets are also propagated to
896 standard Qt widgets. This can lead to some unexpected results if the
897 parent widget is decorated in a non-standard way, as shown in the diagram
900 \image propagation-standard.png
902 The scope for customizing the painting behavior of standard Qt widgets,
903 without resorting to subclassing, is slightly less than that possible for
904 custom widgets. Usually, the desired appearance of a standard widget can be
905 achieved by setting its \l autoFillBackground property.
908 \section1 Creating Translucent Windows
910 Since Qt 4.5, it has been possible to create windows with translucent regions
911 on window systems that support compositing.
913 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
914 attribute with setAttribute() and ensure that its background is painted with
915 non-opaque colors in the regions you want to be partially transparent.
920 \o X11: This feature relies on the use of an X server that supports ARGB visuals
921 and a compositing window manager.
922 \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
923 for the translucency to work.
927 \section1 Native Widgets vs Alien Widgets
929 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
930 system. They do not have a native window handle associated with them. This
931 feature significantly speeds up widget painting, resizing, and removes flicker.
933 Should you require the old behavior with native windows, you can choose
934 one of the following options:
937 \i Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
938 \i Set the Qt::AA_NativeWindows attribute on your application. All
939 widgets will be native widgets.
940 \i Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
941 and all of its ancestors will become native (unless
942 Qt::WA_DontCreateNativeAncestors is set).
943 \i Call QWidget::winId to enforce a native window (this implies 3).
944 \i Set the Qt::WA_PaintOnScreen attribute to enforce a native window
948 \sa QEvent, QPainter, QGridLayout, QBoxLayout
952 Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
953 other visual representation on the screen that is generally located next to its
954 physical counterpart. They are most often found on mobile phone platforms. In
955 modern touch based user interfaces it is also possible to have softkeys that do
956 not correspond to any physical keys. Softkeys differ from other onscreen labels
957 in that they are contextual.
959 In Qt, contextual softkeys are added to a widget by calling addAction() and
960 passing a \c QAction with a softkey role set on it. When the widget
961 containing the softkey actions has focus, its softkeys should appear in
962 the user interface. Softkeys are discovered by traversing the widget
963 hierarchy so it is possible to define a single set of softkeys that are
964 present at all times by calling addAction() for a given top level widget.
966 On some platforms, this concept overlaps with \c QMenuBar such that if no
967 other softkeys are found and the top level widget is a QMainWindow containing
968 a QMenuBar, the menubar actions may appear on one of the softkeys.
970 Note: Currently softkeys are only supported on the Symbian Platform.
972 \sa addAction(), QAction, QMenuBar
976 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
977 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
980 /*****************************************************************************
981 QWidget utility functions
982 *****************************************************************************/
984 QRegion qt_dirtyRegion(QWidget *widget)
989 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
993 return bs->dirtyRegion(widget);
996 /*****************************************************************************
997 QWidget member functions
998 *****************************************************************************/
1003 \i Qt::WA_WState_Created The widget has a valid winId().
1004 \i Qt::WA_WState_Visible The widget is currently visible.
1005 \i Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
1006 become visible unless you call show() on it. Qt::WA_WState_Hidden
1007 implies !Qt::WA_WState_Visible.
1008 \i Qt::WA_WState_CompressKeys Compress keyboard events.
1009 \i Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
1010 \i Qt::WA_WState_InPaintEvent Currently processing a paint event.
1011 \i Qt::WA_WState_Reparented The widget has been reparented.
1012 \i Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
1013 \i Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
1017 struct QWidgetExceptionCleaner
1019 /* this cleans up when the constructor throws an exception */
1020 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
1022 #ifdef QT_NO_EXCEPTIONS
1026 QWidgetPrivate::allWidgets->remove(that);
1027 if (d->focus_next != that) {
1029 d->focus_next->d_func()->focus_prev = d->focus_prev;
1031 d->focus_prev->d_func()->focus_next = d->focus_next;
1038 Constructs a widget which is a child of \a parent, with widget
1041 If \a parent is 0, the new widget becomes a window. If
1042 \a parent is another widget, this widget becomes a child window
1043 inside \a parent. The new widget is deleted when its \a parent is
1046 The widget flags argument, \a f, is normally 0, but it can be set
1047 to customize the frame of a window (i.e. \a
1048 parent must be 0). To customize the frame, use a value composed
1049 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1051 If you add a child widget to an already visible widget you must
1052 explicitly show the child to make it visible.
1054 Note that the X11 version of Qt may not be able to deliver all
1055 combinations of style flags on all systems. This is because on
1056 X11, Qt can only ask the window manager, and the window manager
1057 can override the application's settings. On Windows, Qt can set
1058 whatever flags you want.
1062 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1063 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1066 d_func()->init(parent, f);
1068 QWidgetExceptionCleaner::cleanup(this, d_func());
1076 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1077 : QObject(dd, 0), QPaintDevice()
1083 QWidgetExceptionCleaner::cleanup(this, d_func());
1091 int QWidget::devType() const
1093 return QInternal::Widget;
1097 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1098 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1100 bool customize = (flags & (Qt::CustomizeWindowHint
1101 | Qt::FramelessWindowHint
1102 | Qt::WindowTitleHint
1103 | Qt::WindowSystemMenuHint
1104 | Qt::WindowMinimizeButtonHint
1105 | Qt::WindowMaximizeButtonHint
1106 | Qt::WindowCloseButtonHint
1107 | Qt::WindowContextHelpButtonHint));
1109 uint type = (flags & Qt::WindowType_Mask);
1111 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1113 flags |= Qt::Window;
1116 if (flags & Qt::CustomizeWindowHint) {
1117 // modify window flags to make them consistent.
1118 // Only enable this on non-Mac platforms. Since the old way of doing this would
1119 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1120 // we can't just add this in.
1122 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1123 flags |= Qt::WindowSystemMenuHint;
1125 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1126 | Qt::WindowSystemMenuHint)) {
1128 flags |= Qt::WindowTitleHint;
1129 flags &= ~Qt::FramelessWindowHint;
1131 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1132 // if any of the window hints that affect the titlebar are set
1133 // and the window is supposed to have frame, we add a titlebar
1134 // and system menu by default.
1135 flags |= Qt::WindowSystemMenuHint;
1136 flags |= Qt::WindowTitleHint;
1139 ; // don't modify window flags if the user explicitly set them.
1140 else if (type == Qt::Dialog || type == Qt::Sheet)
1142 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1144 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1146 else if (type == Qt::Tool)
1147 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1149 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1154 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1157 if (QApplication::type() == QApplication::Tty)
1158 qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1160 Q_ASSERT(allWidgets);
1162 allWidgets->insert(q);
1164 QWidget *desktopWidget = 0;
1165 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1166 desktopWidget = parentWidget;
1172 #ifndef QT_NO_THREAD
1174 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1175 "Widgets must be created in the GUI thread.");
1179 #if defined(Q_WS_X11)
1180 if (desktopWidget) {
1181 // make sure the widget is created on the same screen as the
1182 // programmer specified desktop widget
1183 xinfo = desktopWidget->d_func()->xinfo;
1185 #elif defined(Q_OS_SYMBIAN)
1186 if (desktopWidget) {
1187 symbianScreenNumber = qt_widget_private(desktopWidget)->symbianScreenNumber;
1189 #elif defined(Q_WS_QPA)
1190 if (desktopWidget) {
1191 int screen = desktopWidget->d_func()->topData()->screenIndex;
1192 q->windowHandle()->setScreen(QGuiApplication::screens().value(screen, 0));
1195 Q_UNUSED(desktopWidget);
1198 data.fstrut_dirty = true;
1201 data.widget_attributes = 0;
1202 data.window_flags = f;
1203 data.window_state = 0;
1204 data.focus_policy = 0;
1205 data.context_menu_policy = Qt::DefaultContextMenu;
1206 data.window_modality = Qt::NonModal;
1208 data.sizehint_forced = 0;
1209 data.is_closing = 0;
1211 data.in_set_window_state = 0;
1212 data.in_destructor = false;
1214 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1215 if (f & Qt::MSWindowsOwnDC)
1216 q->setAttribute(Qt::WA_NativeWindow);
1219 // q->setAttribute(Qt::WA_NativeWindow);
1222 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1223 adjustQuitOnCloseAttribute();
1225 q->setAttribute(Qt::WA_WState_Hidden);
1227 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1230 // Don't waste GPU mem for unnecessary large egl surface until resized by application
1231 data.crect = QRect(0,0,1,1);
1233 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,360,640);
1236 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1239 focus_next = focus_prev = q;
1241 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1243 else if (parentWidget)
1244 q->setParent(parentWidget, data.window_flags);
1246 adjustFlags(data.window_flags, q);
1247 resolveLayoutDirection();
1248 // opaque system background?
1249 const QBrush &background = q->palette().brush(QPalette::Window);
1250 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1252 data.fnt = QFont(data.fnt, q);
1253 #if defined(Q_WS_X11)
1254 data.fnt.x11SetScreen(xinfo.screen());
1257 q->setAttribute(Qt::WA_PendingMoveEvent);
1258 q->setAttribute(Qt::WA_PendingResizeEvent);
1260 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1261 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1263 if (QApplicationPrivate::app_compile_version < 0x040200
1264 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1268 QEvent e(QEvent::Create);
1269 QApplication::sendEvent(q, &e);
1270 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1272 extraPaintEngine = 0;
1274 #ifdef QT_MAC_USE_COCOA
1275 // If we add a child to the unified toolbar, we have to redirect the painting.
1276 if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1277 if (parentWidget->d_func()->unifiedSurface) {
1278 QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1279 parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1282 #endif // QT_MAC_USE_COCOA
1287 void QWidgetPrivate::createRecursively()
1290 q->create(0, true, true);
1291 for (int i = 0; i < children.size(); ++i) {
1292 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1293 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1294 child->d_func()->createRecursively();
1302 Creates a new widget window if \a window is 0, otherwise sets the
1303 widget's window to \a window.
1305 Initializes the window (sets the geometry etc.) if \a
1306 initializeWindow is true. If \a initializeWindow is false, no
1307 initialization is performed. This parameter only makes sense if \a
1308 window is a valid window.
1310 Destroys the old window if \a destroyOldWindow is true. If \a
1311 destroyOldWindow is false, you are responsible for destroying the
1312 window yourself (using platform native code).
1314 The QWidget constructor calls create(0,true,true) to create a
1315 window for this widget.
1318 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1321 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1324 if (d->data.in_destructor)
1327 Qt::WindowType type = windowType();
1328 Qt::WindowFlags &flags = data->window_flags;
1330 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1332 flags |= Qt::Window;
1335 if (QWidget *parent = parentWidget()) {
1336 if (type & Qt::Window) {
1337 if (!parent->testAttribute(Qt::WA_WState_Created))
1338 parent->createWinId();
1339 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1340 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1341 // We're about to create a native child widget that doesn't have a native parent;
1342 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1343 // attribute is set.
1344 d->createWinId(window);
1345 // Nothing more to do.
1346 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1347 Q_ASSERT(internalWinId());
1353 static int paintOnScreenEnv = -1;
1354 if (paintOnScreenEnv == -1)
1355 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1356 if (paintOnScreenEnv == 1)
1357 setAttribute(Qt::WA_PaintOnScreen);
1359 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1360 setAttribute(Qt::WA_NativeWindow);
1363 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1364 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1367 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1368 // Unregister the dropsite (if already registered) before we
1369 // re-create the widget with a native window.
1370 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1371 && d->extra && d->extra->dropTarget) {
1372 d->registerDropSite(false);
1374 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1376 d->updateIsOpaque();
1378 setAttribute(Qt::WA_WState_Created); // set created flag
1379 d->create_sys(window, initializeWindow, destroyOldWindow);
1381 // a real toplevel window needs a backing store
1382 if (isWindow() && windowType() != Qt::Desktop) {
1383 d->topData()->backingStoreTracker.destroy();
1384 if (hasBackingStoreSupport())
1385 d->topData()->backingStoreTracker.create(this);
1390 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1391 setAttribute(Qt::WA_DropSiteRegistered, true);
1394 extern void qt_eval_init_widget(QWidget *w);
1395 qt_eval_init_widget(this);
1398 // need to force the resting of the icon after changing parents
1399 if (testAttribute(Qt::WA_SetWindowIcon))
1400 d->setWindowIcon_sys(true);
1401 if (isWindow() && !d->topData()->iconText.isEmpty())
1402 d->setWindowIconText_helper(d->topData()->iconText);
1403 if (isWindow() && !d->topData()->caption.isEmpty())
1404 d->setWindowTitle_helper(d->topData()->caption);
1405 if (windowType() != Qt::Desktop) {
1406 d->updateSystemBackground();
1408 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1409 d->setWindowIcon_sys();
1414 Destroys the widget.
1416 All this widget's children are deleted first. The application
1417 exits if this widget is the main widget.
1423 d->data.in_destructor = true;
1425 #if defined (QT_CHECK_STATE)
1426 if (paintingActive())
1427 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1430 #ifndef QT_NO_GESTURES
1431 foreach (Qt::GestureType type, d->gestureContext.keys())
1432 ungrabGesture(type);
1435 // force acceptDrops false before winId is destroyed.
1436 d->registerDropSite(false);
1438 #ifndef QT_NO_ACTION
1439 // remove all actions from this widget
1440 for (int i = 0; i < d->actions.size(); ++i) {
1441 QActionPrivate *apriv = d->actions.at(i)->d_func();
1442 apriv->widgets.removeAll(this);
1447 #ifndef QT_NO_SHORTCUT
1448 // Remove all shortcuts grabbed by this
1449 // widget, unless application is closing
1450 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1451 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1454 // delete layout while we still are a valid widget
1457 // Remove myself from focus list
1459 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1460 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1462 if (d->focus_next != this) {
1463 d->focus_next->d_func()->focus_prev = d->focus_prev;
1464 d->focus_prev->d_func()->focus_next = d->focus_next;
1465 d->focus_next = d->focus_prev = 0;
1472 // swallow this problem because we are in a destructor
1475 d->setDirtyOpaqueRegion();
1477 if (isWindow() && isVisible() && internalWinId()) {
1479 d->close_helper(QWidgetPrivate::CloseNoEvent);
1481 // if we're out of memory, at least hide the window.
1485 // and if that also doesn't work, then give up
1490 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1491 else if (!internalWinId() && isVisible()) {
1492 qApp->d_func()->sendSyntheticEnterLeave(this);
1494 #elif defined(Q_WS_QPA)
1495 else if (isVisible()) {
1496 qApp->d_func()->sendSyntheticEnterLeave(this);
1501 if (d->extra && d->extra->topextra && d->extra->topextra->backingStore) {
1502 // Okay, we are about to destroy the top-level window that owns
1503 // the backing store. Make sure we delete the backing store right away
1504 // before the window handle is invalid. This is important because
1505 // the backing store will delete its window surface, which may or may
1506 // not have a reference to this widget that will be used later to
1507 // notify the window it no longer has a surface.
1508 d->extra->topextra->backingStore.destroy();
1511 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1512 bs->removeDirtyWidget(this);
1513 if (testAttribute(Qt::WA_StaticContents))
1514 bs->removeStaticWidget(this);
1517 delete d->needsFlush;
1520 // set all QPointers for this object to zero
1522 QObjectPrivate::clearGuards(this);
1524 if (d->declarativeData) {
1525 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1526 d->declarativeData = 0; // don't activate again in ~QObject
1529 #ifdef QT_MAC_USE_COCOA
1530 // QCocoaView holds a pointer back to this widget. Clear it now
1531 // to make sure it's not followed later on. The lifetime of the
1532 // QCocoaView might exceed the lifetime of this widget in cases
1533 // where Cocoa itself holds references to it.
1534 extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1535 qt_mac_clearCocoaViewQWidgetPointers(this);
1538 if (!d->children.isEmpty())
1539 d->deleteChildren();
1541 QApplication::removePostedEvents(this);
1544 destroy(); // platform-dependent cleanup
1546 // if this fails we can't do anything about it but at least we are not allowed to throw.
1548 --QWidgetPrivate::instanceCounter;
1550 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1551 QWidgetPrivate::allWidgets->remove(this);
1554 QEvent e(QEvent::Destroy);
1555 QCoreApplication::sendEvent(this, &e);
1556 } QT_CATCH(const std::exception&) {
1557 // if this fails we can't do anything about it but at least we are not allowed to throw.
1561 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1562 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1564 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1567 // the user might create a widget with Qt::Desktop window
1568 // attribute (or create another QDesktopWidget instance), which
1569 // will have the same windowid (the root window id) as the
1570 // qt_desktopWidget. We should not add the second desktop widget
1572 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1573 if (mapper && data.winid && !userDesktopWidget) {
1574 mapper->remove(data.winid);
1577 const WId oldWinId = data.winid;
1580 #if defined(Q_WS_X11)
1581 hd = id; // X11: hd == ident
1583 if (mapper && id && !userDesktopWidget) {
1584 mapper->insert(data.winid, q);
1587 if(oldWinId != id) {
1588 QEvent e(QEvent::WinIdChange);
1589 QCoreApplication::sendEvent(q, &e);
1593 void QWidgetPrivate::createTLExtra()
1597 if (!extra->topextra) {
1598 QTLWExtra* x = extra->topextra = new QTLWExtra;
1601 x->backingStore = 0;
1602 x->sharedPainter = 0;
1603 x->incw = x->inch = 0;
1604 x->basew = x->baseh = 0;
1605 x->frameStrut.setCoords(0, 0, 0, 0);
1606 x->normalGeometry = QRect(0,0,-1,-1);
1609 x->posFromMove = false;
1610 x->sizeAdjusted = false;
1611 x->inTopLevelResize = false;
1612 x->inRepaint = false;
1615 #ifdef QT_MAC_USE_COCOA
1616 x->wasMaximized = false;
1617 #endif // QT_MAC_USE_COCOA
1620 #ifdef QWIDGET_EXTRA_DEBUG
1621 static int count = 0;
1622 qDebug() << "tlextra" << ++count;
1629 Creates the widget extra data.
1632 void QWidgetPrivate::createExtra()
1634 if (!extra) { // if not exists
1635 extra = new QWExtra;
1636 extra->glContext = 0;
1637 extra->topextra = 0;
1638 #ifndef QT_NO_GRAPHICSVIEW
1639 extra->proxyWidget = 0;
1641 #ifndef QT_NO_CURSOR
1646 extra->maxw = QWIDGETSIZE_MAX;
1647 extra->maxh = QWIDGETSIZE_MAX;
1648 extra->customDpiX = 0;
1649 extra->customDpiY = 0;
1650 extra->explicitMinSize = 0;
1651 extra->explicitMaxSize = 0;
1652 extra->autoFillBackground = 0;
1653 extra->nativeChildrenForced = 0;
1654 extra->inRenderWithPainter = 0;
1657 #ifdef QWIDGET_EXTRA_DEBUG
1658 static int count = 0;
1659 qDebug() << "extra" << ++count;
1667 Deletes the widget extra data.
1670 void QWidgetPrivate::deleteExtra()
1672 if (extra) { // if exists
1673 #ifndef QT_NO_CURSOR
1677 #ifndef QT_NO_STYLE_STYLESHEET
1678 // dereference the stylesheet style
1679 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1682 if (extra->topextra) {
1684 extra->topextra->backingStoreTracker.destroy();
1685 delete extra->topextra->icon;
1686 delete extra->topextra->iconPixmap;
1687 delete extra->topextra->backingStore;
1688 delete extra->topextra;
1691 // extra->xic destroyed in QWidget::destroy()
1697 Returns true if there are widgets above this which overlap with
1698 \a rect, which is in parent's coordinate system (same as crect).
1701 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1705 const QWidget *w = q;
1710 QWidgetPrivate *pd = w->parentWidget()->d_func();
1712 for (int i = 0; i < pd->children.size(); ++i) {
1713 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1714 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1717 above = (sibling == w);
1721 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1722 const QWExtra *siblingExtra = sibling->d_func()->extra;
1723 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1724 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1730 w = w->parentWidget();
1731 r.translate(pd->data.crect.topLeft());
1736 void QWidgetPrivate::syncBackingStore()
1738 if (paintOnScreen()) {
1741 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1746 void QWidgetPrivate::syncBackingStore(const QRegion ®ion)
1748 if (paintOnScreen())
1749 repaint_sys(region);
1750 else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1751 bs->sync(q_func(), region);
1755 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1759 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1760 return; // nothing we can do
1762 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1763 return; // nothing to do
1765 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1769 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1770 for (int i = 0; i < children.size(); ++i) {
1771 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1772 if (w && !w->isWindow() && !w->testAttribute(attribute))
1773 w->d_func()->setUpdatesEnabled_helper(enable);
1780 Propagate this widget's palette to all children, except style sheet
1781 widgets, and windows that don't enable window propagation (palettes don't
1782 normally propagate to windows).
1784 void QWidgetPrivate::propagatePaletteChange()
1787 // Propagate a new inherited mask to all children.
1788 #ifndef QT_NO_GRAPHICSVIEW
1789 if (!q->parentWidget() && extra && extra->proxyWidget) {
1790 QGraphicsProxyWidget *p = extra->proxyWidget;
1791 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1793 #endif //QT_NO_GRAPHICSVIEW
1794 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1795 inheritedPaletteResolveMask = 0;
1797 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1799 QEvent pc(QEvent::PaletteChange);
1800 QApplication::sendEvent(q, &pc);
1801 for (int i = 0; i < children.size(); ++i) {
1802 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1803 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1804 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1805 QWidgetPrivate *wd = w->d_func();
1806 wd->inheritedPaletteResolveMask = mask;
1807 wd->resolvePalette();
1810 #if defined(QT3_SUPPORT)
1811 q->paletteChange(q->palette()); // compatibility
1816 Returns the widget's clipping rectangle.
1818 QRect QWidgetPrivate::clipRect() const
1821 const QWidget * w = q;
1822 if (!w->isVisible())
1824 QRect r = effectiveRectFor(q->rect());
1830 && w->parentWidget()) {
1833 w = w->parentWidget();
1834 r &= QRect(ox, oy, w->width(), w->height());
1840 Returns the widget's clipping region (without siblings).
1842 QRegion QWidgetPrivate::clipRegion() const
1845 if (!q->isVisible())
1847 QRegion r(q->rect());
1848 const QWidget * w = q;
1849 const QWidget *ignoreUpTo;
1855 && w->parentWidget()) {
1859 w = w->parentWidget();
1860 r &= QRegion(ox, oy, w->width(), w->height());
1863 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1865 for ( ; i < w->d_func()->children.size(); ++i) {
1866 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1867 if(sibling->isVisible() && !sibling->isWindow()) {
1868 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1869 sibling->width(), sibling->height());
1870 if (qRectIntersects(siblingRect, q->rect()))
1871 r -= QRegion(siblingRect);
1879 #ifndef QT_NO_GRAPHICSEFFECT
1880 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1885 if (w->graphicsEffect()) {
1886 QWidgetEffectSourcePrivate *sourced =
1887 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1888 if (!sourced->updateDueToGraphicsEffect)
1889 w->graphicsEffect()->source()->d_func()->invalidateCache();
1891 w = w->parentWidget();
1894 #endif //QT_NO_GRAPHICSEFFECT
1896 void QWidgetPrivate::setDirtyOpaqueRegion()
1900 dirtyOpaqueChildren = true;
1902 #ifndef QT_NO_GRAPHICSEFFECT
1903 invalidateGraphicsEffectsRecursively();
1904 #endif //QT_NO_GRAPHICSEFFECT
1909 QWidget *parent = q->parentWidget();
1913 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1914 QWidgetPrivate *pd = parent->d_func();
1915 if (!pd->dirtyOpaqueChildren)
1916 pd->setDirtyOpaqueRegion();
1919 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1921 if (!dirtyOpaqueChildren)
1922 return opaqueChildren;
1924 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1925 that->opaqueChildren = QRegion();
1927 for (int i = 0; i < children.size(); ++i) {
1928 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1929 if (!child || !child->isVisible() || child->isWindow())
1932 const QPoint offset = child->geometry().topLeft();
1933 QWidgetPrivate *childd = child->d_func();
1934 QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1935 if (childd->extra && childd->extra->hasMask)
1936 r &= childd->extra->mask;
1939 r.translate(offset);
1940 that->opaqueChildren += r;
1943 that->opaqueChildren &= q_func()->rect();
1944 that->dirtyOpaqueChildren = false;
1946 return that->opaqueChildren;
1949 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1951 if (children.isEmpty() || clipRect.isEmpty())
1954 const QRegion &r = getOpaqueChildren();
1956 source -= (r & clipRect);
1959 //subtract any relatives that are higher up than me --- this is too expensive !!!
1960 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1961 bool alsoNonOpaque) const
1964 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1965 if (disableSubtractOpaqueSiblings || q->isWindow())
1968 #ifdef QT_MAC_USE_COCOA
1969 if (q->d_func()->isInUnifiedToolbar)
1971 #endif // QT_MAC_USE_COCOA
1973 QRect clipBoundingRect;
1974 bool dirtyClipBoundingRect = true;
1977 bool dirtyParentClip = true;
1979 QPoint parentOffset = data.crect.topLeft();
1981 const QWidget *w = q;
1986 QWidgetPrivate *pd = w->parentWidget()->d_func();
1987 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1988 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1989 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1990 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1991 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1994 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1995 if (!qRectIntersects(siblingGeometry, widgetGeometry))
1998 if (dirtyClipBoundingRect) {
1999 clipBoundingRect = sourceRegion.boundingRect();
2000 dirtyClipBoundingRect = false;
2003 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
2006 if (dirtyParentClip) {
2007 parentClip = sourceRegion.translated(parentOffset);
2008 dirtyParentClip = false;
2011 const QPoint siblingPos(sibling->data->crect.topLeft());
2012 const QRect siblingClipRect(sibling->d_func()->clipRect());
2013 QRegion siblingDirty(parentClip);
2014 siblingDirty &= (siblingClipRect.translated(siblingPos));
2015 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
2016 && !sibling->d_func()->graphicsEffect;
2018 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
2019 if (siblingDirty.isEmpty())
2022 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
2024 siblingDirty.translate(-parentOffset);
2025 sourceRegion -= siblingDirty;
2027 sourceRegion -= siblingGeometry.translated(-parentOffset);
2030 if (hasDirtySiblingsAbove)
2031 *hasDirtySiblingsAbove = true;
2032 if (sibling->d_func()->children.isEmpty())
2034 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
2035 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
2036 sourceRegion -= opaqueSiblingChildren;
2038 if (sourceRegion.isEmpty())
2041 dirtyClipBoundingRect = true;
2042 dirtyParentClip = true;
2045 w = w->parentWidget();
2046 parentOffset += pd->data.crect.topLeft();
2047 dirtyParentClip = true;
2051 void QWidgetPrivate::clipToEffectiveMask(QRegion ®ion) const
2055 const QWidget *w = q;
2058 #ifndef QT_NO_GRAPHICSEFFECT
2059 if (graphicsEffect) {
2060 w = q->parentWidget();
2061 offset -= data.crect.topLeft();
2063 #endif //QT_NO_GRAPHICSEFFECT
2066 const QWidgetPrivate *wd = w->d_func();
2067 if (wd->extra && wd->extra->hasMask)
2068 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
2071 offset -= wd->data.crect.topLeft();
2072 w = w->parentWidget();
2076 bool QWidgetPrivate::paintOnScreen() const
2078 #if defined(QT_NO_BACKINGSTORE)
2082 if (q->testAttribute(Qt::WA_PaintOnScreen)
2083 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2087 return !qt_enable_backingstore;
2091 void QWidgetPrivate::updateIsOpaque()
2093 // hw: todo: only needed if opacity actually changed
2094 setDirtyOpaqueRegion();
2096 #ifndef QT_NO_GRAPHICSEFFECT
2097 if (graphicsEffect) {
2098 // ### We should probably add QGraphicsEffect::isOpaque at some point.
2102 #endif //QT_NO_GRAPHICSEFFECT
2106 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2113 if (q->windowType() == Qt::Dialog && q->testAttribute(Qt::WA_TranslucentBackground)
2114 && S60->avkonComponentsSupportTransparency) {
2120 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2125 const QPalette &pal = q->palette();
2127 if (q->autoFillBackground()) {
2128 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2129 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2135 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2136 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2137 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2145 void QWidgetPrivate::setOpaque(bool opaque)
2147 if (isOpaque == opaque)
2151 macUpdateIsOpaque();
2154 x11UpdateIsOpaque();
2157 winUpdateIsOpaque();
2160 s60UpdateIsOpaque();
2164 void QWidgetPrivate::updateIsTranslucent()
2167 macUpdateIsOpaque();
2170 x11UpdateIsOpaque();
2173 winUpdateIsOpaque();
2176 s60UpdateIsOpaque();
2180 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2184 if (brush.style() == Qt::TexturePattern) {
2186 // Optimize pattern filling on mac by using HITheme directly
2187 // when filling with the standard widget background.
2188 // Defined in qmacstyle_mac.cpp
2189 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2190 qt_mac_fill_background(painter, rgn, brush);
2192 #if !defined(QT_NO_STYLE_S60)
2193 // Defined in qs60style.cpp
2194 extern bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2195 if (!qt_s60_fill_background(painter, rgn, brush))
2196 #endif // !defined(QT_NO_STYLE_S60)
2198 const QRect rect(rgn.boundingRect());
2199 painter->setClipRegion(rgn);
2200 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2204 } else if (brush.gradient()
2205 && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2207 painter->setClipRegion(rgn);
2208 painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2211 const QVector<QRect> &rects = rgn.rects();
2212 for (int i = 0; i < rects.size(); ++i)
2213 painter->fillRect(rects.at(i), brush);
2217 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2221 #ifndef QT_NO_SCROLLAREA
2222 bool resetBrushOrigin = false;
2223 QPointF oldBrushOrigin;
2224 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2225 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2226 if (scrollArea && scrollArea->viewport() == q) {
2227 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2228 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2229 oldBrushOrigin = painter->brushOrigin();
2230 resetBrushOrigin = true;
2231 painter->setBrushOrigin(-priv->contentsOffset());
2234 #endif // QT_NO_SCROLLAREA
2236 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2238 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2239 const QBrush bg = q->palette().brush(QPalette::Window);
2240 fillRegion(painter, rgn, bg);
2243 if (q->autoFillBackground())
2244 fillRegion(painter, rgn, autoFillBrush);
2246 if (q->testAttribute(Qt::WA_StyledBackground)) {
2247 painter->setClipRegion(rgn);
2250 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2253 #ifndef QT_NO_SCROLLAREA
2254 if (resetBrushOrigin)
2255 painter->setBrushOrigin(oldBrushOrigin);
2256 #endif // QT_NO_SCROLLAREA
2261 This function is called when a widget is hidden or destroyed.
2262 It resets some application global pointers that should only refer active,
2267 extern QPointer<QWidget> qt_button_down;
2269 extern QWidget *qt_button_down;
2272 void QWidgetPrivate::deactivateWidgetCleanup()
2275 // If this was the active application window, reset it
2276 if (QApplication::activeWindow() == q)
2277 QApplication::setActiveWindow(0);
2278 // If the is the active mouse press widget, reset it
2279 if (q == qt_button_down)
2285 Returns a pointer to the widget with window identifer/handle \a
2288 The window identifier type depends on the underlying window
2289 system, see \c qwindowdefs.h for the actual definition. If there
2290 is no widget with this identifier, 0 is returned.
2293 QWidget *QWidget::find(WId id)
2295 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2301 \fn WId QWidget::internalWinId() const
2303 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2308 \fn WId QWidget::winId() const
2310 Returns the window system identifier of the widget.
2312 Portable in principle, but if you use it you are probably about to
2313 do something non-portable. Be careful.
2315 If a widget is non-native (alien) and winId() is invoked on it, that widget
2316 will be provided a native handle.
2318 On Mac OS X, the type returned depends on which framework Qt was linked
2319 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2320 is using Cocoa, {WId} is a pointer to an NSView.
2322 This value may change at run-time. An event with type QEvent::WinIdChange
2323 will be sent to the widget following a change in window system identifier.
2327 WId QWidget::winId() const
2329 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2331 qDebug() << "QWidget::winId: creating native window for" << this;
2333 QWidget *that = const_cast<QWidget*>(this);
2334 that->setAttribute(Qt::WA_NativeWindow);
2335 that->d_func()->createWinId();
2336 return that->data->winid;
2342 void QWidgetPrivate::createWinId(WId winid)
2347 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2349 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2350 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2351 if (!q->isWindow()) {
2352 QWidget *parent = q->parentWidget();
2353 QWidgetPrivate *pd = parent->d_func();
2354 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2355 parent->setAttribute(Qt::WA_NativeWindow);
2356 if (!parent->internalWinId()) {
2360 for (int i = 0; i < pd->children.size(); ++i) {
2361 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2362 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2363 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2368 // if the window has already been created, we
2369 // need to raise it to its proper stacking position
2384 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2388 void QWidget::createWinId()
2392 qDebug() << "QWidget::createWinId" << this;
2394 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2401 Returns the effective window system identifier of the widget, i.e. the
2402 native parent's window system identifier.
2404 If the widget is native, this function returns the native widget ID.
2405 Otherwise, the window ID of the first native parent widget, i.e., the
2406 top-level widget that contains this widget, is returned.
2408 \note We recommend that you do not store this value as it is likely to
2411 \sa nativeParentWidget()
2413 WId QWidget::effectiveWinId() const
2415 WId id = internalWinId();
2416 if (id || !testAttribute(Qt::WA_WState_Created))
2418 QWidget *realParent = nativeParentWidget();
2419 if (!realParent && d_func()->inSetParent) {
2420 // In transitional state. This is really just a workaround. The real problem
2421 // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2422 // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2423 // attribute to false. The correct way is to do it the other way around, and
2424 // in that case the Qt::WA_WState_Created logic above will kick in and
2425 // return 0 whenever the widget is in a transitional state. However, changing
2426 // the original logic for all platforms is far more intrusive and might
2427 // break existing applications.
2428 // Note: The widget can only be in a transitional state when changing its
2429 // parent -- everything else is an internal error -- hence explicitly checking
2430 // against 'inSetParent' rather than doing an unconditional return whenever
2431 // 'realParent' is 0 (which may cause strange artifacts and headache later).
2434 // This widget *must* have a native parent widget.
2435 Q_ASSERT(realParent);
2436 Q_ASSERT(realParent->internalWinId());
2437 return realParent->internalWinId();
2440 #ifndef QT_NO_STYLE_STYLESHEET
2443 \property QWidget::styleSheet
2444 \brief the widget's style sheet
2447 The style sheet contains a textual description of customizations to the
2448 widget's style, as described in the \l{Qt Style Sheets} document.
2450 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2452 \warning Qt style sheets are currently not supported for custom QStyle
2453 subclasses. We plan to address this in some future release.
2455 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2457 QString QWidget::styleSheet() const
2462 return d->extra->styleSheet;
2465 void QWidget::setStyleSheet(const QString& styleSheet)
2470 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2471 d->extra->styleSheet = styleSheet;
2472 if (styleSheet.isEmpty()) { // stylesheet removed
2480 if (proxy) { // style sheet update
2481 proxy->repolish(this);
2485 if (testAttribute(Qt::WA_SetStyle)) {
2486 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2488 d->setStyle_helper(new QStyleSheetStyle(0), true);
2492 #endif // QT_NO_STYLE_STYLESHEET
2495 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2498 QStyle *QWidget::style() const
2502 if (d->extra && d->extra->style)
2503 return d->extra->style;
2504 return QApplication::style();
2508 Sets the widget's GUI style to \a style. The ownership of the style
2509 object is not transferred.
2511 If no style is set, the widget uses the application's style,
2512 QApplication::style() instead.
2514 Setting a widget's style has no effect on existing or future child
2517 \warning This function is particularly useful for demonstration
2518 purposes, where you want to show Qt's styling capabilities. Real
2519 applications should avoid it and use one consistent GUI style
2522 \warning Qt style sheets are currently not supported for custom QStyle
2523 subclasses. We plan to address this in some future release.
2525 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2528 void QWidget::setStyle(QStyle *style)
2531 setAttribute(Qt::WA_SetStyle, style != 0);
2533 #ifndef QT_NO_STYLE_STYLESHEET
2534 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2535 //if for some reason someone try to set a QStyleSheetStyle, ref it
2536 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2538 d->setStyle_helper(style, false);
2539 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2540 // if we have an application stylesheet or have a proxy already, propagate
2541 d->setStyle_helper(new QStyleSheetStyle(style), true);
2544 d->setStyle_helper(style, false);
2547 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2554 QStyle *oldStyle = q->style();
2555 #ifndef QT_NO_STYLE_STYLESHEET
2556 QWeakPointer<QStyle> origStyle;
2560 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2561 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2562 // set when changing that attribute and passes the widget's CURRENT style.
2563 // therefore no need to do a reassignment.
2569 #ifndef QT_NO_STYLE_STYLESHEET
2570 origStyle = extra->style.data();
2572 extra->style = newStyle;
2576 if (q->windowType() != Qt::Desktop) {
2578 oldStyle->unpolish(q);
2581 macUpdateMetalAttribute();
2583 q->style()->polish(q);
2585 } else if (metalHack) {
2586 macUpdateMetalAttribute();
2592 for (int i = 0; i < children.size(); ++i) {
2593 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2595 c->d_func()->inheritStyle();
2599 #ifndef QT_NO_STYLE_STYLESHEET
2600 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2601 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2602 cssStyle->clearWidgetFont(q);
2607 QEvent e(QEvent::StyleChange);
2608 QApplication::sendEvent(q, &e);
2610 #ifndef QT_NO_STYLE_STYLESHEET
2611 // dereference the old stylesheet style
2612 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2617 // Inherits style from the current parent and propagates it as necessary
2618 void QWidgetPrivate::inheritStyle()
2620 #ifndef QT_NO_STYLE_STYLESHEET
2623 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2625 if (!q->styleSheet().isEmpty()) {
2631 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2632 QWidget *parent = q->parentWidget();
2633 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2634 // If we have stylesheet on app or parent has stylesheet style, we need
2635 // to be running a proxy
2636 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2637 QStyle *newStyle = parentStyle;
2638 if (q->testAttribute(Qt::WA_SetStyle))
2639 newStyle = new QStyleSheetStyle(origStyle);
2640 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2643 setStyle_helper(newStyle, true);
2647 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2648 // we just need our original style back
2649 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2652 // We could have inherited the proxy from our parent (which has a custom style)
2653 // In such a case we need to start following the application style (i.e revert
2654 // the propagation behavior of QStyleSheetStyle)
2655 if (!q->testAttribute(Qt::WA_SetStyle))
2658 setStyle_helper(origStyle, true);
2659 #endif // QT_NO_STYLE_STYLESHEET
2664 \fn bool QWidget::isWindow() const
2666 Returns true if the widget is an independent window, otherwise
2669 A window is a widget that isn't visually the child of any other
2670 widget and that usually has a frame and a
2671 \l{QWidget::setWindowTitle()}{window title}.
2673 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2674 It will then be grouped with its parent and deleted when the
2675 parent is deleted, minimized when the parent is minimized etc. If
2676 supported by the window manager, it will also have a common
2677 taskbar entry with its parent.
2679 QDialog and QMainWindow widgets are by default windows, even if a
2680 parent widget is specified in the constructor. This behavior is
2681 specified by the Qt::Window flag.
2683 \sa window(), isModal(), parentWidget()
2687 \property QWidget::modal
2688 \brief whether the widget is a modal widget
2690 This property only makes sense for windows. A modal widget
2691 prevents widgets in all other windows from getting any input.
2693 By default, this property is false.
2695 \sa isWindow(), windowModality, QDialog
2699 \property QWidget::windowModality
2700 \brief which windows are blocked by the modal widget
2703 This property only makes sense for windows. A modal widget
2704 prevents widgets in other windows from getting input. The value of
2705 this property controls which windows are blocked when the widget
2706 is visible. Changing this property while the window is visible has
2707 no effect; you must hide() the widget first, then show() it again.
2709 By default, this property is Qt::NonModal.
2711 \sa isWindow(), QWidget::modal, QDialog
2714 Qt::WindowModality QWidget::windowModality() const
2716 return static_cast<Qt::WindowModality>(data->window_modality);
2719 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2721 data->window_modality = windowModality;
2722 // setModal_sys() will be called by setAttribute()
2723 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2724 setAttribute(Qt::WA_SetWindowModality, true);
2728 \fn bool QWidget::underMouse() const
2730 Returns true if the widget is under the mouse cursor; otherwise
2733 This value is not updated properly during drag and drop
2736 \sa enterEvent(), leaveEvent()
2740 \property QWidget::minimized
2741 \brief whether this widget is minimized (iconified)
2743 This property is only relevant for windows.
2745 By default, this property is false.
2747 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2749 bool QWidget::isMinimized() const
2750 { return data->window_state & Qt::WindowMinimized; }
2753 Shows the widget minimized, as an icon.
2755 Calling this function only affects \l{isWindow()}{windows}.
2757 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2760 void QWidget::showMinimized()
2762 bool isMin = isMinimized();
2763 if (isMin && isVisible())
2769 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2774 \property QWidget::maximized
2775 \brief whether this widget is maximized
2777 This property is only relevant for windows.
2779 \note Due to limitations on some window systems, this does not always
2780 report the expected results (e.g., if the user on X11 maximizes the
2781 window via the window manager, Qt has no way of distinguishing this
2782 from any other resize). This is expected to improve as window manager
2785 By default, this property is false.
2787 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2789 bool QWidget::isMaximized() const
2790 { return data->window_state & Qt::WindowMaximized; }
2795 Returns the current window state. The window state is a OR'ed
2796 combination of Qt::WindowState: Qt::WindowMinimized,
2797 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2799 \sa Qt::WindowState setWindowState()
2801 Qt::WindowStates QWidget::windowState() const
2803 return Qt::WindowStates(data->window_state);
2808 The function sets the window state on child widgets similar to
2809 setWindowState(). The difference is that the window state changed
2810 event has the isOverride() flag set. It exists mainly to keep
2811 Q3Workspace working.
2813 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2815 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2816 data->window_state = newstate;
2817 QApplication::sendEvent(this, &e);
2821 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2823 Sets the window state to \a windowState. The window state is a OR'ed
2824 combination of Qt::WindowState: Qt::WindowMinimized,
2825 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2827 If the window is not visible (i.e. isVisible() returns false), the
2828 window state will take effect when show() is called. For visible
2829 windows, the change is immediate. For example, to toggle between
2830 full-screen and normal mode, use the following code:
2832 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2834 In order to restore and activate a minimized window (while
2835 preserving its maximized and/or full-screen state), use the following:
2837 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2839 Calling this function will hide the widget. You must call show() to make
2840 the widget visible again.
2842 \note On some window systems Qt::WindowActive is not immediate, and may be
2843 ignored in certain cases.
2845 When the window state changes, the widget receives a changeEvent()
2846 of type QEvent::WindowStateChange.
2848 \sa Qt::WindowState windowState()
2852 \property QWidget::fullScreen
2853 \brief whether the widget is shown in full screen mode
2855 A widget in full screen mode occupies the whole screen area and does not
2856 display window decorations, such as a title bar.
2858 By default, this property is false.
2860 \sa windowState(), minimized, maximized
2862 bool QWidget::isFullScreen() const
2863 { return data->window_state & Qt::WindowFullScreen; }
2866 Shows the widget in full-screen mode.
2868 Calling this function only affects \l{isWindow()}{windows}.
2870 To return from full-screen mode, call showNormal().
2872 Full-screen mode works fine under Windows, but has certain
2873 problems under X. These problems are due to limitations of the
2874 ICCCM protocol that specifies the communication between X11
2875 clients and the window manager. ICCCM simply does not understand
2876 the concept of non-decorated full-screen windows. Therefore, the
2877 best we can do is to request a borderless window and place and
2878 resize it to fill the entire screen. Depending on the window
2879 manager, this may or may not work. The borderless window is
2880 requested using MOTIF hints, which are at least partially
2881 supported by virtually all modern window managers.
2883 An alternative would be to bypass the window manager entirely and
2884 create a window with the Qt::X11BypassWindowManagerHint flag. This
2885 has other severe problems though, like totally broken keyboard focus
2886 and very strange effects on desktop changes or when the user raises
2889 X11 window managers that follow modern post-ICCCM specifications
2890 support full-screen mode properly.
2892 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2894 void QWidget::showFullScreen()
2897 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2898 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2899 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2900 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2901 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2902 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2907 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2908 | Qt::WindowFullScreen);
2914 Shows the widget maximized.
2916 Calling this function only affects \l{isWindow()}{windows}.
2918 On X11, this function may not work properly with certain window
2919 managers. See the \l{Window Geometry} documentation for an explanation.
2921 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2923 void QWidget::showMaximized()
2927 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2928 | Qt::WindowMaximized);
2930 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2931 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2934 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2935 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2936 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2937 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2945 Restores the widget after it has been maximized or minimized.
2947 Calling this function only affects \l{isWindow()}{windows}.
2949 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2951 void QWidget::showNormal()
2955 setWindowState(windowState() & ~(Qt::WindowMinimized
2956 | Qt::WindowMaximized
2957 | Qt::WindowFullScreen));
2959 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2960 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2963 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2964 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2965 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2966 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2974 Returns true if this widget would become enabled if \a ancestor is
2975 enabled; otherwise returns false.
2979 This is the case if neither the widget itself nor every parent up
2980 to but excluding \a ancestor has been explicitly disabled.
2982 isEnabledTo(0) is equivalent to isEnabled().
2984 \sa setEnabled() enabled
2987 bool QWidget::isEnabledTo(QWidget* ancestor) const
2989 const QWidget * w = this;
2990 while (!w->testAttribute(Qt::WA_ForceDisabled)
2992 && w->parentWidget()
2993 && w->parentWidget() != ancestor)
2994 w = w->parentWidget();
2995 return !w->testAttribute(Qt::WA_ForceDisabled);
2998 #ifndef QT_NO_ACTION
3000 Appends the action \a action to this widget's list of actions.
3002 All QWidgets have a list of \l{QAction}s, however they can be
3003 represented graphically in many different ways. The default use of
3004 the QAction list (as returned by actions()) is to create a context
3007 A QWidget should only have one of each action and adding an action
3008 it already has will not cause the same action to be in the widget twice.
3010 The ownership of \a action is not transferred to this QWidget.
3012 \sa removeAction(), insertAction(), actions(), QMenu
3014 void QWidget::addAction(QAction *action)
3016 insertAction(0, action);
3020 Appends the actions \a actions to this widget's list of actions.
3022 \sa removeAction(), QMenu, addAction()
3024 void QWidget::addActions(QList<QAction*> actions)
3026 for(int i = 0; i < actions.count(); i++)
3027 insertAction(0, actions.at(i));
3031 Inserts the action \a action to this widget's list of actions,
3032 before the action \a before. It appends the action if \a before is 0 or
3033 \a before is not a valid action for this widget.
3035 A QWidget should only have one of each action.
3037 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
3039 void QWidget::insertAction(QAction *before, QAction *action)
3042 qWarning("QWidget::insertAction: Attempt to insert null action");
3047 if(d->actions.contains(action))
3048 removeAction(action);
3050 int pos = d->actions.indexOf(before);
3053 pos = d->actions.size();
3055 d->actions.insert(pos, action);
3057 QActionPrivate *apriv = action->d_func();
3058 apriv->widgets.append(this);
3060 QActionEvent e(QEvent::ActionAdded, action, before);
3061 QApplication::sendEvent(this, &e);
3065 Inserts the actions \a actions to this widget's list of actions,
3066 before the action \a before. It appends the action if \a before is 0 or
3067 \a before is not a valid action for this widget.
3069 A QWidget can have at most one of each action.
3071 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
3073 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
3075 for(int i = 0; i < actions.count(); ++i)
3076 insertAction(before, actions.at(i));
3080 Removes the action \a action from this widget's list of actions.
3081 \sa insertAction(), actions(), insertAction()
3083 void QWidget::removeAction(QAction *action)
3090 QActionPrivate *apriv = action->d_func();
3091 apriv->widgets.removeAll(this);
3093 if (d->actions.removeAll(action)) {
3094 QActionEvent e(QEvent::ActionRemoved, action);
3095 QApplication::sendEvent(this, &e);
3100 Returns the (possibly empty) list of this widget's actions.
3102 \sa contextMenuPolicy, insertAction(), removeAction()
3104 QList<QAction*> QWidget::actions() const
3109 #endif // QT_NO_ACTION
3112 \fn bool QWidget::isEnabledToTLW() const
3115 This function is deprecated. It is equivalent to isEnabled()
3119 \property QWidget::enabled
3120 \brief whether the widget is enabled
3122 An enabled widget handles keyboard and mouse events; a disabled
3125 Some widgets display themselves differently when they are
3126 disabled. For example a button might draw its label grayed out. If
3127 your widget needs to know when it becomes enabled or disabled, you
3128 can use the changeEvent() with type QEvent::EnabledChange.
3130 Disabling a widget implicitly disables all its children. Enabling
3131 respectively enables all child widgets unless they have been
3132 explicitly disabled.
3134 By default, this property is true.
3136 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3138 void QWidget::setEnabled(bool enable)
3141 setAttribute(Qt::WA_ForceDisabled, !enable);
3142 d->setEnabled_helper(enable);
3145 void QWidgetPrivate::setEnabled_helper(bool enable)
3149 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3150 return; // nothing we can do
3152 if (enable != q->testAttribute(Qt::WA_Disabled))
3153 return; // nothing to do
3155 q->setAttribute(Qt::WA_Disabled, !enable);
3156 updateSystemBackground();
3158 if (!enable && q->window()->focusWidget() == q) {
3159 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3160 if (!parentIsEnabled || !q->focusNextChild())
3164 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3165 for (int i = 0; i < children.size(); ++i) {
3166 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3167 if (w && !w->testAttribute(attribute))
3168 w->d_func()->setEnabled_helper(enable);
3170 #if defined(Q_WS_X11)
3171 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3172 // enforce the windows behavior of clearing the cursor on
3174 qt_x11_enforce_cursor(q);
3176 #elif defined(Q_WS_QPA)
3177 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3178 // enforce the windows behavior of clearing the cursor on
3180 qt_qpa_set_cursor(q, false);
3183 #if defined(Q_WS_MAC)
3184 setEnabled_helper_sys(enable);
3187 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3188 QWidget *focusWidget = effectiveFocusWidget();
3191 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3192 qApp->inputPanel()->setInputItem(focusWidget);
3194 qApp->inputPanel()->commit();
3195 qApp->inputPanel()->setInputItem(0);
3199 QEvent e(QEvent::EnabledChange);
3200 QApplication::sendEvent(q, &e);
3204 \property QWidget::acceptDrops
3205 \brief whether drop events are enabled for this widget
3207 Setting this property to true announces to the system that this
3208 widget \e may be able to accept drop events.
3210 If the widget is the desktop (windowType() == Qt::Desktop), this may
3211 fail if another application is using the desktop; you can call
3212 acceptDrops() to test if this occurs.
3214 \warning Do not modify this property in a drag and drop event handler.
3216 By default, this property is false.
3220 bool QWidget::acceptDrops() const
3222 return testAttribute(Qt::WA_AcceptDrops);
3225 void QWidget::setAcceptDrops(bool on)
3227 setAttribute(Qt::WA_AcceptDrops, on);
3232 \fn void QWidget::enabledChange(bool)
3239 \fn void QWidget::paletteChange(const QPalette &)
3246 \fn void QWidget::fontChange(const QFont &)
3253 \fn void QWidget::windowActivationChange(bool)
3260 \fn void QWidget::languageChange()
3266 \fn void QWidget::styleChange(QStyle& style)
3273 Disables widget input events if \a disable is true; otherwise
3274 enables input events.
3276 See the \l enabled documentation for more information.
3278 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3280 void QWidget::setDisabled(bool disable)
3282 setEnabled(!disable);
3286 \property QWidget::frameGeometry
3287 \brief geometry of the widget relative to its parent including any
3290 See the \l{Window Geometry} documentation for an overview of geometry
3291 issues with windows.
3293 By default, this property contains a value that depends on the user's
3294 platform and screen geometry.
3296 \sa geometry() x() y() pos()
3298 QRect QWidget::frameGeometry() const
3301 if (isWindow() && ! (windowType() == Qt::Popup)) {
3302 QRect fs = d->frameStrut();
3303 return QRect(data->crect.x() - fs.left(),
3304 data->crect.y() - fs.top(),
3305 data->crect.width() + fs.left() + fs.right(),
3306 data->crect.height() + fs.top() + fs.bottom());
3312 \property QWidget::x
3314 \brief the x coordinate of the widget relative to its parent including
3317 See the \l{Window Geometry} documentation for an overview of geometry
3318 issues with windows.
3320 By default, this property has a value of 0.
3322 \sa frameGeometry, y, pos
3324 int QWidget::x() const
3327 if (isWindow() && ! (windowType() == Qt::Popup))
3328 return data->crect.x() - d->frameStrut().left();
3329 return data->crect.x();
3333 \property QWidget::y
3334 \brief the y coordinate of the widget relative to its parent and
3335 including any window frame
3337 See the \l{Window Geometry} documentation for an overview of geometry
3338 issues with windows.
3340 By default, this property has a value of 0.
3342 \sa frameGeometry, x, pos
3344 int QWidget::y() const
3347 if (isWindow() && ! (windowType() == Qt::Popup))
3348 return data->crect.y() - d->frameStrut().top();
3349 return data->crect.y();
3353 \property QWidget::pos
3354 \brief the position of the widget within its parent widget
3356 If the widget is a window, the position is that of the widget on
3357 the desktop, including its frame.
3359 When changing the position, the widget, if visible, receives a
3360 move event (moveEvent()) immediately. If the widget is not
3361 currently visible, it is guaranteed to receive an event before it
3364 By default, this property contains a position that refers to the
3367 \warning Calling move() or setGeometry() inside moveEvent() can
3368 lead to infinite recursion.
3370 See the \l{Window Geometry} documentation for an overview of geometry
3371 issues with windows.
3373 \sa frameGeometry, size x(), y()
3375 QPoint QWidget::pos() const
3378 if (isWindow() && ! (windowType() == Qt::Popup)) {
3379 QRect fs = d->frameStrut();
3380 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3382 return data->crect.topLeft();
3386 \property QWidget::geometry
3387 \brief the geometry of the widget relative to its parent and
3388 excluding the window frame
3390 When changing the geometry, the widget, if visible, receives a
3391 move event (moveEvent()) and/or a resize event (resizeEvent())
3392 immediately. If the widget is not currently visible, it is
3393 guaranteed to receive appropriate events before it is shown.
3395 The size component is adjusted if it lies outside the range
3396 defined by minimumSize() and maximumSize().
3398 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3399 can lead to infinite recursion.
3401 See the \l{Window Geometry} documentation for an overview of geometry
3402 issues with windows.
3404 By default, this property contains a value that depends on the user's
3405 platform and screen geometry.
3407 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3408 resizeEvent(), minimumSize(), maximumSize()
3412 \property QWidget::normalGeometry
3414 \brief the geometry of the widget as it will appear when shown as
3415 a normal (not maximized or full screen) top-level widget
3417 For child widgets this property always holds an empty rectangle.
3419 By default, this property contains an empty rectangle.
3421 \sa QWidget::windowState(), QWidget::geometry
3425 \property QWidget::size
3426 \brief the size of the widget excluding any window frame
3428 If the widget is visible when it is being resized, it receives a resize event
3429 (resizeEvent()) immediately. If the widget is not currently
3430 visible, it is guaranteed to receive an event before it is shown.
3432 The size is adjusted if it lies outside the range defined by
3433 minimumSize() and maximumSize().
3435 By default, this property contains a value that depends on the user's
3436 platform and screen geometry.
3438 \warning Calling resize() or setGeometry() inside resizeEvent() can
3439 lead to infinite recursion.
3441 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3442 appear on screen. This also applies to windows.
3444 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3448 \property QWidget::width
3449 \brief the width of the widget excluding any window frame
3451 See the \l{Window Geometry} documentation for an overview of geometry
3452 issues with windows.
3454 \note Do not use this function to find the width of a screen on
3455 a \l{QDesktopWidget}{multiple screen desktop}. Read
3456 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3458 By default, this property contains a value that depends on the user's
3459 platform and screen geometry.
3461 \sa geometry, height, size
3465 \property QWidget::height
3466 \brief the height of the widget excluding any window frame
3468 See the \l{Window Geometry} documentation for an overview of geometry
3469 issues with windows.
3471 \note Do not use this function to find the height of a screen
3472 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3473 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3475 By default, this property contains a value that depends on the user's
3476 platform and screen geometry.
3478 \sa geometry, width, size
3482 \property QWidget::rect
3483 \brief the internal geometry of the widget excluding any window
3486 The rect property equals QRect(0, 0, width(), height()).
3488 See the \l{Window Geometry} documentation for an overview of geometry
3489 issues with windows.
3491 By default, this property contains a value that depends on the user's
3492 platform and screen geometry.
3498 QRect QWidget::normalGeometry() const
3501 if (!d->extra || !d->extra->topextra)
3504 if (!isMaximized() && !isFullScreen())
3507 return d->topData()->normalGeometry;
3512 \property QWidget::childrenRect
3513 \brief the bounding rectangle of the widget's children
3515 Hidden children are excluded.
3517 By default, for a widget with no children, this property contains a
3518 rectangle with zero width and height located at the origin.
3520 \sa childrenRegion() geometry()
3523 QRect QWidget::childrenRect() const
3526 QRect r(0, 0, 0, 0);
3527 for (int i = 0; i < d->children.size(); ++i) {
3528 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3529 if (w && !w->isWindow() && !w->isHidden())
3536 \property QWidget::childrenRegion
3537 \brief the combined region occupied by the widget's children
3539 Hidden children are excluded.
3541 By default, for a widget with no children, this property contains an
3544 \sa childrenRect() geometry() mask()
3547 QRegion QWidget::childrenRegion() const
3551 for (int i = 0; i < d->children.size(); ++i) {
3552 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3553 if (w && !w->isWindow() && !w->isHidden()) {
3554 QRegion mask = w->mask();
3558 r |= mask.translated(w->pos());
3566 \property QWidget::minimumSize
3567 \brief the widget's minimum size
3569 The widget cannot be resized to a smaller size than the minimum
3570 widget size. The widget's size is forced to the minimum size if
3571 the current size is smaller.
3573 The minimum size set by this function will override the minimum size
3574 defined by QLayout. In order to unset the minimum size, use a
3575 value of \c{QSize(0, 0)}.
3577 By default, this property contains a size with zero width and height.
3579 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3582 QSize QWidget::minimumSize() const
3585 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3589 \property QWidget::maximumSize
3590 \brief the widget's maximum size in pixels
3592 The widget cannot be resized to a larger size than the maximum
3595 By default, this property contains a size in which both width and height
3596 have values of 16777215.
3598 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3601 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3604 QSize QWidget::maximumSize() const
3607 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3608 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3613 \property QWidget::minimumWidth
3614 \brief the widget's minimum width in pixels
3616 This property corresponds to the width held by the \l minimumSize property.
3618 By default, this property has a value of 0.
3620 \sa minimumSize, minimumHeight
3624 \property QWidget::minimumHeight
3625 \brief the widget's minimum height in pixels
3627 This property corresponds to the height held by the \l minimumSize property.
3629 By default, this property has a value of 0.
3631 \sa minimumSize, minimumWidth
3635 \property QWidget::maximumWidth
3636 \brief the widget's maximum width in pixels
3638 This property corresponds to the width held by the \l maximumSize property.
3640 By default, this property contains a value of 16777215.
3642 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3645 \sa maximumSize, maximumHeight
3649 \property QWidget::maximumHeight
3650 \brief the widget's maximum height in pixels
3652 This property corresponds to the height held by the \l maximumSize property.
3654 By default, this property contains a value of 16777215.
3656 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3659 \sa maximumSize, maximumWidth
3663 \property QWidget::sizeIncrement
3664 \brief the size increment of the widget
3666 When the user resizes the window, the size will move in steps of
3667 sizeIncrement().width() pixels horizontally and
3668 sizeIncrement.height() pixels vertically, with baseSize() as the
3669 basis. Preferred widget sizes are for non-negative integers \e i
3671 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3673 Note that while you can set the size increment for all widgets, it
3674 only affects windows.
3676 By default, this property contains a size with zero width and height.
3678 \warning The size increment has no effect under Windows, and may
3679 be disregarded by the window manager on X11.
3681 \sa size, minimumSize, maximumSize
3683 QSize QWidget::sizeIncrement() const
3686 return (d->extra && d->extra->topextra)
3687 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3692 \property QWidget::baseSize
3693 \brief the base size of the widget
3695 The base size is used to calculate a proper widget size if the
3696 widget defines sizeIncrement().
3698 By default, for a newly-created widget, this property contains a size with
3699 zero width and height.
3701 \sa setSizeIncrement()
3704 QSize QWidget::baseSize() const
3707 return (d->extra != 0 && d->extra->topextra != 0)
3708 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3712 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3716 int mw = minw, mh = minh;
3717 if (mw == QWIDGETSIZE_MAX)
3719 if (mh == QWIDGETSIZE_MAX)
3721 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3722 qWarning("QWidget::setMinimumSize: (%s/%s) "
3723 "The largest allowed size is (%d,%d)",
3724 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3726 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3727 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3729 if (minw < 0 || minh < 0) {
3730 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3732 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3733 minw = mw = qMax(minw, 0);
3734 minh = mh = qMax(minh, 0);
3737 if (extra->minw == mw && extra->minh == mh)
3741 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3748 This function corresponds to setMinimumSize(QSize(minw, minh)).
3749 Sets the minimum width to \a minw and the minimum height to \a
3753 void QWidget::setMinimumSize(int minw, int minh)
3756 if (!d->setMinimumSize_helper(minw, minh))
3760 d->setConstraints_sys();
3761 if (minw > width() || minh > height()) {
3762 bool resized = testAttribute(Qt::WA_Resized);
3763 bool maximized = isMaximized();
3764 resize(qMax(minw,width()), qMax(minh,height()));
3765 setAttribute(Qt::WA_Resized, resized); //not a user resize
3767 data->window_state = data->window_state | Qt::WindowMaximized;
3769 #ifndef QT_NO_GRAPHICSVIEW
3771 if (d->extra->proxyWidget)
3772 d->extra->proxyWidget->setMinimumSize(minw, minh);
3775 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3778 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3781 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3782 qWarning("QWidget::setMaximumSize: (%s/%s) "
3783 "The largest allowed size is (%d,%d)",
3784 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3786 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3787 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3789 if (maxw < 0 || maxh < 0) {
3790 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3792 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3793 maxw = qMax(maxw, 0);
3794 maxh = qMax(maxh, 0);
3797 if (extra->maxw == maxw && extra->maxh == maxh)
3801 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3802 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3809 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3810 maxh)). Sets the maximum width to \a maxw and the maximum height
3813 void QWidget::setMaximumSize(int maxw, int maxh)
3816 if (!d->setMaximumSize_helper(maxw, maxh))
3820 d->setConstraints_sys();
3821 if (maxw < width() || maxh < height()) {
3822 bool resized = testAttribute(Qt::WA_Resized);
3823 resize(qMin(maxw,width()), qMin(maxh,height()));
3824 setAttribute(Qt::WA_Resized, resized); //not a user resize
3827 #ifndef QT_NO_GRAPHICSVIEW
3829 if (d->extra->proxyWidget)
3830 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3834 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3840 Sets the x (width) size increment to \a w and the y (height) size
3843 void QWidget::setSizeIncrement(int w, int h)
3847 QTLWExtra* x = d->topData();
3848 if (x->incw == w && x->inch == h)
3853 d->setConstraints_sys();
3859 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3860 the widgets base size to width \a basew and height \a baseh.
3862 void QWidget::setBaseSize(int basew, int baseh)
3866 QTLWExtra* x = d->topData();
3867 if (x->basew == basew && x->baseh == baseh)
3872 d->setConstraints_sys();
3876 Sets both the minimum and maximum sizes of the widget to \a s,
3877 thereby preventing it from ever growing or shrinking.
3879 This will override the default size constraints set by QLayout.
3881 To remove constraints, set the size to QWIDGETSIZE_MAX.
3883 Alternatively, if you want the widget to have a
3884 fixed size based on its contents, you can call
3885 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3887 \sa maximumSize, minimumSize
3890 void QWidget::setFixedSize(const QSize & s)
3892 setFixedSize(s.width(), s.height());
3897 \fn void QWidget::setFixedSize(int w, int h)
3900 Sets the width of the widget to \a w and the height to \a h.
3903 void QWidget::setFixedSize(int w, int h)
3906 bool minSizeSet = d->setMinimumSize_helper(w, h);
3907 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3908 if (!minSizeSet && !maxSizeSet)
3912 d->setConstraints_sys();
3914 d->updateGeometry_helper(true);
3916 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3920 void QWidget::setMinimumWidth(int w)
3924 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3925 setMinimumSize(w, minimumSize().height());
3926 d->extra->explicitMinSize = expl;
3929 void QWidget::setMinimumHeight(int h)
3933 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3934 setMinimumSize(minimumSize().width(), h);
3935 d->extra->explicitMinSize = expl;
3938 void QWidget::setMaximumWidth(int w)
3942 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3943 setMaximumSize(w, maximumSize().height());
3944 d->extra->explicitMaxSize = expl;
3947 void QWidget::setMaximumHeight(int h)
3951 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3952 setMaximumSize(maximumSize().width(), h);
3953 d->extra->explicitMaxSize = expl;
3957 Sets both the minimum and maximum width of the widget to \a w
3958 without changing the heights. Provided for convenience.
3960 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3963 void QWidget::setFixedWidth(int w)
3967 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3968 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3969 setMinimumSize(w, minimumSize().height());
3970 setMaximumSize(w, maximumSize().height());
3971 d->extra->explicitMinSize = explMin;
3972 d->extra->explicitMaxSize = explMax;
3977 Sets both the minimum and maximum heights of the widget to \a h
3978 without changing the widths. Provided for convenience.
3980 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3983 void QWidget::setFixedHeight(int h)
3987 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3988 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3989 setMinimumSize(minimumSize().width(), h);
3990 setMaximumSize(maximumSize().width(), h);
3991 d->extra->explicitMinSize = explMin;
3992 d->extra->explicitMaxSize = explMax;
3997 Translates the widget coordinate \a pos to the coordinate system
3998 of \a parent. The \a parent must not be 0 and must be a parent
3999 of the calling widget.
4001 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
4004 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
4008 const QWidget * w = this;
4009 while (w != parent) {
4010 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
4011 "parent must be in parent hierarchy");
4012 p = w->mapToParent(p);
4013 w = w->parentWidget();
4021 Translates the widget coordinate \a pos from the coordinate system
4022 of \a parent to this widget's coordinate system. The \a parent
4023 must not be 0 and must be a parent of the calling widget.
4025 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
4028 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
4032 const QWidget * w = this;
4033 while (w != parent) {
4034 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
4035 "parent must be in parent hierarchy");
4037 p = w->mapFromParent(p);
4038 w = w->parentWidget();
4046 Translates the widget coordinate \a pos to a coordinate in the
4049 Same as mapToGlobal() if the widget has no parent.
4051 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
4054 QPoint QWidget::mapToParent(const QPoint &pos) const
4056 return pos + data->crect.topLeft();
4060 Translates the parent widget coordinate \a pos to widget
4063 Same as mapFromGlobal() if the widget has no parent.
4065 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
4068 QPoint QWidget::mapFromParent(const QPoint &pos) const
4070 return pos - data->crect.topLeft();
4075 Returns the window for this widget, i.e. the next ancestor widget
4076 that has (or could have) a window-system frame.
4078 If the widget is a window, the widget itself is returned.
4080 Typical usage is changing the window title:
4082 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
4087 QWidget *QWidget::window() const
4089 QWidget *w = (QWidget *)this;
4090 QWidget *p = w->parentWidget();
4091 while (!w->isWindow() && p) {
4093 p = p->parentWidget();
4101 Returns the native parent for this widget, i.e. the next ancestor widget
4102 that has a system identifier, or 0 if it does not have any native parent.
4104 \sa effectiveWinId()
4106 QWidget *QWidget::nativeParentWidget() const
4108 QWidget *parent = parentWidget();
4109 while (parent && !parent->internalWinId())
4110 parent = parent->parentWidget();
4114 /*! \fn QWidget *QWidget::topLevelWidget() const
4117 Use window() instead.
4123 Returns the background role of the widget.
4125 The background role defines the brush from the widget's \l palette that
4126 is used to render the background.
4128 If no explicit background role is set, the widget inherts its parent
4129 widget's background role.
4131 \sa setBackgroundRole(), foregroundRole()
4133 QPalette::ColorRole QWidget::backgroundRole() const
4136 const QWidget *w = this;
4138 QPalette::ColorRole role = w->d_func()->bg_role;
4139 if (role != QPalette::NoRole)
4141 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4143 w = w->parentWidget();
4145 return QPalette::Window;
4149 Sets the background role of the widget to \a role.
4151 The background role defines the brush from the widget's \l palette that
4152 is used to render the background.
4154 If \a role is QPalette::NoRole, then the widget inherits its
4155 parent's background role.
4157 Note that styles are free to choose any color from the palette.
4158 You can modify the palette or set a style sheet if you don't
4159 achieve the result you want with setBackgroundRole().
4161 \sa backgroundRole(), foregroundRole()
4164 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4168 d->updateSystemBackground();
4169 d->propagatePaletteChange();
4170 d->updateIsOpaque();
4174 Returns the foreground role.
4176 The foreground role defines the color from the widget's \l palette that
4177 is used to draw the foreground.
4179 If no explicit foreground role is set, the function returns a role
4180 that contrasts with the background role.
4182 \sa setForegroundRole(), backgroundRole()
4184 QPalette::ColorRole QWidget::foregroundRole() const
4187 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4188 if (rl != QPalette::NoRole)
4190 QPalette::ColorRole role = QPalette::WindowText;
4191 switch (backgroundRole()) {
4192 case QPalette::Button:
4193 role = QPalette::ButtonText;
4195 case QPalette::Base:
4196 role = QPalette::Text;
4198 case QPalette::Dark:
4199 case QPalette::Shadow:
4200 role = QPalette::Light;
4202 case QPalette::Highlight:
4203 role = QPalette::HighlightedText;
4205 case QPalette::ToolTipBase:
4206 role = QPalette::ToolTipText;
4215 Sets the foreground role of the widget to \a role.
4217 The foreground role defines the color from the widget's \l palette that
4218 is used to draw the foreground.
4220 If \a role is QPalette::NoRole, the widget uses a foreground role
4221 that contrasts with the background role.
4223 Note that styles are free to choose any color from the palette.
4224 You can modify the palette or set a style sheet if you don't
4225 achieve the result you want with setForegroundRole().
4227 \sa foregroundRole(), backgroundRole()
4229 void QWidget::setForegroundRole(QPalette::ColorRole role)
4233 d->updateSystemBackground();
4234 d->propagatePaletteChange();
4238 \property QWidget::palette
4239 \brief the widget's palette
4241 This property describes the widget's palette. The palette is used by the
4242 widget's style when rendering standard components, and is available as a
4243 means to ensure that custom widgets can maintain consistency with the
4244 native platform's look and feel. It's common that different platforms, or
4245 different styles, have different palettes.
4247 When you assign a new palette to a widget, the color roles from this
4248 palette are combined with the widget's default palette to form the
4249 widget's final palette. The palette entry for the widget's background role
4250 is used to fill the widget's background (see QWidget::autoFillBackground),
4251 and the foreground role initializes QPainter's pen.
4253 The default depends on the system environment. QApplication maintains a
4254 system/theme palette which serves as a default for all widgets. There may
4255 also be special palette defaults for certain types of widgets (e.g., on
4256 Windows XP and Vista, all classes that derive from QMenuBar have a special
4257 default palette). You can also define default palettes for widgets
4258 yourself by passing a custom palette and the name of a widget to
4259 QApplication::setPalette(). Finally, the style always has the option of
4260 polishing the palette as it's assigned (see QStyle::polish()).
4262 QWidget propagates explicit palette roles from parent to child. If you
4263 assign a brush or color to a specific role on a palette and assign that
4264 palette to a widget, that role will propagate to all the widget's
4265 children, overriding any system defaults for that role. Note that palettes
4266 by default don't propagate to windows (see isWindow()) unless the
4267 Qt::WA_WindowPropagation attribute is enabled.
4269 QWidget's palette propagation is similar to its font propagation.
4271 The current style, which is used to render the content of all standard Qt
4272 widgets, is free to choose colors and brushes from the widget palette, or
4273 in some cases, to ignore the palette (partially, or completely). In
4274 particular, certain styles like GTK style, Mac style, Windows XP, and
4275 Vista style, depend on third party APIs to render the content of widgets,
4276 and these styles typically do not follow the palette. Because of this,
4277 assigning roles to a widget's palette is not guaranteed to change the
4278 appearance of the widget. Instead, you may choose to apply a \l
4279 styleSheet. You can refer to our Knowledge Base article
4280 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4283 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4284 When using style sheets, the palette of a widget can be customized using
4285 the "color", "background-color", "selection-color",
4286 "selection-background-color" and "alternate-background-color".
4288 \sa QApplication::palette(), QWidget::font()
4290 const QPalette &QWidget::palette() const
4293 data->pal.setCurrentColorGroup(QPalette::Disabled);
4294 } else if ((!isVisible() || isActiveWindow())
4295 #if defined(Q_OS_WIN) && !defined(Q_WS_WINCE)
4296 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4299 data->pal.setCurrentColorGroup(QPalette::Active);
4302 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4303 if (qt_mac_can_clickThrough(this))
4304 data->pal.setCurrentColorGroup(QPalette::Active);
4307 data->pal.setCurrentColorGroup(QPalette::Inactive);
4312 void QWidget::setPalette(const QPalette &palette)
4315 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4317 // Determine which palette is inherited from this widget's ancestors and
4318 // QApplication::palette, resolve this against \a palette (attributes from
4319 // the inherited palette are copied over this widget's palette). Then
4320 // propagate this palette to this widget's children.
4321 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4322 QPalette resolvedPalette = palette.resolve(naturalPalette);
4323 d->setPalette_helper(resolvedPalette);
4329 Returns the palette that the widget \a w inherits from its ancestors and
4330 QApplication::palette. \a inheritedMask is the combination of the widget's
4331 ancestors palette request masks (i.e., which attributes from the parent
4332 widget's palette are implicitly imposed on this widget by the user). Note
4333 that this font does not take into account the palette set on \a w itself.
4335 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4338 QPalette naturalPalette = QApplication::palette(q);
4339 if (!q->testAttribute(Qt::WA_StyleSheet)
4340 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4341 #ifndef QT_NO_GRAPHICSVIEW
4342 || (extra && extra->proxyWidget)
4343 #endif //QT_NO_GRAPHICSVIEW
4345 if (QWidget *p = q->parentWidget()) {
4346 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4347 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4348 QPalette inheritedPalette = p->palette();
4349 inheritedPalette.resolve(inheritedMask);
4350 naturalPalette = inheritedPalette.resolve(naturalPalette);
4352 naturalPalette = p->palette();
4356 #ifndef QT_NO_GRAPHICSVIEW
4357 else if (extra && extra->proxyWidget) {
4358 QPalette inheritedPalette = extra->proxyWidget->palette();
4359 inheritedPalette.resolve(inheritedMask);
4360 naturalPalette = inheritedPalette.resolve(naturalPalette);
4362 #endif //QT_NO_GRAPHICSVIEW
4364 naturalPalette.resolve(0);
4365 return naturalPalette;
4370 Determine which palette is inherited from this widget's ancestors and
4371 QApplication::palette, resolve this against this widget's palette
4372 (attributes from the inherited palette are copied over this widget's
4373 palette). Then propagate this palette to this widget's children.
4375 void QWidgetPrivate::resolvePalette()
4377 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4378 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4379 setPalette_helper(resolvedPalette);
4382 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4385 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4388 updateSystemBackground();
4389 propagatePaletteChange();
4396 \property QWidget::font
4397 \brief the font currently set for the widget
4399 This property describes the widget's requested font. The font is used by
4400 the widget's style when rendering standard components, and is available as
4401 a means to ensure that custom widgets can maintain consistency with the
4402 native platform's look and feel. It's common that different platforms, or
4403 different styles, define different fonts for an application.
4405 When you assign a new font to a widget, the properties from this font are
4406 combined with the widget's default font to form the widget's final
4407 font. You can call fontInfo() to get a copy of the widget's final
4408 font. The final font is also used to initialize QPainter's font.
4410 The default depends on the system environment. QApplication maintains a
4411 system/theme font which serves as a default for all widgets. There may
4412 also be special font defaults for certain types of widgets. You can also
4413 define default fonts for widgets yourself by passing a custom font and the
4414 name of a widget to QApplication::setFont(). Finally, the font is matched
4415 against Qt's font database to find the best match.
4417 QWidget propagates explicit font properties from parent to child. If you
4418 change a specific property on a font and assign that font to a widget,
4419 that property will propagate to all the widget's children, overriding any
4420 system defaults for that property. Note that fonts by default don't
4421 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4422 attribute is enabled.
4424 QWidget's font propagation is similar to its palette propagation.
4426 The current style, which is used to render the content of all standard Qt
4427 widgets, is free to choose to use the widget font, or in some cases, to
4428 ignore it (partially, or completely). In particular, certain styles like
4429 GTK style, Mac style, Windows XP, and Vista style, apply special
4430 modifications to the widget font to match the platform's native look and
4431 feel. Because of this, assigning properties to a widget's font is not
4432 guaranteed to change the appearance of the widget. Instead, you may choose
4433 to apply a \l styleSheet.
4435 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4436 style sheets will take precedence if the settings conflict.
4438 \sa fontInfo(), fontMetrics()
4441 void QWidget::setFont(const QFont &font)
4445 #ifndef QT_NO_STYLE_STYLESHEET
4446 const QStyleSheetStyle* style;
4447 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4448 style->saveWidgetFont(this, font);
4452 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4454 // Determine which font is inherited from this widget's ancestors and
4455 // QApplication::font, resolve this against \a font (attributes from the
4456 // inherited font are copied over). Then propagate this font to this
4457 // widget's children.
4458 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4459 QFont resolvedFont = font.resolve(naturalFont);
4460 d->setFont_helper(resolvedFont);
4466 Returns the font that the widget \a w inherits from its ancestors and
4467 QApplication::font. \a inheritedMask is the combination of the widget's
4468 ancestors font request masks (i.e., which attributes from the parent
4469 widget's font are implicitly imposed on this widget by the user). Note
4470 that this font does not take into account the font set on \a w itself.
4472 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4473 is applied, fonts are not propagated anymore
4475 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4478 QFont naturalFont = QApplication::font(q);
4479 if (!q->testAttribute(Qt::WA_StyleSheet)
4480 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4481 #ifndef QT_NO_GRAPHICSVIEW
4482 || (extra && extra->proxyWidget)
4483 #endif //QT_NO_GRAPHICSVIEW
4485 if (QWidget *p = q->parentWidget()) {
4486 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4487 if (!naturalFont.isCopyOf(QApplication::font())) {
4488 QFont inheritedFont = p->font();
4489 inheritedFont.resolve(inheritedMask);
4490 naturalFont = inheritedFont.resolve(naturalFont);
4492 naturalFont = p->font();
4496 #ifndef QT_NO_GRAPHICSVIEW
4497 else if (extra && extra->proxyWidget) {
4498 QFont inheritedFont = extra->proxyWidget->font();
4499 inheritedFont.resolve(inheritedMask);
4500 naturalFont = inheritedFont.resolve(naturalFont);
4502 #endif //QT_NO_GRAPHICSVIEW
4504 naturalFont.resolve(0);
4511 Determine which font is implicitly imposed on this widget by its ancestors
4512 and QApplication::font, resolve this against its own font (attributes from
4513 the implicit font are copied over). Then propagate this font to this
4516 void QWidgetPrivate::resolveFont()
4518 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4519 QFont resolvedFont = data.fnt.resolve(naturalFont);
4520 setFont_helper(resolvedFont);
4526 Assign \a font to this widget, and propagate it to all children, except
4527 style sheet widgets (handled differently) and windows that don't enable
4528 window propagation. \a implicitMask is the union of all ancestor widgets'
4529 font request masks, and determines which attributes from this widget's
4530 font should propagate.
4532 void QWidgetPrivate::updateFont(const QFont &font)
4535 #ifndef QT_NO_STYLE_STYLESHEET
4536 const QStyleSheetStyle* cssStyle;
4537 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4540 data.fnt = QFont(font, q);
4541 #if defined(Q_WS_X11)
4542 // make sure the font set on this widget is associated with the correct screen
4543 data.fnt.x11SetScreen(xinfo.screen());
4545 // Combine new mask with natural mask and propagate to children.
4546 #ifndef QT_NO_GRAPHICSVIEW
4547 if (!q->parentWidget() && extra && extra->proxyWidget) {
4548 QGraphicsProxyWidget *p = extra->proxyWidget;
4549 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4551 #endif //QT_NO_GRAPHICSVIEW
4552 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4553 inheritedFontResolveMask = 0;
4555 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4557 for (int i = 0; i < children.size(); ++i) {
4558 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4561 #ifndef QT_NO_STYLE_STYLESHEET
4562 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4563 // Style sheets follow a different font propagation scheme.
4565 cssStyle->updateStyleSheetFont(w);
4567 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4568 // Propagate font changes.
4569 QWidgetPrivate *wd = w->d_func();
4570 wd->inheritedFontResolveMask = newMask;
4576 #ifndef QT_NO_STYLE_STYLESHEET
4578 cssStyle->updateStyleSheetFont(q);
4582 QEvent e(QEvent::FontChange);
4583 QApplication::sendEvent(q, &e);
4586 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4590 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4592 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4593 if (!children.isEmpty()) {
4594 for (int i = 0; i < children.size(); ++i) {
4595 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4596 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4597 w->d_func()->setLayoutDirection_helper(direction);
4600 QEvent e(QEvent::LayoutDirectionChange);
4601 QApplication::sendEvent(q, &e);
4604 void QWidgetPrivate::resolveLayoutDirection()
4607 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4608 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4612 \property QWidget::layoutDirection
4614 \brief the layout direction for this widget
4616 By default, this property is set to Qt::LeftToRight.
4618 When the layout direction is set on a widget, it will propagate to
4619 the widget's children, but not to a child that is a window and not
4620 to a child for which setLayoutDirection() has been explicitly
4621 called. Also, child widgets added \e after setLayoutDirection()
4622 has been called for the parent do not inherit the parent's layout
4625 This method no longer affects text layout direction since Qt 4.7.
4627 \sa QApplication::layoutDirection
4629 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4633 if (direction == Qt::LayoutDirectionAuto) {
4634 unsetLayoutDirection();
4638 setAttribute(Qt::WA_SetLayoutDirection);
4639 d->setLayoutDirection_helper(direction);
4642 Qt::LayoutDirection QWidget::layoutDirection() const
4644 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4647 void QWidget::unsetLayoutDirection()
4650 setAttribute(Qt::WA_SetLayoutDirection, false);
4651 d->resolveLayoutDirection();
4655 \fn QFontMetrics QWidget::fontMetrics() const
4657 Returns the font metrics for the widget's current font.
4658 Equivalent to QFontMetrics(widget->font()).
4660 \sa font(), fontInfo(), setFont()
4664 \fn QFontInfo QWidget::fontInfo() const
4666 Returns the font info for the widget's current font.
4667 Equivalent to QFontInto(widget->font()).
4669 \sa font(), fontMetrics(), setFont()
4674 \property QWidget::cursor
4675 \brief the cursor shape for this widget
4677 The mouse cursor will assume this shape when it's over this
4678 widget. See the \link Qt::CursorShape list of predefined cursor
4679 objects\endlink for a range of useful shapes.
4681 An editor widget might use an I-beam cursor:
4682 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4684 If no cursor has been set, or after a call to unsetCursor(), the
4685 parent's cursor is used.
4687 By default, this property contains a cursor with the Qt::ArrowCursor
4690 Some underlying window implementations will reset the cursor if it
4691 leaves a widget even if the mouse is grabbed. If you want to have
4692 a cursor set for all widgets, even when outside the window, consider
4693 QApplication::setOverrideCursor().
4695 \sa QApplication::setOverrideCursor()
4698 #ifndef QT_NO_CURSOR
4699 QCursor QWidget::cursor() const
4702 if (testAttribute(Qt::WA_SetCursor))
4703 return (d->extra && d->extra->curs)
4705 : QCursor(Qt::ArrowCursor);
4706 if (isWindow() || !parentWidget())
4707 return QCursor(Qt::ArrowCursor);
4708 return parentWidget()->cursor();
4711 void QWidget::setCursor(const QCursor &cursor)
4714 // On Mac we must set the cursor even if it is the ArrowCursor.
4715 #if !defined(Q_WS_MAC)
4716 if (cursor.shape() != Qt::ArrowCursor
4717 || (d->extra && d->extra->curs))
4721 QCursor *newCursor = new QCursor(cursor);
4722 delete d->extra->curs;
4723 d->extra->curs = newCursor;
4725 setAttribute(Qt::WA_SetCursor);
4726 d->setCursor_sys(cursor);
4728 QEvent event(QEvent::CursorChange);
4729 QApplication::sendEvent(this, &event);
4732 void QWidget::unsetCursor()
4736 delete d->extra->curs;
4740 setAttribute(Qt::WA_SetCursor, false);
4741 d->unsetCursor_sys();
4743 QEvent event(QEvent::CursorChange);
4744 QApplication::sendEvent(this, &event);
4750 \enum QWidget::RenderFlag
4752 This enum describes how to render the widget when calling QWidget::render().
4754 \value DrawWindowBackground If you enable this option, the widget's background
4755 is rendered into the target even if autoFillBackground is not set. By default,
4756 this option is enabled.
4758 \value DrawChildren If you enable this option, the widget's children
4759 are rendered recursively into the target. By default, this option is enabled.
4761 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4762 is ignored when rendering into the target. By default, this option is disabled.
4770 Renders the \a sourceRegion of this widget into the \a target
4771 using \a renderFlags to determine how to render. Rendering
4772 starts at \a targetOffset in the \a target. For example:
4774 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4776 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4777 the region, i.e. the entire widget.
4779 Ensure that you call QPainter::end() for the \a target device's
4780 active painter (if any) before rendering. For example:
4782 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4784 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4785 or QGLWidget::renderPixmap() instead.
4787 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4788 const QRegion &sourceRegion, RenderFlags renderFlags)
4790 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4796 Renders the widget into the \a painter's QPainter::device().
4798 Transformations and settings applied to the \a painter will be used
4801 \note The \a painter must be active. On Mac OS X the widget will be
4802 rendered into a QPixmap and then drawn by the \a painter.
4804 \sa QPainter::device()
4806 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4807 const QRegion &sourceRegion, RenderFlags renderFlags)
4810 qWarning("QWidget::render: Null pointer to painter");
4814 if (!painter->isActive()) {
4815 qWarning("QWidget::render: Cannot render with an inactive painter");
4819 const qreal opacity = painter->opacity();
4820 if (qFuzzyIsNull(opacity))
4821 return; // Fully transparent.
4824 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4825 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4827 if (toBePainted.isEmpty())
4832 d->extra->inRenderWithPainter = true;
4835 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4837 QPaintEngine *engine = painter->paintEngine();
4839 QPaintEnginePrivate *enginePriv = engine->d_func();
4840 Q_ASSERT(enginePriv);
4841 QPaintDevice *target = engine->paintDevice();
4844 // Render via a pixmap when dealing with non-opaque painters or printers.
4845 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4846 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4847 d->extra->inRenderWithPainter = false;
4851 // Set new shared painter.
4852 QPainter *oldPainter = d->sharedPainter();
4853 d->setSharedPainter(painter);
4855 // Save current system clip, viewport and transform,
4856 const QTransform oldTransform = enginePriv->systemTransform;
4857 const QRegion oldSystemClip = enginePriv->systemClip;
4858 const QRegion oldSystemViewport = enginePriv->systemViewport;
4860 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4861 if (painter->hasClipping()) {
4862 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4863 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4865 enginePriv->setSystemViewport(oldSystemClip);
4868 render(target, targetOffset, toBePainted, renderFlags);
4870 // Restore system clip, viewport and transform.
4871 enginePriv->systemClip = oldSystemClip;
4872 enginePriv->setSystemViewport(oldSystemViewport);
4873 enginePriv->setSystemTransform(oldTransform);
4875 // Restore shared painter.
4876 d->setSharedPainter(oldPainter);
4879 d->extra->inRenderWithPainter = false;
4882 static void sendResizeEvents(QWidget *target)
4884 QResizeEvent e(target->size(), QSize());
4885 QApplication::sendEvent(target, &e);
4887 const QObjectList children = target->children();
4888 for (int i = 0; i < children.size(); ++i) {
4889 QWidget *child = static_cast<QWidget*>(children.at(i));
4890 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4891 sendResizeEvents(child);
4898 Renders the widget into a pixmap restricted by the
4899 given \a rectangle. If the \a widget has any children, then
4900 they are also painted in the appropriate positions.
4902 If no rectangle is specified (the default) the entire widget is
4905 Replacement for Qt 4's QPixmap::grabWidget().
4907 \sa render(), QPixmap
4910 /* INVOKABLE since used by QPixmap::grabWidget(). */
4911 QPixmap QWidget::grab(const QRect &rectangle)
4914 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4915 sendResizeEvents(this);
4921 r.setWidth(width() - rectangle.x());
4923 r.setHeight(height() - rectangle.y());
4925 if (!r.intersects(rect()))
4928 QPixmap res(r.size());
4930 res.fill(Qt::transparent);
4931 render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
4932 | QWidget::DrawChildren | QWidget::IgnoreMask);
4937 \brief The graphicsEffect function returns a pointer to the
4938 widget's graphics effect.
4940 If the widget has no graphics effect, 0 is returned.
4944 \sa setGraphicsEffect()
4946 #ifndef QT_NO_GRAPHICSEFFECT
4947 QGraphicsEffect *QWidget::graphicsEffect() const
4950 return d->graphicsEffect;
4952 #endif //QT_NO_GRAPHICSEFFECT
4956 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4958 Sets \a effect as the widget's effect. If there already is an effect installed
4959 on this widget, QWidget will delete the existing effect before installing
4962 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4963 the effect from the widget and install it on this widget.
4965 QWidget takes ownership of \a effect.
4967 \note This function will apply the effect on itself and all its children.
4971 \sa graphicsEffect()
4973 #ifndef QT_NO_GRAPHICSEFFECT
4974 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4977 if (d->graphicsEffect == effect)
4980 if (d->graphicsEffect) {
4981 d->invalidateBuffer(rect());
4982 delete d->graphicsEffect;
4983 d->graphicsEffect = 0;
4988 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4989 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4990 d->graphicsEffect = effect;
4991 effect->d_func()->setGraphicsEffectSource(source);
4995 d->updateIsOpaque();
4997 #endif //QT_NO_GRAPHICSEFFECT
4999 bool QWidgetPrivate::isAboutToShow() const
5008 // The widget will be shown if any of its ancestors are about to show.
5009 QWidget *parent = q->parentWidget();
5010 return parent ? parent->d_func()->isAboutToShow() : false;
5013 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
5016 const bool isVisible = q->isVisible();
5018 // Make sure the widget is laid out correctly.
5019 if (!isVisible && !isAboutToShow()) {
5020 QWidget *topLevel = q->window();
5021 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
5022 topLevel->ensurePolished();
5024 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
5025 // they're not explicitly hidden.
5026 QWidget *widget = q;
5027 QWidgetList hiddenWidgets;
5029 if (widget->isHidden()) {
5030 widget->setAttribute(Qt::WA_WState_Hidden, false);
5031 hiddenWidgets.append(widget);
5032 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
5033 widget->d_func()->updateGeometry_helper(true);
5035 widget = widget->parentWidget();
5038 // Activate top-level layout.
5039 if (topLevel->d_func()->layout)
5040 topLevel->d_func()->layout->activate();
5042 // Adjust size if necessary.
5043 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
5044 if (topLevelExtra && !topLevelExtra->sizeAdjusted
5045 && !topLevel->testAttribute(Qt::WA_Resized)) {
5046 topLevel->adjustSize();
5047 topLevel->setAttribute(Qt::WA_Resized, false);
5050 // Activate child layouts.
5051 topLevel->d_func()->activateChildLayoutsRecursively();
5053 // We're not cheating with WA_WState_Hidden anymore.
5054 for (int i = 0; i < hiddenWidgets.size(); ++i) {
5055 QWidget *widget = hiddenWidgets.at(i);
5056 widget->setAttribute(Qt::WA_WState_Hidden);
5057 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
5058 widget->parentWidget()->d_func()->layout->invalidate();
5060 } else if (isVisible) {
5061 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
5064 // Calculate the region to be painted.
5065 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
5066 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
5067 toBePainted &= extra->mask;
5071 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
5072 QWidget::RenderFlags renderFlags)
5075 Q_ASSERT(!toBePainted.isEmpty());
5079 const QTransform originalTransform = painter->worldTransform();
5080 const bool useDeviceCoordinates = originalTransform.isScaling();
5081 if (!useDeviceCoordinates) {
5083 // Render via a pixmap.
5084 const QRect rect = toBePainted.boundingRect();
5085 const QSize size = rect.size();
5089 QPixmap pixmap(size);
5090 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
5091 pixmap.fill(Qt::transparent);
5092 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
5094 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
5095 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
5097 painter->drawPixmap(targetOffset, pixmap);
5100 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
5104 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
5105 QTransform transform = originalTransform;
5106 transform.translate(targetOffset.x(), targetOffset.y());
5108 QPaintDevice *device = painter->device();
5111 // Calculate device rect.
5112 const QRectF rect(toBePainted.boundingRect());
5113 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
5114 deviceRect &= QRect(0, 0, device->width(), device->height());
5116 QPixmap pixmap(deviceRect.size());
5117 pixmap.fill(Qt::transparent);
5119 // Create a pixmap device coordinate painter.
5120 QPainter pixmapPainter(&pixmap);
5121 pixmapPainter.setRenderHints(painter->renderHints());
5122 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
5123 pixmapPainter.setTransform(transform);
5125 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
5126 pixmapPainter.end();
5128 // And then draw the pixmap.
5129 painter->setTransform(QTransform());
5130 painter->drawPixmap(deviceRect.topLeft(), pixmap);
5131 painter->setTransform(originalTransform);
5136 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
5137 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5142 #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
5143 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5144 dirtyOnWidget = QRegion();
5146 // We disable the rendering of QToolBar in the backingStore if
5147 // it's supposed to be in the unified toolbar on Mac OS X.
5148 if (backingStore && isInUnifiedToolbar)
5150 #endif // Q_WS_MAC && QT_MAC_USE_COCOA
5154 #ifndef QT_NO_GRAPHICSEFFECT
5155 if (graphicsEffect && graphicsEffect->isEnabled()) {
5156 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5157 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5159 if (!sourced->context) {
5160 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5161 sourced->context = &context;
5162 if (!sharedPainter) {
5163 QPaintEngine *paintEngine = pdev->paintEngine();
5164 paintEngine->d_func()->systemClip = rgn.translated(offset);
5166 p.translate(offset);
5167 context.painter = &p;
5168 graphicsEffect->draw(&p);
5169 paintEngine->d_func()->systemClip = QRegion();
5171 context.painter = sharedPainter;
5172 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5173 sourced->invalidateCache();
5174 sourced->lastEffectTransform = sharedPainter->worldTransform();
5176 sharedPainter->save();
5177 sharedPainter->translate(offset);
5178 graphicsEffect->draw(sharedPainter);
5179 sharedPainter->restore();
5181 sourced->context = 0;
5185 #endif //QT_NO_GRAFFICSEFFECT
5187 const bool asRoot = flags & DrawAsRoot;
5188 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5189 const bool recursive = flags & DrawRecursive;
5190 const bool alsoInvisible = flags & DrawInvisible;
5192 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5194 QRegion toBePainted(rgn);
5195 if (asRoot && !alsoInvisible)
5196 toBePainted &= clipRect(); //(rgn & visibleRegion());
5197 if (!(flags & DontSubtractOpaqueChildren))
5198 subtractOpaqueChildren(toBePainted, q->rect());
5200 if (!toBePainted.isEmpty()) {
5201 bool onScreen = paintOnScreen();
5202 if (!onScreen || alsoOnScreen) {
5203 //update the "in paint event" flag
5204 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5205 qWarning("QWidget::repaint: Recursive repaint detected");
5206 q->setAttribute(Qt::WA_WState_InPaintEvent);
5208 //clip away the new area
5209 #ifndef QT_NO_PAINT_DEBUG
5210 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5212 QPaintEngine *paintEngine = pdev->paintEngine();
5214 setRedirected(pdev, -offset);
5217 // (Alien support) Special case for Mac when redirecting: If the paint device
5218 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5219 // outside the paint event is not supported on QWidgets. The attributeis
5220 // restored further down.
5221 if (pdev->devType() == QInternal::Widget)
5222 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5226 paintEngine->d_func()->systemClip = toBePainted;
5228 paintEngine->d_func()->systemRect = q->data->crect;
5230 //paint the background
5231 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5232 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5234 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5238 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5240 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5242 QColor tint = q->palette().window().color();
5243 tint.setAlphaF(qreal(.6));
5244 p.fillRect(toBePainted.boundingRect(), tint);
5249 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5250 qDebug() << "clipping to" << toBePainted << "location == " << offset
5251 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5254 //actually send the paint event
5255 QPaintEvent e(toBePainted);
5256 QCoreApplication::sendSpontaneousEvent(q, &e);
5257 #if !defined(Q_WS_QPA)
5258 if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
5259 backingStore->markDirtyOnScreen(toBePainted, q, offset);
5265 if (pdev->devType() == QInternal::Widget)
5266 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5268 restoreRedirected();
5270 paintEngine->d_func()->systemRect = QRect();
5272 paintEngine->d_func()->currentClipDevice = 0;
5273 paintEngine->d_func()->systemClip = QRegion();
5275 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5276 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5277 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5279 if (paintEngine && paintEngine->autoDestruct()) {
5283 #ifndef QT_NO_PAINT_DEBUG
5285 QWidgetBackingStore::unflushPaint(q, toBePainted);
5287 } else if (q->isWindow()) {
5288 QPaintEngine *engine = pdev->paintEngine();
5291 p.setClipRegion(toBePainted);
5292 const QBrush bg = q->palette().brush(QPalette::Window);
5293 if (bg.style() == Qt::TexturePattern)
5294 p.drawTiledPixmap(q->rect(), bg.texture());
5296 p.fillRect(q->rect(), bg);
5298 if (engine->autoDestruct())
5304 if (recursive && !children.isEmpty()) {
5305 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5306 , sharedPainter, backingStore);
5310 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5311 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5315 qWarning("QWidget::render: null pointer to paint device");
5319 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5320 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5321 ? prepareToRender(sourceRegion, renderFlags)
5323 if (paintRegion.isEmpty())
5327 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5329 // Use the target's shared painter if set (typically set when doing
5330 // "other->render(widget);" in the widget's paintEvent.
5331 if (target->devType() == QInternal::Widget) {
5332 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5333 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5334 QPainter *targetPainter = targetPrivate->sharedPainter();
5335 if (targetPainter && targetPainter->isActive())
5336 setSharedPainter(targetPainter);
5341 // Use the target's redirected device if set and adjust offset and paint
5342 // region accordingly. This is typically the case when people call render
5343 // from the paintEvent.
5344 QPoint offset = targetOffset;
5345 offset -= paintRegion.boundingRect().topLeft();
5346 QPoint redirectionOffset;
5347 QPaintDevice *redirected = 0;
5349 if (target->devType() == QInternal::Widget)
5350 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5352 redirected = QPainter::redirected(target, &redirectionOffset);
5355 target = redirected;
5356 offset -= redirectionOffset;
5359 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5360 if (QPaintEngine *targetEngine = target->paintEngine()) {
5361 const QRegion targetSystemClip = targetEngine->systemClip();
5362 if (!targetSystemClip.isEmpty())
5363 paintRegion &= targetSystemClip.translated(-offset);
5367 // Set backingstore flags.
5368 int flags = DrawPaintOnScreen | DrawInvisible;
5369 if (renderFlags & QWidget::DrawWindowBackground)
5370 flags |= DrawAsRoot;
5372 if (renderFlags & QWidget::DrawChildren)
5373 flags |= DrawRecursive;
5375 flags |= DontSubtractOpaqueChildren;
5377 if (target->devType() == QInternal::Printer) {
5379 render_helper(&p, targetOffset, paintRegion, renderFlags);
5384 // Render via backingstore.
5385 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5387 // Restore shared painter.
5388 if (oldSharedPainter)
5389 setSharedPainter(oldSharedPainter);
5391 // Render via backingstore (no shared painter).
5392 drawWidget(target, paintRegion, offset, flags, 0);
5396 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5397 const QPoint &offset, int flags
5398 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5402 bool dirtyBoundingRect = true;
5403 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5404 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5407 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5408 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5409 && !(excludeNativeChildren && x->internalWinId())) {
5410 if (dirtyBoundingRect) {
5411 boundingRect = rgn.boundingRect();
5412 dirtyBoundingRect = false;
5415 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5421 } while (index >= 0);
5426 QWidgetPrivate *wd = w->d_func();
5427 const QPoint widgetPos(w->data->crect.topLeft());
5428 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5432 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5433 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5434 , sharedPainter, backingStore);
5437 if (w->updatesEnabled()
5438 #ifndef QT_NO_GRAPHICSVIEW
5439 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5440 #endif //QT_NO_GRAPHICSVIEW
5442 QRegion wRegion(rgn);
5443 wRegion &= wd->effectiveRectFor(w->data->crect);
5444 wRegion.translate(-widgetPos);
5446 wRegion &= wd->extra->mask;
5447 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5451 #ifndef QT_NO_GRAPHICSEFFECT
5452 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5454 if (system != Qt::DeviceCoordinates)
5455 return m_widget->rect();
5458 // Device coordinates without context not yet supported.
5459 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5463 return context->painter->worldTransform().mapRect(m_widget->rect());
5466 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5468 if (!context || context->painter != painter) {
5469 m_widget->render(painter);
5473 // The region saved in the context is neither clipped to the rect
5474 // nor the mask, so we have to clip it here before calling drawWidget.
5475 QRegion toBePainted = context->rgn;
5476 toBePainted &= m_widget->rect();
5477 QWidgetPrivate *wd = qt_widget_private(m_widget);
5478 if (wd->extra && wd->extra->hasMask)
5479 toBePainted &= wd->extra->mask;
5481 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5482 context->sharedPainter, context->backingStore);
5485 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5486 QGraphicsEffect::PixmapPadMode mode) const
5488 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5489 if (!context && deviceCoordinates) {
5490 // Device coordinates without context not yet supported.
5491 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5495 QPoint pixmapOffset;
5496 QRectF sourceRect = m_widget->rect();
5498 if (deviceCoordinates) {
5499 const QTransform &painterTransform = context->painter->worldTransform();
5500 sourceRect = painterTransform.mapRect(sourceRect);
5501 pixmapOffset = painterTransform.map(pixmapOffset);
5506 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5507 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5508 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5509 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5511 effectRect = sourceRect.toAlignedRect();
5514 *offset = effectRect.topLeft();
5516 pixmapOffset -= effectRect.topLeft();
5518 QPixmap pixmap(effectRect.size());
5519 pixmap.fill(Qt::transparent);
5520 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5523 #endif //QT_NO_GRAPHICSEFFECT
5525 #ifndef QT_NO_GRAPHICSVIEW
5529 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5530 widget and its ancestors. The search starts at \a origin (inclusive).
5531 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5534 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5537 QWExtra *extra = origin->d_func()->extra;
5538 if (extra && extra->proxyWidget)
5539 return extra->proxyWidget;
5540 return nearestGraphicsProxyWidget(origin->parentWidget());
5547 \property QWidget::locale
5548 \brief the widget's locale
5551 As long as no special locale has been set, this is either
5552 the parent's locale or (if this widget is a top level widget),
5555 If the widget displays dates or numbers, these should be formatted
5556 using the widget's locale.
5558 \sa QLocale QLocale::setDefault()
5561 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5564 if (locale == loc && !forceUpdate)
5569 if (!children.isEmpty()) {
5570 for (int i = 0; i < children.size(); ++i) {
5571 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5574 if (w->testAttribute(Qt::WA_SetLocale))
5576 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5578 w->d_func()->setLocale_helper(loc, forceUpdate);
5581 QEvent e(QEvent::LocaleChange);
5582 QApplication::sendEvent(q, &e);
5585 void QWidget::setLocale(const QLocale &locale)
5589 setAttribute(Qt::WA_SetLocale);
5590 d->setLocale_helper(locale);
5593 QLocale QWidget::locale() const
5600 void QWidgetPrivate::resolveLocale()
5604 if (!q->testAttribute(Qt::WA_SetLocale)) {
5605 setLocale_helper(q->isWindow()
5607 : q->parentWidget()->locale());
5611 void QWidget::unsetLocale()
5614 setAttribute(Qt::WA_SetLocale, false);
5618 static QString constructWindowTitleFromFilePath(const QString &filePath)
5620 QFileInfo fi(filePath);
5621 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5623 QString appName = QApplication::applicationName();
5624 if (!appName.isEmpty())
5625 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5631 \property QWidget::windowTitle
5632 \brief the window title (caption)
5634 This property only makes sense for top-level widgets, such as
5635 windows and dialogs. If no caption has been set, the title is based of the
5636 \l windowFilePath. If neither of these is set, then the title is
5639 If you use the \l windowModified mechanism, the window title must
5640 contain a "[*]" placeholder, which indicates where the '*' should
5641 appear. Normally, it should appear right after the file name
5642 (e.g., "document1.txt[*] - Text Editor"). If the \l
5643 windowModified property is false (the default), the placeholder
5646 \sa windowIcon, windowIconText, windowModified, windowFilePath
5648 QString QWidget::windowTitle() const
5651 if (d->extra && d->extra->topextra) {
5652 if (!d->extra->topextra->caption.isEmpty())
5653 return d->extra->topextra->caption;
5654 if (!d->extra->topextra->filePath.isEmpty())
5655 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5661 Returns a modified window title with the [*] place holder
5662 replaced according to the rules described in QWidget::setWindowTitle
5664 This function assumes that "[*]" can be quoted by another
5665 "[*]", so it will replace two place holders by one and
5666 a single last one by either "*" or nothing depending on
5671 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5676 extern QString qt_eval_adapt_window_title(const QString &title);
5677 QString cap = qt_eval_adapt_window_title(title);
5679 QString cap = title;
5685 QLatin1String placeHolder("[*]");
5686 int placeHolderLength = 3; // QLatin1String doesn't have length()
5688 int index = cap.indexOf(placeHolder);
5690 // here the magic begins
5691 while (index != -1) {
5692 index += placeHolderLength;
5694 while (cap.indexOf(placeHolder, index) == index) {
5696 index += placeHolderLength;
5699 if (count%2) { // odd number of [*] -> replace last one
5700 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5701 if (widget->isWindowModified()
5702 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5703 cap.replace(lastIndex, 3, QWidget::tr("*"));
5705 cap.remove(lastIndex, 3);
5708 index = cap.indexOf(placeHolder, index);
5711 cap.replace(QLatin1String("[*][*]"), placeHolder);
5716 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5719 if (q->testAttribute(Qt::WA_WState_Created))
5720 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5723 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5726 if (q->testAttribute(Qt::WA_WState_Created))
5727 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5730 void QWidget::setWindowIconText(const QString &iconText)
5732 if (QWidget::windowIconText() == iconText)
5736 d->topData()->iconText = iconText;
5737 d->setWindowIconText_helper(iconText);
5739 QEvent e(QEvent::IconTextChange);
5740 QApplication::sendEvent(this, &e);
5743 void QWidget::setWindowTitle(const QString &title)
5745 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5749 d->topData()->caption = title;
5750 d->setWindowTitle_helper(title);
5752 QEvent e(QEvent::WindowTitleChange);
5753 QApplication::sendEvent(this, &e);
5758 \property QWidget::windowIcon
5759 \brief the widget's icon
5761 This property only makes sense for windows. If no icon
5762 has been set, windowIcon() returns the application icon
5763 (QApplication::windowIcon()).
5765 \sa windowIconText, windowTitle
5767 QIcon QWidget::windowIcon() const
5769 const QWidget *w = this;
5771 const QWidgetPrivate *d = w->d_func();
5772 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5773 return *d->extra->topextra->icon;
5774 w = w->parentWidget();
5776 return QApplication::windowIcon();
5779 void QWidgetPrivate::setWindowIcon_helper()
5781 QEvent e(QEvent::WindowIconChange);
5782 QApplication::sendEvent(q_func(), &e);
5783 for (int i = 0; i < children.size(); ++i) {
5784 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5785 if (w && !w->isWindow())
5786 QApplication::sendEvent(w, &e);
5790 void QWidget::setWindowIcon(const QIcon &icon)
5794 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5797 if (!d->extra->topextra->icon)
5798 d->extra->topextra->icon = new QIcon();
5799 *d->extra->topextra->icon = icon;
5801 delete d->extra->topextra->iconPixmap;
5802 d->extra->topextra->iconPixmap = 0;
5804 d->setWindowIcon_sys();
5805 d->setWindowIcon_helper();
5810 \property QWidget::windowIconText
5811 \brief the widget's icon text
5813 This property only makes sense for windows. If no icon
5814 text has been set, this functions returns an empty string.
5816 \sa windowIcon, windowTitle
5819 QString QWidget::windowIconText() const
5822 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5826 \property QWidget::windowFilePath
5828 \brief the file path associated with a widget
5830 This property only makes sense for windows. It associates a file path with
5831 a window. If you set the file path, but have not set the window title, Qt
5832 sets the window title to contain a string created using the following
5838 \o The file name of the specified path, obtained using QFileInfo::fileName().
5844 \o The file name of the specified path, obtained using QFileInfo::fileName().
5845 \o An optional \c{*} character, if the \l windowModified property is set.
5846 \o The \c{0x2014} unicode character, padded either side by spaces.
5847 \o The application name, obtained from the application's
5848 \l{QCoreApplication::}{applicationName} property.
5851 If the window title is set at any point, then the window title takes precedence and
5852 will be shown instead of the file path string.
5854 Additionally, on Mac OS X, this has an added benefit that it sets the
5855 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5856 for the window, assuming that the file path exists.
5858 If no file path is set, this property contains an empty string.
5860 By default, this property contains an empty string.
5862 \sa windowTitle, windowIcon
5865 QString QWidget::windowFilePath() const
5868 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5871 void QWidget::setWindowFilePath(const QString &filePath)
5873 if (filePath == windowFilePath())
5879 d->extra->topextra->filePath = filePath;
5880 d->setWindowFilePath_helper(filePath);
5883 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5885 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5887 setWindowTitle_helper(QFileInfo(filePath).fileName());
5891 setWindowTitle_helper(q->windowTitle());
5895 setWindowFilePath_sys(filePath);
5900 Returns the window's role, or an empty string.
5902 \sa windowIcon, windowTitle
5905 QString QWidget::windowRole() const
5908 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5912 Sets the window's role to \a role. This only makes sense for
5915 void QWidget::setWindowRole(const QString &role)
5917 #if defined(Q_WS_X11)
5919 d->topData()->role = role;
5927 \property QWidget::mouseTracking
5928 \brief whether mouse tracking is enabled for the widget
5930 If mouse tracking is disabled (the default), the widget only
5931 receives mouse move events when at least one mouse button is
5932 pressed while the mouse is being moved.
5934 If mouse tracking is enabled, the widget receives mouse move
5935 events even if no buttons are pressed.
5937 \sa mouseMoveEvent()
5942 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5943 function resets this widget to have no focus proxy.
5945 Some widgets can "have focus", but create a child widget, such as
5946 QLineEdit, to actually handle the focus. In this case, the widget
5947 can set the line edit to be its focus proxy.
5949 setFocusProxy() sets the widget which will actually get focus when
5950 "this widget" gets it. If there is a focus proxy, setFocus() and
5951 hasFocus() operate on the focus proxy.
5956 void QWidget::setFocusProxy(QWidget * w)
5959 if (!w && !d->extra)
5962 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5964 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5970 d->extra->focus_proxy = w;
5975 Returns the focus proxy, or 0 if there is no focus proxy.
5980 QWidget * QWidget::focusProxy() const
5983 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5988 \property QWidget::focus
5989 \brief whether this widget (or its focus proxy) has the keyboard
5992 By default, this property is false.
5994 \note Obtaining the value of this property for a widget is effectively equivalent
5995 to checking whether QApplication::focusWidget() refers to the widget.
5997 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5999 bool QWidget::hasFocus() const
6001 const QWidget* w = this;
6002 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
6003 w = w->d_func()->extra->focus_proxy;
6004 if (QWidget *window = w->window()) {
6005 #ifndef QT_NO_GRAPHICSVIEW
6006 QWExtra *e = window->d_func()->extra;
6007 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
6011 return (QApplication::focusWidget() == w);
6015 Gives the keyboard input focus to this widget (or its focus
6016 proxy) if this widget or one of its parents is the \link
6017 isActiveWindow() active window\endlink. The \a reason argument will
6018 be passed into any focus event sent from this function, it is used
6019 to give an explanation of what caused the widget to get focus.
6020 If the window is not active, the widget will be given the focus when
6021 the window becomes active.
6023 First, a focus out event is sent to the focus widget (if any) to
6024 tell it that it is about to lose the focus. Then a focus in event
6025 is sent to this widget to tell it that it just received the focus.
6026 (Nothing happens if the focus in and focus out widgets are the
6029 \note On embedded platforms, setFocus() will not cause an input panel
6030 to be opened by the input method. If you want this to happen, you
6031 have to send a QEvent::RequestSoftwareInputPanel event to the
6034 setFocus() gives focus to a widget regardless of its focus policy,
6035 but does not clear any keyboard grab (see grabKeyboard()).
6037 Be aware that if the widget is hidden, it will not accept focus
6040 \warning If you call setFocus() in a function which may itself be
6041 called from focusOutEvent() or focusInEvent(), you may get an
6044 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
6045 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
6046 grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
6049 void QWidget::setFocus(Qt::FocusReason reason)
6055 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
6056 f = f->d_func()->extra->focus_proxy;
6058 if (QApplication::focusWidget() == f
6059 #if defined(Q_WS_WIN)
6060 && GetFocus() == f->internalWinId()
6065 #ifndef QT_NO_GRAPHICSVIEW
6066 QWidget *previousProxyFocus = 0;
6067 if (QWExtra *topData = window()->d_func()->extra) {
6068 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
6069 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
6070 if (previousProxyFocus && previousProxyFocus->focusProxy())
6071 previousProxyFocus = previousProxyFocus->focusProxy();
6072 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
6080 while (w && w->isHidden()) {
6081 w->d_func()->focus_child = f;
6082 w = w->isWindow() ? 0 : w->parentWidget();
6086 w->d_func()->focus_child = f;
6087 w = w->isWindow() ? 0 : w->parentWidget();
6091 #ifndef QT_NO_GRAPHICSVIEW
6092 // Update proxy state
6093 if (QWExtra *topData = window()->d_func()->extra) {
6094 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
6095 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
6096 topData->proxyWidget->setFocus(reason);
6097 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
6102 if (f->isActiveWindow()) {
6103 QApplicationPrivate::setFocusWidget(f, reason);
6104 #ifndef QT_NO_ACCESSIBILITY
6106 // The negation of the condition in setFocus_sys
6107 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
6108 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
6111 // menus update the focus manually and this would create bogus events
6112 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
6114 QAccessible::updateAccessibility(f, 0, QAccessible::Focus);
6116 #ifndef QT_NO_GRAPHICSVIEW
6117 if (QWExtra *topData = window()->d_func()->extra) {
6118 if (topData->proxyWidget) {
6119 if (previousProxyFocus && previousProxyFocus != f) {
6120 // Send event to self
6121 QFocusEvent event(QEvent::FocusOut, reason);
6122 QPointer<QWidget> that = previousProxyFocus;
6123 QApplication::sendEvent(previousProxyFocus, &event);
6125 QApplication::sendEvent(that->style(), &event);
6128 #ifndef QT_NO_GRAPHICSVIEW
6129 // Update proxy state
6130 if (QWExtra *topData = window()->d_func()->extra)
6131 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
6132 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
6134 // Send event to self
6135 QFocusEvent event(QEvent::FocusIn, reason);
6136 QPointer<QWidget> that = f;
6137 QApplication::sendEvent(f, &event);
6139 QApplication::sendEvent(that->style(), &event);
6148 \fn void QWidget::setFocus()
6151 Gives the keyboard input focus to this widget (or its focus
6152 proxy) if this widget or one of its parents is the
6153 \l{isActiveWindow()}{active window}.
6157 Takes keyboard input focus from the widget.
6159 If the widget has active focus, a \link focusOutEvent() focus out
6160 event\endlink is sent to this widget to tell it that it is about
6163 This widget must enable focus setting in order to get the keyboard
6164 input focus, i.e. it must call setFocusPolicy().
6166 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6167 setFocusPolicy(), QApplication::focusWidget()
6170 void QWidget::clearFocus()
6174 if (w->d_func()->focus_child == this)
6175 w->d_func()->focus_child = 0;
6176 w = w->parentWidget();
6178 #ifndef QT_NO_GRAPHICSVIEW
6179 QWExtra *topData = d_func()->extra;
6180 if (topData && topData->proxyWidget)
6181 topData->proxyWidget->clearFocus();
6185 // Update proxy state
6186 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6187 #if defined(Q_WS_WIN)
6188 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6193 #ifndef QT_NO_ACCESSIBILITY
6194 QAccessible::updateAccessibility(this, 0, QAccessible::Focus);
6202 \fn bool QWidget::focusNextChild()
6204 Finds a new widget to give the keyboard focus to, as appropriate
6205 for \key Tab, and returns true if it can find a new widget, or
6208 \sa focusPreviousChild()
6212 \fn bool QWidget::focusPreviousChild()
6214 Finds a new widget to give the keyboard focus to, as appropriate
6215 for \key Shift+Tab, and returns true if it can find a new widget,
6216 or false if it can't.
6218 \sa focusNextChild()
6222 Finds a new widget to give the keyboard focus to, as appropriate
6223 for Tab and Shift+Tab, and returns true if it can find a new
6224 widget, or false if it can't.
6226 If \a next is true, this function searches forward, if \a next
6227 is false, it searches backward.
6229 Sometimes, you will want to reimplement this function. For
6230 example, a web browser might reimplement it to move its "current
6231 active link" forward or backward, and call
6232 focusNextPrevChild() only when it reaches the last or
6233 first link on the "page".
6235 Child widgets call focusNextPrevChild() on their parent widgets,
6236 but only the window that contains the child widgets decides where
6237 to redirect focus. By reimplementing this function for an object,
6238 you thus gain control of focus traversal for all child widgets.
6240 \sa focusNextChild(), focusPreviousChild()
6243 bool QWidget::focusNextPrevChild(bool next)
6246 QWidget* p = parentWidget();
6247 bool isSubWindow = (windowType() == Qt::SubWindow);
6248 if (!isWindow() && !isSubWindow && p)
6249 return p->focusNextPrevChild(next);
6250 #ifndef QT_NO_GRAPHICSVIEW
6251 if (d->extra && d->extra->proxyWidget)
6252 return d->extra->proxyWidget->focusNextPrevChild(next);
6254 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6255 if (!w) return false;
6257 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6262 Returns the last child of this widget that setFocus had been
6263 called on. For top level widgets this is the widget that will get
6264 focus in case this window gets activated
6266 This is not the same as QApplication::focusWidget(), which returns
6267 the focus widget in the currently active window.
6270 QWidget *QWidget::focusWidget() const
6272 return const_cast<QWidget *>(d_func()->focus_child);
6276 Returns the next widget in this widget's focus chain.
6278 \sa previousInFocusChain()
6280 QWidget *QWidget::nextInFocusChain() const
6282 return const_cast<QWidget *>(d_func()->focus_next);
6286 \brief The previousInFocusChain function returns the previous
6287 widget in this widget's focus chain.
6289 \sa nextInFocusChain()
6293 QWidget *QWidget::previousInFocusChain() const
6295 return const_cast<QWidget *>(d_func()->focus_prev);
6299 \property QWidget::isActiveWindow
6300 \brief whether this widget's window is the active window
6302 The active window is the window that contains the widget that has
6303 keyboard focus (The window may still have focus if it has no
6304 widgets or none of its widgets accepts keyboard focus).
6306 When popup windows are visible, this property is true for both the
6307 active window \e and for the popup.
6309 By default, this property is false.
6311 \sa activateWindow(), QApplication::activeWindow()
6313 bool QWidget::isActiveWindow() const
6315 QWidget *tlw = window();
6316 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6319 #ifndef QT_NO_GRAPHICSVIEW
6320 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6321 if (isVisible() && tlwExtra->proxyWidget)
6322 return tlwExtra->proxyWidget->isActiveWindow();
6327 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6328 if(qt_mac_is_macdrawer(tlw) &&
6329 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6332 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6333 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6336 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6337 if(tlw->windowType() == Qt::Tool &&
6339 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6341 QWidget *w = QApplication::activeWindow();
6342 while(w && tlw->windowType() == Qt::Tool &&
6343 !w->isModal() && w->parentWidget()) {
6344 w = w->parentWidget()->window();
6349 #if defined(Q_WS_WIN32)
6350 HWND active = GetActiveWindow();
6351 if (!tlw->testAttribute(Qt::WA_WState_Created))
6353 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6360 Puts the \a second widget after the \a first widget in the focus order.
6362 Note that since the tab order of the \a second widget is changed, you
6363 should order a chain like this:
6365 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6369 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6371 If \a first or \a second has a focus proxy, setTabOrder()
6372 correctly substitutes the proxy.
6374 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6376 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6378 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6381 if (first->window() != second->window()) {
6382 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6386 QWidget *fp = first->focusProxy();
6388 // If first is redirected, set first to the last child of first
6389 // that can take keyboard focus so that second is inserted after
6390 // that last child, and the focus order within first is (more
6391 // likely to be) preserved.
6392 QList<QWidget *> l = first->findChildren<QWidget *>();
6393 for (int i = l.size()-1; i >= 0; --i) {
6394 QWidget * next = l.at(i);
6395 if (next->window() == fp->window()) {
6397 if (fp->focusPolicy() != Qt::NoFocus)
6407 if (QWidget *sp = second->focusProxy())
6410 // QWidget *fp = first->d_func()->focus_prev;
6411 QWidget *fn = first->d_func()->focus_next;
6413 if (fn == second || first == second)
6416 QWidget *sp = second->d_func()->focus_prev;
6417 QWidget *sn = second->d_func()->focus_next;
6419 fn->d_func()->focus_prev = second;
6420 first->d_func()->focus_next = second;
6422 second->d_func()->focus_next = fn;
6423 second->d_func()->focus_prev = first;
6425 sp->d_func()->focus_next = sn;
6426 sn->d_func()->focus_prev = sp;
6429 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6430 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6432 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6433 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6438 Moves the relevant subwidgets of this widget from the \a oldtlw's
6439 tab chain to that of the new parent, if there's anything to move and
6442 This function is called from QWidget::reparent() *after* the widget
6443 has been reparented.
6448 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6451 if (oldtlw == q->window())
6452 return; // nothing to do
6455 focus_child->clearFocus();
6457 // separate the focus chain into new (children of myself) and old (the rest)
6458 QWidget *firstOld = 0;
6459 //QWidget *firstNew = q; //invariant
6460 QWidget *o = 0; // last in the old list
6461 QWidget *n = q; // last in the new list
6463 bool prevWasNew = true;
6464 QWidget *w = focus_next;
6466 //Note: for efficiency, we do not maintain the list invariant inside the loop
6467 //we append items to the relevant list, and we optimize by not changing pointers
6468 //when subsequent items are going into the same list.
6470 bool currentIsNew = q->isAncestorOf(w);
6473 //prev was old -- append to new list
6474 n->d_func()->focus_next = w;
6475 w->d_func()->focus_prev = n;
6480 //prev was new -- append to old list, if there is one
6482 o->d_func()->focus_next = w;
6483 w->d_func()->focus_prev = o;
6485 // "create" the old list
6491 w = w->d_func()->focus_next;
6492 prevWasNew = currentIsNew;
6495 //repair the old list:
6497 o->d_func()->focus_next = firstOld;
6498 firstOld->d_func()->focus_prev = o;
6501 if (!q->isWindow()) {
6502 QWidget *topLevel = q->window();
6503 //insert new chain into toplevel's chain
6505 QWidget *prev = topLevel->d_func()->focus_prev;
6507 topLevel->d_func()->focus_prev = n;
6508 prev->d_func()->focus_next = q;
6511 n->d_func()->focus_next = topLevel;
6513 //repair the new list
6514 n->d_func()->focus_next = q;
6522 Measures the shortest distance from a point to a rect.
6524 This function is called from QDesktopwidget::screen(QPoint) to find the
6525 closest screen for a point.
6526 In directional KeypadNavigation, it is called to find the closest
6527 widget to the current focus widget center.
6529 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6533 if (p.x() < r.left())
6534 dx = r.left() - p.x();
6535 else if (p.x() > r.right())
6536 dx = p.x() - r.right();
6537 if (p.y() < r.top())
6538 dy = r.top() - p.y();
6539 else if (p.y() > r.bottom())
6540 dy = p.y() - r.bottom();
6545 \property QWidget::frameSize
6546 \brief the size of the widget including any window frame
6548 By default, this property contains a value that depends on the user's
6549 platform and screen geometry.
6551 QSize QWidget::frameSize() const
6554 if (isWindow() && !(windowType() == Qt::Popup)) {
6555 QRect fs = d->frameStrut();
6556 return QSize(data->crect.width() + fs.left() + fs.right(),
6557 data->crect.height() + fs.top() + fs.bottom());
6559 return data->crect.size();
6562 /*! \fn void QWidget::move(int x, int y)
6566 This corresponds to move(QPoint(\a x, \a y)).
6569 void QWidget::move(const QPoint &p)
6572 setAttribute(Qt::WA_Moved);
6574 d->topData()->posFromMove = true;
6575 if (testAttribute(Qt::WA_WState_Created)) {
6576 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6577 p.y() + geometry().y() - QWidget::y(),
6578 width(), height(), true);
6579 d->setDirtyOpaqueRegion();
6581 data->crect.moveTopLeft(p); // no frame yet
6582 setAttribute(Qt::WA_PendingMoveEvent);
6586 /*! \fn void QWidget::resize(int w, int h)
6589 This corresponds to resize(QSize(\a w, \a h)).
6592 void QWidget::resize(const QSize &s)
6595 setAttribute(Qt::WA_Resized);
6596 if (testAttribute(Qt::WA_WState_Created)) {
6597 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6598 d->setDirtyOpaqueRegion();
6600 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6601 setAttribute(Qt::WA_PendingResizeEvent);
6605 void QWidget::setGeometry(const QRect &r)
6608 setAttribute(Qt::WA_Resized);
6609 setAttribute(Qt::WA_Moved);
6611 d->topData()->posFromMove = false;
6612 if (testAttribute(Qt::WA_WState_Created)) {
6613 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6614 d->setDirtyOpaqueRegion();
6616 data->crect.setTopLeft(r.topLeft());
6617 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6618 setAttribute(Qt::WA_PendingMoveEvent);
6619 setAttribute(Qt::WA_PendingResizeEvent);
6625 Saves the current geometry and state for top-level widgets.
6627 To save the geometry when the window closes, you can
6628 implement a close event like this:
6630 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6632 See the \l{Window Geometry} documentation for an overview of geometry
6633 issues with windows.
6635 Use QMainWindow::saveState() to save the geometry and the state of
6636 toolbars and dock widgets.
6638 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6640 QByteArray QWidget::saveGeometry() const
6642 #ifdef QT_MAC_USE_COCOA
6643 // We check if the window was maximized during this invocation. If so, we need to record the
6644 // starting position as 0,0.
6646 QRect newFramePosition = frameGeometry();
6647 QRect newNormalPosition = normalGeometry();
6648 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6649 // Change the starting position
6650 newFramePosition.moveTo(0, 0);
6651 newNormalPosition.moveTo(0, 0);
6653 #endif // QT_MAC_USE_COCOA
6655 QDataStream stream(&array, QIODevice::WriteOnly);
6656 stream.setVersion(QDataStream::Qt_4_0);
6657 const quint32 magicNumber = 0x1D9D0CB;
6658 quint16 majorVersion = 1;
6659 quint16 minorVersion = 0;
6660 stream << magicNumber
6663 #ifdef QT_MAC_USE_COCOA
6665 << newNormalPosition
6669 #endif // QT_MAC_USE_COCOA
6670 << qint32(QApplication::desktop()->screenNumber(this))
6671 << quint8(windowState() & Qt::WindowMaximized)
6672 << quint8(windowState() & Qt::WindowFullScreen);
6679 Restores the geometry and state top-level widgets stored in the
6680 byte array \a geometry. Returns true on success; otherwise
6683 If the restored geometry is off-screen, it will be modified to be
6684 inside the available screen geometry.
6686 To restore geometry saved using QSettings, you can use code like
6689 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6691 See the \l{Window Geometry} documentation for an overview of geometry
6692 issues with windows.
6694 Use QMainWindow::restoreState() to restore the geometry and the
6695 state of toolbars and dock widgets.
6697 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6699 bool QWidget::restoreGeometry(const QByteArray &geometry)
6701 if (geometry.size() < 4)
6703 QDataStream stream(geometry);
6704 stream.setVersion(QDataStream::Qt_4_0);
6706 const quint32 magicNumber = 0x1D9D0CB;
6707 quint32 storedMagicNumber;
6708 stream >> storedMagicNumber;
6709 if (storedMagicNumber != magicNumber)
6712 const quint16 currentMajorVersion = 1;
6713 quint16 majorVersion = 0;
6714 quint16 minorVersion = 0;
6716 stream >> majorVersion >> minorVersion;
6718 if (majorVersion != currentMajorVersion)
6720 // (Allow all minor versions.)
6722 QRect restoredFrameGeometry;
6723 QRect restoredNormalGeometry;
6724 qint32 restoredScreenNumber;
6728 stream >> restoredFrameGeometry
6729 >> restoredNormalGeometry
6730 >> restoredScreenNumber
6734 const int frameHeight = 20;
6735 if (!restoredFrameGeometry.isValid())
6736 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6738 if (!restoredNormalGeometry.isValid())
6739 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6740 if (!restoredNormalGeometry.isValid()) {
6741 // use the widget's adjustedSize if the sizeHint() doesn't help
6742 restoredNormalGeometry.setSize(restoredNormalGeometry
6744 .expandedTo(d_func()->adjustedSize()));
6747 const QDesktopWidget * const desktop = QApplication::desktop();
6748 if (restoredScreenNumber >= desktop->numScreens())
6749 restoredScreenNumber = desktop->primaryScreen();
6751 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6753 // Modify the restored geometry if we are about to restore to coordinates
6754 // that would make the window "lost". This happens if:
6755 // - The restored geometry is completely oustside the available geometry
6756 // - The title bar is outside the available geometry.
6757 // - (Mac only) The window is higher than the available geometry. It must
6758 // be possible to bring the size grip on screen by moving the window.
6760 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6761 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6764 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6765 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6766 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6767 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6769 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6771 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6772 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6773 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6774 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6776 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6778 if (maximized || fullScreen) {
6779 // set geomerty before setting the window state to make
6780 // sure the window is maximized to the right screen.
6781 // Skip on windows: the window is restored into a broken
6782 // half-maximized state.
6784 setGeometry(restoredNormalGeometry);
6786 Qt::WindowStates ws = windowState();
6788 ws |= Qt::WindowMaximized;
6790 ws |= Qt::WindowFullScreen;
6792 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6797 offset = d_func()->topData()->fullScreenOffset;
6799 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6800 move(restoredFrameGeometry.topLeft() + offset);
6801 resize(restoredNormalGeometry.size());
6806 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6809 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6813 Sets the margins around the contents of the widget to have the sizes
6814 \a left, \a top, \a right, and \a bottom. The margins are used by
6815 the layout system, and may be used by subclasses to specify the area
6816 to draw in (e.g. excluding the frame).
6818 Changing the margins will trigger a resizeEvent().
6820 \sa contentsRect(), getContentsMargins()
6822 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6825 if (left == d->leftmargin && top == d->topmargin
6826 && right == d->rightmargin && bottom == d->bottommargin)
6828 d->leftmargin = left;
6830 d->rightmargin = right;
6831 d->bottommargin = bottom;
6833 if (QLayout *l=d->layout)
6834 l->update(); //force activate; will do updateGeometry
6838 // ### Qt 5: compat, remove
6841 QResizeEvent e(data->crect.size(), data->crect.size());
6842 QApplication::sendEvent(this, &e);
6844 setAttribute(Qt::WA_PendingResizeEvent, true);
6847 QEvent e(QEvent::ContentsRectChange);
6848 QApplication::sendEvent(this, &e);
6855 \brief The setContentsMargins function sets the margins around the
6858 Sets the margins around the contents of the widget to have the
6859 sizes determined by \a margins. The margins are
6860 used by the layout system, and may be used by subclasses to
6861 specify the area to draw in (e.g. excluding the frame).
6863 Changing the margins will trigger a resizeEvent().
6865 \sa contentsRect(), getContentsMargins()
6867 void QWidget::setContentsMargins(const QMargins &margins)
6869 setContentsMargins(margins.left(), margins.top(),
6870 margins.right(), margins.bottom());
6874 Returns the widget's contents margins for \a left, \a top, \a
6875 right, and \a bottom.
6877 \sa setContentsMargins(), contentsRect()
6879 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6883 *left = d->leftmargin;
6885 *top = d->topmargin;
6887 *right = d->rightmargin;
6889 *bottom = d->bottommargin;
6895 \brief The contentsMargins function returns the widget's contents margins.
6897 \sa getContentsMargins(), setContentsMargins(), contentsRect()
6899 QMargins QWidget::contentsMargins() const
6902 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6907 Returns the area inside the widget's margins.
6909 \sa setContentsMargins(), getContentsMargins()
6911 QRect QWidget::contentsRect() const
6914 return QRect(QPoint(d->leftmargin, d->topmargin),
6915 QPoint(data->crect.width() - 1 - d->rightmargin,
6916 data->crect.height() - 1 - d->bottommargin));
6923 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6925 This signal is emitted when the widget's \l contextMenuPolicy is
6926 Qt::CustomContextMenu, and the user has requested a context menu on
6927 the widget. The position \a pos is the position of the context menu
6928 event that the widget receives. Normally this is in widget
6929 coordinates. The exception to this rule is QAbstractScrollArea and
6930 its subclasses that map the context menu event to coordinates of the
6931 \link QAbstractScrollArea::viewport() viewport() \endlink .
6934 \sa mapToGlobal() QMenu contextMenuPolicy
6939 \property QWidget::contextMenuPolicy
6940 \brief how the widget shows a context menu
6942 The default value of this property is Qt::DefaultContextMenu,
6943 which means the contextMenuEvent() handler is called. Other values
6944 are Qt::NoContextMenu, Qt::PreventContextMenu,
6945 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6946 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6949 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6952 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6954 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6957 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6959 data->context_menu_policy = (uint) policy;
6963 \property QWidget::focusPolicy
6964 \brief the way the widget accepts keyboard focus
6966 The policy is Qt::TabFocus if the widget accepts keyboard
6967 focus by tabbing, Qt::ClickFocus if the widget accepts
6968 focus by clicking, Qt::StrongFocus if it accepts both, and
6969 Qt::NoFocus (the default) if it does not accept focus at
6972 You must enable keyboard focus for a widget if it processes
6973 keyboard events. This is normally done from the widget's
6974 constructor. For instance, the QLineEdit constructor calls
6975 setFocusPolicy(Qt::StrongFocus).
6977 If the widget has a focus proxy, then the focus policy will
6978 be propagated to it.
6980 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6984 Qt::FocusPolicy QWidget::focusPolicy() const
6986 return (Qt::FocusPolicy)data->focus_policy;
6989 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6991 data->focus_policy = (uint) policy;
6993 if (d->extra && d->extra->focus_proxy)
6994 d->extra->focus_proxy->setFocusPolicy(policy);
6998 \property QWidget::updatesEnabled
6999 \brief whether updates are enabled
7001 An updates enabled widget receives paint events and has a system
7002 background; a disabled widget does not. This also implies that
7003 calling update() and repaint() has no effect if updates are
7006 By default, this property is true.
7008 setUpdatesEnabled() is normally used to disable updates for a
7009 short period of time, for instance to avoid screen flicker during
7010 large changes. In Qt, widgets normally do not generate screen
7011 flicker, but on X11 the server might erase regions on the screen
7012 when widgets get hidden before they can be replaced by other
7013 widgets. Disabling updates solves this.
7016 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
7018 Disabling a widget implicitly disables all its children. Enabling a widget
7019 enables all child widgets \e except top-level widgets or those that
7020 have been explicitly disabled. Re-enabling updates implicitly calls
7021 update() on the widget.
7025 void QWidget::setUpdatesEnabled(bool enable)
7028 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
7029 d->setUpdatesEnabled_helper(enable);
7032 /*! \fn void QWidget::show()
7034 Shows the widget and its child widgets. This function is
7035 equivalent to setVisible(true).
7037 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
7038 showNormal(), isVisible()
7044 Makes the widget visible in the isVisible() meaning of the word.
7045 It is only called for toplevels or widgets with visible parents.
7047 void QWidgetPrivate::show_recursive()
7050 // polish if necessary
7052 if (!q->testAttribute(Qt::WA_WState_Created))
7053 createRecursively();
7054 q->ensurePolished();
7056 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
7057 q->parentWidget()->d_func()->layout->activate();
7058 // activate our layout before we and our children become visible
7065 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
7069 disableUpdates = disableUpdates && q->updatesEnabled();
7071 q->setAttribute(Qt::WA_UpdatesDisabled);
7073 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
7074 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
7075 QApplication::sendEvent(q, &e);
7076 q->setAttribute(Qt::WA_PendingMoveEvent, false);
7079 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
7080 QResizeEvent e(data.crect.size(), QSize());
7081 QApplication::sendEvent(q, &e);
7082 q->setAttribute(Qt::WA_PendingResizeEvent, false);
7086 q->setAttribute(Qt::WA_UpdatesDisabled, false);
7091 for (int i = 0; i < children.size(); ++i) {
7092 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
7093 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
7097 void QWidgetPrivate::activateChildLayoutsRecursively()
7099 sendPendingMoveAndResizeEvents(false, true);
7101 for (int i = 0; i < children.size(); ++i) {
7102 QWidget *child = qobject_cast<QWidget *>(children.at(i));
7103 if (!child || child->isHidden() || child->isWindow())
7106 child->ensurePolished();
7108 // Activate child's layout
7109 QWidgetPrivate *childPrivate = child->d_func();
7110 if (childPrivate->layout)
7111 childPrivate->layout->activate();
7113 // Pretend we're visible.
7114 const bool wasVisible = child->isVisible();
7116 child->setAttribute(Qt::WA_WState_Visible);
7118 // Do the same for all my children.
7119 childPrivate->activateChildLayoutsRecursively();
7121 // We're not cheating anymore.
7123 child->setAttribute(Qt::WA_WState_Visible, false);
7127 void QWidgetPrivate::show_helper()
7130 data.in_show = true; // qws optimization
7131 // make sure we receive pending move and resize events
7132 sendPendingMoveAndResizeEvents();
7134 // become visible before showing all children
7135 q->setAttribute(Qt::WA_WState_Visible);
7137 // finally show all children recursively
7138 showChildren(false);
7142 // popup handling: new popups and tools need to be raised, and
7143 // existing popups must be closed. Also propagate the current
7144 // windows's KeyboardFocusChange status.
7145 if (q->isWindow()) {
7146 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7148 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7149 q->setAttribute(Qt::WA_KeyboardFocusChange);
7151 while (QApplication::activePopupWidget()) {
7152 if (!QApplication::activePopupWidget()->close())
7158 // Automatic embedding of child windows of widgets already embedded into
7159 // QGraphicsProxyWidget when they are shown the first time.
7160 bool isEmbedded = false;
7161 #ifndef QT_NO_GRAPHICSVIEW
7162 if (q->isWindow()) {
7163 isEmbedded = q->graphicsProxyWidget() ? true : false;
7164 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7165 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7166 if (ancestorProxy) {
7168 ancestorProxy->d_func()->embedSubWindow(q);
7173 Q_UNUSED(isEmbedded);
7176 // On Windows, show the popup now so that our own focus handling
7177 // stores the correct old focus widget even if it's stolen in the
7179 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
7180 if (!isEmbedded && q->windowType() == Qt::Popup)
7181 qApp->d_func()->openPopup(q);
7184 // send the show event before showing the window
7185 QShowEvent showEvent;
7186 QApplication::sendEvent(q, &showEvent);
7188 if (!isEmbedded && q->isModal() && q->isWindow())
7189 // QApplicationPrivate::enterModal *before* show, otherwise the initial
7190 // stacking might be wrong
7191 QApplicationPrivate::enterModal(q);
7196 #if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN)
7197 if (!isEmbedded && q->windowType() == Qt::Popup)
7198 qApp->d_func()->openPopup(q);
7201 #ifndef QT_NO_ACCESSIBILITY
7202 if (q->windowType() != Qt::ToolTip) // Tooltips are read aloud twice in MS narrator.
7203 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectShow);
7206 if (QApplicationPrivate::hidden_focus_widget == q) {
7207 QApplicationPrivate::hidden_focus_widget = 0;
7208 q->setFocus(Qt::OtherFocusReason);
7211 // Process events when showing a Qt::SplashScreen widget before the event loop
7212 // is spinnning; otherwise it might not show up on particular platforms.
7213 // This makes QSplashScreen behave the same on all platforms.
7214 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7215 QApplication::processEvents();
7217 data.in_show = false; // reset qws optimization
7220 /*! \fn void QWidget::hide()
7222 Hides the widget. This function is equivalent to
7226 \note If you are working with QDialog or its subclasses and you invoke
7227 the show() function after this function, the dialog will be displayed in
7228 its original position.
7230 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7235 void QWidgetPrivate::hide_helper()
7239 bool isEmbedded = false;
7240 #if !defined QT_NO_GRAPHICSVIEW
7241 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7243 Q_UNUSED(isEmbedded);
7246 if (!isEmbedded && (q->windowType() == Qt::Popup))
7247 qApp->d_func()->closePopup(q);
7249 // Move test modal here. Otherwise, a modal dialog could get
7250 // destroyed and we lose all access to its parent because we haven't
7251 // left modality. (Eg. modal Progress Dialog)
7252 if (!isEmbedded && q->isModal() && q->isWindow())
7253 QApplicationPrivate::leaveModal(q);
7255 #if defined(Q_WS_WIN)
7256 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7257 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7258 q->parentWidget()->activateWindow(); // Activate parent
7261 q->setAttribute(Qt::WA_Mapped, false);
7264 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7267 q->setAttribute(Qt::WA_WState_Visible, false);
7271 QHideEvent hideEvent;
7272 QApplication::sendEvent(q, &hideEvent);
7273 hideChildren(false);
7275 // next bit tries to move the focus if the focus widget is now
7278 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7279 qApp->d_func()->sendSyntheticEnterLeave(q);
7282 QWidget *fw = QApplication::focusWidget();
7283 while (fw && !fw->isWindow()) {
7285 q->focusNextPrevChild(true);
7288 fw = fw->parentWidget();
7292 if (QWidgetBackingStore *bs = maybeBackingStore())
7293 bs->removeDirtyWidget(q);
7295 #ifndef QT_NO_ACCESSIBILITY
7297 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectHide);
7302 \fn bool QWidget::isHidden() const
7304 Returns true if the widget is hidden, otherwise returns false.
7306 A hidden widget will only become visible when show() is called on
7307 it. It will not be automatically shown when the parent is shown.
7309 To check visibility, use !isVisible() instead (notice the exclamation mark).
7311 isHidden() implies !isVisible(), but a widget can be not visible
7312 and not hidden at the same time. This is the case for widgets that are children of
7313 widgets that are not visible.
7316 Widgets are hidden if:
7318 \o they were created as independent windows,
7319 \o they were created as children of visible widgets,
7320 \o hide() or setVisible(false) was called.
7325 void QWidget::setVisible(bool visible)
7327 if (visible) { // show
7328 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7333 // Designer uses a trick to make grabWidget work without showing
7334 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7335 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7336 parentWidget()->window()->d_func()->createRecursively();
7338 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7339 //but not children of non-visible parents
7340 QWidget *pw = parentWidget();
7341 if (!testAttribute(Qt::WA_WState_Created)
7342 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7346 #if defined(Q_WS_X11)
7347 if (windowType() == Qt::Window)
7348 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7351 bool wasResized = testAttribute(Qt::WA_Resized);
7352 Qt::WindowStates initialWindowState = windowState();
7354 // polish if necessary
7357 // remember that show was called explicitly
7358 setAttribute(Qt::WA_WState_ExplicitShowHide);
7359 // whether we need to inform the parent widget immediately
7360 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7361 // we are no longer hidden
7362 setAttribute(Qt::WA_WState_Hidden, false);
7364 if (needUpdateGeometry)
7365 d->updateGeometry_helper(true);
7367 // activate our layout before we and our children become visible
7369 d->layout->activate();
7372 QWidget *parent = parentWidget();
7373 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7374 parent->d_func()->layout->activate();
7375 if (parent->isWindow())
7377 parent = parent->parentWidget();
7380 parent->d_func()->setDirtyOpaqueRegion();
7383 // adjust size if necessary
7385 && (isWindow() || !parentWidget()->d_func()->layout)) {
7388 if (windowState() != initialWindowState)
7389 setWindowState(initialWindowState);
7393 setAttribute(Qt::WA_Resized, false);
7396 setAttribute(Qt::WA_KeyboardFocusChange, false);
7398 if (isWindow() || parentWidget()->isVisible()) {
7399 // remove posted quit events when showing a new window
7400 QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
7404 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7405 qApp->d_func()->sendSyntheticEnterLeave(this);
7409 QEvent showToParentEvent(QEvent::ShowToParent);
7410 QApplication::sendEvent(this, &showToParentEvent);
7412 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7414 #if defined(Q_WS_WIN)
7415 // reset WS_DISABLED style in a Blocked window
7416 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7417 && QApplicationPrivate::isBlockedByModal(this))
7419 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7420 dwStyle &= ~WS_DISABLED;
7421 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7424 if (QApplicationPrivate::hidden_focus_widget == this)
7425 QApplicationPrivate::hidden_focus_widget = 0;
7429 // hw: The test on getOpaqueRegion() needs to be more intelligent
7430 // currently it doesn't work if the widget is hidden (the region will
7431 // be clipped). The real check should be testing the cached region
7432 // (and dirty flag) directly.
7433 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7434 parentWidget()->d_func()->setDirtyOpaqueRegion();
7436 setAttribute(Qt::WA_WState_Hidden);
7437 setAttribute(Qt::WA_WState_ExplicitShowHide);
7438 if (testAttribute(Qt::WA_WState_Created))
7441 // invalidate layout similar to updateGeometry()
7442 if (!isWindow() && parentWidget()) {
7443 if (parentWidget()->d_func()->layout)
7444 parentWidget()->d_func()->layout->invalidate();
7445 else if (parentWidget()->isVisible())
7446 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7449 QEvent hideToParentEvent(QEvent::HideToParent);
7450 QApplication::sendEvent(this, &hideToParentEvent);
7454 /*!\fn void QWidget::setHidden(bool hidden)
7456 Convenience function, equivalent to setVisible(!\a hidden).
7459 /*!\fn void QWidget::setShown(bool shown)
7461 Use setVisible(\a shown) instead.
7465 void QWidgetPrivate::_q_showIfNotHidden()
7468 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7469 q->setVisible(true);
7472 void QWidgetPrivate::showChildren(bool spontaneous)
7474 QList<QObject*> childList = children;
7475 for (int i = 0; i < childList.size(); ++i) {
7476 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7478 || widget->isWindow()
7479 || widget->testAttribute(Qt::WA_WState_Hidden))
7482 widget->setAttribute(Qt::WA_Mapped);
7483 widget->d_func()->showChildren(true);
7485 QApplication::sendSpontaneousEvent(widget, &e);
7487 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7488 widget->d_func()->show_recursive();
7495 void QWidgetPrivate::hideChildren(bool spontaneous)
7497 QList<QObject*> childList = children;
7498 for (int i = 0; i < childList.size(); ++i) {
7499 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7500 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7502 #ifdef QT_MAC_USE_COCOA
7503 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7504 // When hiding a widget we need to make sure that no mouse_down events are active, because
7505 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7506 // The solution is simple, before going through with this we check if there are any mouse_down events in
7507 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7508 // then we continue.
7509 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7510 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7511 // mouse release event. There are two ways to interpret this:
7512 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7513 // might be waiting for a release event that will never arrive.
7514 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7515 // supposed to trigger because it is not visible.
7516 if(widget == qt_button_down)
7518 #endif // QT_MAC_USE_COCOA
7520 widget->setAttribute(Qt::WA_Mapped, false);
7522 widget->setAttribute(Qt::WA_WState_Visible, false);
7523 widget->d_func()->hideChildren(spontaneous);
7526 QApplication::sendSpontaneousEvent(widget, &e);
7528 QApplication::sendEvent(widget, &e);
7529 if (widget->internalWinId()
7530 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7531 // hide_sys() on an ancestor won't have any affect on this
7532 // widget, so it needs an explicit hide_sys() of its own
7533 widget->d_func()->hide_sys();
7536 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7537 qApp->d_func()->sendSyntheticEnterLeave(widget);
7539 #ifndef QT_NO_ACCESSIBILITY
7541 QAccessible::updateAccessibility(widget, 0, QAccessible::ObjectHide);
7546 bool QWidgetPrivate::close_helper(CloseMode mode)
7548 if (data.is_closing)
7552 data.is_closing = 1;
7554 QPointer<QWidget> that = q;
7555 QPointer<QWidget> parentWidget = q->parentWidget();
7557 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7558 if (mode != CloseNoEvent) {
7560 if (mode == CloseWithSpontaneousEvent)
7561 QApplication::sendSpontaneousEvent(q, &e);
7563 QApplication::sendEvent(q, &e);
7564 if (!that.isNull() && !e.isAccepted()) {
7565 data.is_closing = 0;
7570 if (!that.isNull() && !q->isHidden())
7573 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7574 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7577 /* if there is no non-withdrawn primary window left (except
7578 the ones without QuitOnClose), we emit the lastWindowClosed
7580 QWidgetList list = QApplication::topLevelWidgets();
7581 bool lastWindowClosed = true;
7582 for (int i = 0; i < list.size(); ++i) {
7583 QWidget *w = list.at(i);
7584 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7586 lastWindowClosed = false;
7589 if (lastWindowClosed)
7590 QApplicationPrivate::emitLastWindowClosed();
7593 if (!that.isNull()) {
7594 data.is_closing = 0;
7595 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7596 q->setAttribute(Qt::WA_DeleteOnClose, false);
7605 Closes this widget. Returns true if the widget was closed;
7606 otherwise returns false.
7608 First it sends the widget a QCloseEvent. The widget is \link
7609 hide() hidden\endlink if it \link QCloseEvent::accept()
7610 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7611 ignores\endlink the event, nothing happens. The default
7612 implementation of QWidget::closeEvent() accepts the close event.
7614 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7615 is also deleted. A close events is delivered to the widget no
7616 matter if the widget is visible or not.
7618 The \l QApplication::lastWindowClosed() signal is emitted when the
7619 last visible primary window (i.e. window with no parent) with the
7620 Qt::WA_QuitOnClose attribute set is closed. By default this
7621 attribute is set for all widgets except transient windows such as
7622 splash screens, tool windows, and popup menus.
7626 bool QWidget::close()
7628 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7632 \property QWidget::visible
7633 \brief whether the widget is visible
7635 Calling setVisible(true) or show() sets the widget to visible
7636 status if all its parent widgets up to the window are visible. If
7637 an ancestor is not visible, the widget won't become visible until
7638 all its ancestors are shown. If its size or position has changed,
7639 Qt guarantees that a widget gets move and resize events just
7640 before it is shown. If the widget has not been resized yet, Qt
7641 will adjust the widget's size to a useful default using
7644 Calling setVisible(false) or hide() hides a widget explicitly. An
7645 explicitly hidden widget will never become visible, even if all
7646 its ancestors become visible, unless you show it.
7648 A widget receives show and hide events when its visibility status
7649 changes. Between a hide and a show event, there is no need to
7650 waste CPU cycles preparing or displaying information to the user.
7651 A video application, for example, might simply stop generating new
7654 A widget that happens to be obscured by other windows on the
7655 screen is considered to be visible. The same applies to iconified
7656 windows and windows that exist on another virtual
7657 desktop (on platforms that support this concept). A widget
7658 receives spontaneous show and hide events when its mapping status
7659 is changed by the window system, e.g. a spontaneous hide event
7660 when the user minimizes the window, and a spontaneous show event
7661 when the window is restored again.
7663 You almost never have to reimplement the setVisible() function. If
7664 you need to change some settings before a widget is shown, use
7665 showEvent() instead. If you need to do some delayed initialization
7666 use the Polish event delivered to the event() function.
7668 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7669 showEvent(), hideEvent()
7674 Returns true if this widget would become visible if \a ancestor is
7675 shown; otherwise returns false.
7677 The true case occurs if neither the widget itself nor any parent
7678 up to but excluding \a ancestor has been explicitly hidden.
7680 This function will still return true if the widget is obscured by
7681 other windows on the screen, but could be physically visible if it
7682 or they were to be moved.
7684 isVisibleTo(0) is identical to isVisible().
7686 \sa show() hide() isVisible()
7689 bool QWidget::isVisibleTo(QWidget* ancestor) const
7693 const QWidget * w = this;
7694 while (!w->isHidden()
7696 && w->parentWidget()
7697 && w->parentWidget() != ancestor)
7698 w = w->parentWidget();
7699 return !w->isHidden();
7704 Returns the unobscured region where paint events can occur.
7706 For visible widgets, this is an approximation of the area not
7707 covered by other widgets; otherwise, this is an empty region.
7709 The repaint() function calls this function if necessary, so in
7710 general you do not need to call it.
7713 QRegion QWidget::visibleRegion() const
7717 QRect clipRect = d->clipRect();
7718 if (clipRect.isEmpty())
7720 QRegion r(clipRect);
7721 d->subtractOpaqueChildren(r, clipRect);
7722 d->subtractOpaqueSiblings(r);
7727 QSize QWidgetPrivate::adjustedSize() const
7731 QSize s = q->sizeHint();
7733 if (q->isWindow()) {
7734 Qt::Orientations exp;
7736 if (layout->hasHeightForWidth())
7737 s.setHeight(layout->totalHeightForWidth(s.width()));
7738 exp = layout->expandingDirections();
7741 if (q->sizePolicy().hasHeightForWidth())
7742 s.setHeight(q->heightForWidth(s.width()));
7743 exp = q->sizePolicy().expandingDirections();
7745 if (exp & Qt::Horizontal)
7746 s.setWidth(qMax(s.width(), 200));
7747 if (exp & Qt::Vertical)
7748 s.setHeight(qMax(s.height(), 100));
7749 #if defined(Q_WS_X11)
7750 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7752 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7754 #if defined (Q_WS_WINCE) || defined (Q_OS_SYMBIAN)
7755 s.setWidth(qMin(s.width(), screen.width()));
7756 s.setHeight(qMin(s.height(), screen.height()));
7758 s.setWidth(qMin(s.width(), screen.width()*2/3));
7759 s.setHeight(qMin(s.height(), screen.height()*2/3));
7761 if (QTLWExtra *extra = maybeTopData())
7762 extra->sizeAdjusted = true;
7766 QRect r = q->childrenRect(); // get children rectangle
7769 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7776 Adjusts the size of the widget to fit its contents.
7778 This function uses sizeHint() if it is valid, i.e., the size hint's width
7779 and height are \>= 0. Otherwise, it sets the size to the children
7780 rectangle that covers all child widgets (the union of all child widget
7783 For windows, the screen size is also taken into account. If the sizeHint()
7784 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7785 {expanding}, the window will be at least (200, 100). The maximum size of
7786 a window is 2/3 of the screen's width and height.
7788 \sa sizeHint(), childrenRect()
7791 void QWidget::adjustSize()
7795 QSize s = d->adjustedSize();
7798 d->layout->activate();
7806 \property QWidget::sizeHint
7807 \brief the recommended size for the widget
7809 If the value of this property is an invalid size, no size is
7812 The default implementation of sizeHint() returns an invalid size
7813 if there is no layout for this widget, and returns the layout's
7814 preferred size otherwise.
7816 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7817 setMinimumSize(), updateGeometry()
7820 QSize QWidget::sizeHint() const
7824 return d->layout->totalSizeHint();
7825 return QSize(-1, -1);
7829 \property QWidget::minimumSizeHint
7830 \brief the recommended minimum size for the widget
7832 If the value of this property is an invalid size, no minimum size
7835 The default implementation of minimumSizeHint() returns an invalid
7836 size if there is no layout for this widget, and returns the
7837 layout's minimum size otherwise. Most built-in widgets reimplement
7840 \l QLayout will never resize a widget to a size smaller than the
7841 minimum size hint unless minimumSize() is set or the size policy is
7842 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7843 size hint will be ignored.
7845 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7847 QSize QWidget::minimumSizeHint() const
7851 return d->layout->totalMinimumSize();
7852 return QSize(-1, -1);
7857 \fn QWidget *QWidget::parentWidget() const
7859 Returns the parent of this widget, or 0 if it does not have any
7865 Returns true if this widget is a parent, (or grandparent and so on
7866 to any level), of the given \a child, and both widgets are within
7867 the same window; otherwise returns false.
7870 bool QWidget::isAncestorOf(const QWidget *child) const
7875 if (child->isWindow())
7877 child = child->parentWidget();
7882 #if defined(Q_WS_WIN)
7883 inline void setDisabledStyle(QWidget *w, bool setStyle)
7885 // set/reset WS_DISABLED style.
7886 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7887 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7888 LONG newStyle = dwStyle;
7890 newStyle |= WS_DISABLED;
7892 newStyle &= ~WS_DISABLED;
7893 if (newStyle != dwStyle) {
7894 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7895 // we might need to repaint in some situations (eg. menu)
7902 /*****************************************************************************
7903 QWidget event handling
7904 *****************************************************************************/
7907 This is the main event handler; it handles event \a event. You can
7908 reimplement this function in a subclass, but we recommend using
7909 one of the specialized event handlers instead.
7911 Key press and release events are treated differently from other
7912 events. event() checks for Tab and Shift+Tab and tries to move the
7913 focus appropriately. If there is no widget to move the focus to
7914 (or the key press is not Tab or Shift+Tab), event() calls
7917 Mouse and tablet event handling is also slightly special: only
7918 when the widget is \l enabled, event() will call the specialized
7919 handlers such as mousePressEvent(); otherwise it will discard the
7922 This function returns true if the event was recognized, otherwise
7923 it returns false. If the recognized event was accepted (see \l
7924 QEvent::accepted), any further processing such as event
7925 propagation to the parent widget stops.
7927 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7928 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7929 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7930 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7931 QObject::event(), QObject::timerEvent()
7934 bool QWidget::event(QEvent *event)
7938 // ignore mouse events when disabled
7940 switch(event->type()) {
7941 case QEvent::TabletPress:
7942 case QEvent::TabletRelease:
7943 case QEvent::TabletMove:
7944 case QEvent::MouseButtonPress:
7945 case QEvent::MouseButtonRelease:
7946 case QEvent::MouseButtonDblClick:
7947 case QEvent::MouseMove:
7948 case QEvent::TouchBegin:
7949 case QEvent::TouchUpdate:
7950 case QEvent::TouchEnd:
7951 case QEvent::ContextMenu:
7952 #ifndef QT_NO_WHEELEVENT
7960 switch (event->type()) {
7961 case QEvent::MouseMove:
7962 mouseMoveEvent((QMouseEvent*)event);
7965 case QEvent::MouseButtonPress:
7966 mousePressEvent((QMouseEvent*)event);
7969 case QEvent::MouseButtonRelease:
7970 mouseReleaseEvent((QMouseEvent*)event);
7973 case QEvent::MouseButtonDblClick:
7974 mouseDoubleClickEvent((QMouseEvent*)event);
7976 #ifndef QT_NO_WHEELEVENT
7978 wheelEvent((QWheelEvent*)event);
7981 #ifndef QT_NO_TABLETEVENT
7982 case QEvent::TabletMove:
7983 case QEvent::TabletPress:
7984 case QEvent::TabletRelease:
7985 tabletEvent((QTabletEvent*)event);
7988 case QEvent::KeyPress: {
7989 QKeyEvent *k = (QKeyEvent *)event;
7991 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7992 if (k->key() == Qt::Key_Backtab
7993 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7994 res = focusNextPrevChild(false);
7995 else if (k->key() == Qt::Key_Tab)
7996 res = focusNextPrevChild(true);
8001 #ifdef QT_KEYPAD_NAVIGATION
8002 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
8003 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
8004 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
8005 if (k->key() == Qt::Key_Up)
8006 res = focusNextPrevChild(false);
8007 else if (k->key() == Qt::Key_Down)
8008 res = focusNextPrevChild(true);
8009 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
8010 if (k->key() == Qt::Key_Up)
8011 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
8012 else if (k->key() == Qt::Key_Right)
8013 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
8014 else if (k->key() == Qt::Key_Down)
8015 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
8016 else if (k->key() == Qt::Key_Left)
8017 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
8025 #ifndef QT_NO_WHATSTHIS
8026 if (!k->isAccepted()
8027 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
8028 && d->whatsThis.size()) {
8029 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
8036 case QEvent::KeyRelease:
8037 keyReleaseEvent((QKeyEvent*)event);
8039 case QEvent::ShortcutOverride:
8042 case QEvent::InputMethod:
8043 inputMethodEvent((QInputMethodEvent *) event);
8046 case QEvent::InputMethodQuery:
8047 if (testAttribute(Qt::WA_InputMethodEnabled)) {
8048 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
8049 Qt::InputMethodQueries queries = query->queries();
8050 for (uint i = 0; i < 32; ++i) {
8051 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
8053 QVariant v = inputMethodQuery(q);
8054 query->setValue(q, v);
8061 case QEvent::PolishRequest:
8065 case QEvent::Polish: {
8066 style()->polish(this);
8067 setAttribute(Qt::WA_WState_Polished);
8068 if (!QApplication::font(this).isCopyOf(QApplication::font()))
8070 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
8071 d->resolvePalette();
8075 case QEvent::ApplicationWindowIconChange:
8076 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
8077 d->setWindowIcon_sys();
8078 d->setWindowIcon_helper();
8081 case QEvent::FocusIn:
8082 #ifdef QT_SOFTKEYS_ENABLED
8083 QSoftKeyManager::updateSoftKeys();
8085 focusInEvent((QFocusEvent*)event);
8086 d->updateWidgetTransform();
8089 case QEvent::FocusOut:
8090 focusOutEvent((QFocusEvent*)event);
8094 #ifndef QT_NO_STATUSTIP
8095 if (d->statusTip.size()) {
8096 QStatusTipEvent tip(d->statusTip);
8097 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8104 #ifndef QT_NO_STATUSTIP
8105 if (d->statusTip.size()) {
8107 QStatusTipEvent tip(empty);
8108 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8114 case QEvent::HoverEnter:
8115 case QEvent::HoverLeave:
8120 // At this point the event has to be delivered, regardless
8121 // whether the widget isVisible() or not because it
8122 // already went through the filters
8123 paintEvent((QPaintEvent*)event);
8127 moveEvent((QMoveEvent*)event);
8128 d->updateWidgetTransform();
8131 case QEvent::Resize:
8132 resizeEvent((QResizeEvent*)event);
8133 d->updateWidgetTransform();
8137 closeEvent((QCloseEvent *)event);
8140 #ifndef QT_NO_CONTEXTMENU
8141 case QEvent::ContextMenu:
8142 switch (data->context_menu_policy) {
8143 case Qt::PreventContextMenu:
8145 case Qt::DefaultContextMenu:
8146 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8148 case Qt::CustomContextMenu:
8149 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8152 case Qt::ActionsContextMenu:
8153 if (d->actions.count()) {
8154 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8165 #endif // QT_NO_CONTEXTMENU
8167 #ifndef QT_NO_DRAGANDDROP
8169 dropEvent((QDropEvent*) event);
8172 case QEvent::DragEnter:
8173 dragEnterEvent((QDragEnterEvent*) event);
8176 case QEvent::DragMove:
8177 dragMoveEvent((QDragMoveEvent*) event);
8180 case QEvent::DragLeave:
8181 dragLeaveEvent((QDragLeaveEvent*) event);
8186 showEvent((QShowEvent*) event);
8190 hideEvent((QHideEvent*) event);
8193 case QEvent::ShowWindowRequest:
8198 case QEvent::ApplicationFontChange:
8201 case QEvent::ApplicationPaletteChange:
8202 if (!(windowType() == Qt::Desktop))
8203 d->resolvePalette();
8206 case QEvent::ToolBarChange:
8207 case QEvent::ActivationChange:
8208 case QEvent::EnabledChange:
8209 case QEvent::FontChange:
8210 case QEvent::StyleChange:
8211 case QEvent::PaletteChange:
8212 case QEvent::WindowTitleChange:
8213 case QEvent::IconTextChange:
8214 case QEvent::ModifiedChange:
8215 case QEvent::MouseTrackingChange:
8216 case QEvent::ParentChange:
8217 case QEvent::WindowStateChange:
8218 case QEvent::LocaleChange:
8219 case QEvent::MacSizeChange:
8220 case QEvent::ContentsRectChange:
8224 case QEvent::WindowActivate:
8225 case QEvent::WindowDeactivate: {
8226 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8228 QList<QObject*> childList = d->children;
8229 for (int i = 0; i < childList.size(); ++i) {
8230 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8231 if (w && w->isVisible() && !w->isWindow())
8232 QApplication::sendEvent(w, event);
8235 #ifdef QT_SOFTKEYS_ENABLED
8237 QSoftKeyManager::updateSoftKeys();
8242 case QEvent::LanguageChange:
8245 QList<QObject*> childList = d->children;
8246 for (int i = 0; i < childList.size(); ++i) {
8247 QObject *o = childList.at(i);
8249 QApplication::sendEvent(o, event);
8255 case QEvent::ApplicationLayoutDirectionChange:
8256 d->resolveLayoutDirection();
8259 case QEvent::LayoutDirectionChange:
8261 d->layout->invalidate();
8265 case QEvent::UpdateRequest:
8266 d->syncBackingStore();
8268 case QEvent::UpdateLater:
8269 update(static_cast<QUpdateLaterEvent*>(event)->region());
8272 case QEvent::WindowBlocked:
8273 case QEvent::WindowUnblocked:
8275 QList<QObject*> childList = d->children;
8276 for (int i = 0; i < childList.size(); ++i) {
8277 QObject *o = childList.at(i);
8278 if (o && o != QApplication::activeModalWidget()) {
8279 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8280 // do not forward the event to child windows,
8281 // QApplication does this for us
8284 QApplication::sendEvent(o, event);
8287 #if defined(Q_WS_WIN)
8288 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8292 #ifndef QT_NO_TOOLTIP
8293 case QEvent::ToolTip:
8294 if (!d->toolTip.isEmpty())
8295 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8300 #ifndef QT_NO_WHATSTHIS
8301 case QEvent::WhatsThis:
8302 if (d->whatsThis.size())
8303 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8307 case QEvent::QueryWhatsThis:
8308 if (d->whatsThis.isEmpty())
8312 #ifndef QT_NO_ACCESSIBILITY
8313 case QEvent::AccessibilityDescription:
8314 case QEvent::AccessibilityHelp: {
8315 QAccessibleEvent *ev = static_cast<QAccessibleEvent *>(event);
8318 switch (ev->type()) {
8319 #ifndef QT_NO_TOOLTIP
8320 case QEvent::AccessibilityDescription:
8321 ev->setValue(d->toolTip);
8324 #ifndef QT_NO_WHATSTHIS
8325 case QEvent::AccessibilityHelp:
8326 ev->setValue(d->whatsThis);
8334 case QEvent::EmbeddingControl:
8335 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8336 data->fstrut_dirty = false;
8337 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8338 d->topData()->embedded = 1;
8341 #ifndef QT_NO_ACTION
8342 case QEvent::ActionAdded:
8343 case QEvent::ActionRemoved:
8344 case QEvent::ActionChanged:
8345 #ifdef QT_SOFTKEYS_ENABLED
8346 QSoftKeyManager::updateSoftKeys();
8348 actionEvent((QActionEvent*)event);
8352 case QEvent::KeyboardLayoutChange:
8356 // inform children of the change
8357 QList<QObject*> childList = d->children;
8358 for (int i = 0; i < childList.size(); ++i) {
8359 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8360 if (w && w->isVisible() && !w->isWindow())
8361 QApplication::sendEvent(w, event);
8366 case QEvent::MacGLWindowChange:
8367 d->needWindowChange = false;
8370 case QEvent::TouchBegin:
8371 case QEvent::TouchUpdate:
8372 case QEvent::TouchEnd:
8375 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
8376 const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().first();
8377 if (touchPoint.isPrimary() || touchEvent->deviceType() == QTouchEvent::TouchPad)
8380 // fake a mouse event!
8381 QEvent::Type eventType = QEvent::None;
8382 switch (touchEvent->type()) {
8383 case QEvent::TouchBegin:
8384 eventType = QEvent::MouseButtonPress;
8386 case QEvent::TouchUpdate:
8387 eventType = QEvent::MouseMove;
8389 case QEvent::TouchEnd:
8390 eventType = QEvent::MouseButtonRelease;
8396 if (eventType == QEvent::None)
8399 QMouseEvent mouseEvent(eventType,
8401 touchPoint.scenePos(),
8402 touchPoint.screenPos(),
8405 touchEvent->modifiers());
8406 (void) QApplication::sendEvent(this, &mouseEvent);
8410 #ifndef QT_NO_GESTURES
8411 case QEvent::Gesture:
8415 #ifndef QT_NO_PROPERTIES
8416 case QEvent::DynamicPropertyChange: {
8417 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8418 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8419 uint value = property(propName.constData()).toUInt();
8422 const char axis = propName.at(12);
8424 d->extra->customDpiX = value;
8425 else if (axis == 'Y')
8426 d->extra->customDpiY = value;
8427 d->updateFont(d->data.fnt);
8433 return QObject::event(event);
8439 This event handler can be reimplemented to handle state changes.
8441 The state being changed in this event can be retrieved through the \a event
8444 Change events include: QEvent::ToolBarChange,
8445 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8446 QEvent::StyleChange, QEvent::PaletteChange,
8447 QEvent::WindowTitleChange, QEvent::IconTextChange,
8448 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8449 QEvent::ParentChange, QEvent::WindowStateChange,
8450 QEvent::LanguageChange, QEvent::LocaleChange,
8451 QEvent::LayoutDirectionChange.
8454 void QWidget::changeEvent(QEvent * event)
8456 switch(event->type()) {
8457 case QEvent::EnabledChange:
8459 #ifndef QT_NO_ACCESSIBILITY
8460 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
8464 case QEvent::FontChange:
8465 case QEvent::StyleChange: {
8470 d->layout->invalidate();
8474 case QEvent::PaletteChange:
8479 case QEvent::MacSizeChange:
8482 case QEvent::ToolTipChange:
8483 case QEvent::MouseTrackingChange:
8484 qt_mac_update_mouseTracking(this);
8494 This event handler, for event \a event, can be reimplemented in a
8495 subclass to receive mouse move events for the widget.
8497 If mouse tracking is switched off, mouse move events only occur if
8498 a mouse button is pressed while the mouse is being moved. If mouse
8499 tracking is switched on, mouse move events occur even if no mouse
8502 QMouseEvent::pos() reports the position of the mouse cursor,
8503 relative to this widget. For press and release events, the
8504 position is usually the same as the position of the last mouse
8505 move event, but it might be different if the user's hand shakes.
8506 This is a feature of the underlying window system, not Qt.
8508 If you want to show a tooltip immediately, while the mouse is
8509 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8510 and show them as a tooltip), you must first enable mouse tracking
8511 as described above. Then, to ensure that the tooltip is updated
8512 immediately, you must call QToolTip::showText() instead of
8513 setToolTip() in your implementation of mouseMoveEvent().
8515 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8516 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8519 void QWidget::mouseMoveEvent(QMouseEvent *event)
8525 This event handler, for event \a event, can be reimplemented in a
8526 subclass to receive mouse press events for the widget.
8528 If you create new widgets in the mousePressEvent() the
8529 mouseReleaseEvent() may not end up where you expect, depending on
8530 the underlying window system (or X11 window manager), the widgets'
8531 location and maybe more.
8533 The default implementation implements the closing of popup widgets
8534 when you click outside the window. For other widget types it does
8537 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8538 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8541 void QWidget::mousePressEvent(QMouseEvent *event)
8544 if ((windowType() == Qt::Popup)) {
8547 while ((w = QApplication::activePopupWidget()) && w != this){
8549 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8550 w->hide(); // hide at least
8552 if (!rect().contains(event->pos())){
8559 This event handler, for event \a event, can be reimplemented in a
8560 subclass to receive mouse release events for the widget.
8562 \sa mousePressEvent(), mouseDoubleClickEvent(),
8563 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8566 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8572 This event handler, for event \a event, can be reimplemented in a
8573 subclass to receive mouse double click events for the widget.
8575 The default implementation generates a normal mouse press event.
8577 \note The widget will also receive mouse press and mouse release
8578 events in addition to the double click event. It is up to the
8579 developer to ensure that the application interprets these events
8582 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8583 event(), QMouseEvent
8586 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8588 mousePressEvent(event); // try mouse press event
8591 #ifndef QT_NO_WHEELEVENT
8593 This event handler, for event \a event, can be reimplemented in a
8594 subclass to receive wheel events for the widget.
8596 If you reimplement this handler, it is very important that you
8597 \link QWheelEvent ignore()\endlink the event if you do not handle
8598 it, so that the widget's parent can interpret it.
8600 The default implementation ignores the event.
8602 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8606 void QWidget::wheelEvent(QWheelEvent *event)
8610 #endif // QT_NO_WHEELEVENT
8612 #ifndef QT_NO_TABLETEVENT
8614 This event handler, for event \a event, can be reimplemented in a
8615 subclass to receive tablet events for the widget.
8617 If you reimplement this handler, it is very important that you
8618 \link QTabletEvent ignore()\endlink the event if you do not handle
8619 it, so that the widget's parent can interpret it.
8621 The default implementation ignores the event.
8623 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8627 void QWidget::tabletEvent(QTabletEvent *event)
8631 #endif // QT_NO_TABLETEVENT
8634 This event handler, for event \a event, can be reimplemented in a
8635 subclass to receive key press events for the widget.
8637 A widget must call setFocusPolicy() to accept focus initially and
8638 have focus in order to receive a key press event.
8640 If you reimplement this handler, it is very important that you
8641 call the base class implementation if you do not act upon the key.
8643 The default implementation closes popup widgets if the user
8644 presses Esc. Otherwise the event is ignored, so that the widget's
8645 parent can interpret it.
8647 Note that QKeyEvent starts with isAccepted() == true, so you do not
8648 need to call QKeyEvent::accept() - just do not call the base class
8649 implementation if you act upon the key.
8651 \sa keyReleaseEvent(), setFocusPolicy(),
8652 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8655 void QWidget::keyPressEvent(QKeyEvent *event)
8657 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8666 This event handler, for event \a event, can be reimplemented in a
8667 subclass to receive key release events for the widget.
8669 A widget must \link setFocusPolicy() accept focus\endlink
8670 initially and \link hasFocus() have focus\endlink in order to
8671 receive a key release event.
8673 If you reimplement this handler, it is very important that you
8674 call the base class implementation if you do not act upon the key.
8676 The default implementation ignores the event, so that the widget's
8677 parent can interpret it.
8679 Note that QKeyEvent starts with isAccepted() == true, so you do not
8680 need to call QKeyEvent::accept() - just do not call the base class
8681 implementation if you act upon the key.
8683 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8684 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8687 void QWidget::keyReleaseEvent(QKeyEvent *event)
8693 \fn void QWidget::focusInEvent(QFocusEvent *event)
8695 This event handler can be reimplemented in a subclass to receive
8696 keyboard focus events (focus received) for the widget. The event
8697 is passed in the \a event parameter
8699 A widget normally must setFocusPolicy() to something other than
8700 Qt::NoFocus in order to receive focus events. (Note that the
8701 application programmer can call setFocus() on any widget, even
8702 those that do not normally accept focus.)
8704 The default implementation updates the widget (except for windows
8705 that do not specify a focusPolicy()).
8707 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8708 keyReleaseEvent(), event(), QFocusEvent
8711 void QWidget::focusInEvent(QFocusEvent *)
8713 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8719 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8721 This event handler can be reimplemented in a subclass to receive
8722 keyboard focus events (focus lost) for the widget. The events is
8723 passed in the \a event parameter.
8725 A widget normally must setFocusPolicy() to something other than
8726 Qt::NoFocus in order to receive focus events. (Note that the
8727 application programmer can call setFocus() on any widget, even
8728 those that do not normally accept focus.)
8730 The default implementation updates the widget (except for windows
8731 that do not specify a focusPolicy()).
8733 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8734 keyReleaseEvent(), event(), QFocusEvent
8737 void QWidget::focusOutEvent(QFocusEvent *)
8739 if (focusPolicy() != Qt::NoFocus || !isWindow())
8744 \fn void QWidget::enterEvent(QEvent *event)
8746 This event handler can be reimplemented in a subclass to receive
8747 widget enter events which are passed in the \a event parameter.
8749 An event is sent to the widget when the mouse cursor enters the
8752 \sa leaveEvent(), mouseMoveEvent(), event()
8755 void QWidget::enterEvent(QEvent *)
8760 \fn void QWidget::leaveEvent(QEvent *event)
8762 This event handler can be reimplemented in a subclass to receive
8763 widget leave events which are passed in the \a event parameter.
8765 A leave event is sent to the widget when the mouse cursor leaves
8768 \sa enterEvent(), mouseMoveEvent(), event()
8771 void QWidget::leaveEvent(QEvent *)
8776 \fn void QWidget::paintEvent(QPaintEvent *event)
8778 This event handler can be reimplemented in a subclass to receive paint
8779 events passed in \a event.
8781 A paint event is a request to repaint all or part of a widget. It can
8782 happen for one of the following reasons:
8785 \o repaint() or update() was invoked,
8786 \o the widget was obscured and has now been uncovered, or
8787 \o many other reasons.
8790 Many widgets can simply repaint their entire surface when asked to, but
8791 some slow widgets need to optimize by painting only the requested region:
8792 QPaintEvent::region(). This speed optimization does not change the result,
8793 as painting is clipped to that region during event processing. QListView
8794 and QTableView do this, for example.
8796 Qt also tries to speed up painting by merging multiple paint events into
8797 one. When update() is called several times or the window system sends
8798 several paint events, Qt merges these events into one event with a larger
8799 region (see QRegion::united()). The repaint() function does not permit this
8800 optimization, so we suggest using update() whenever possible.
8802 When the paint event occurs, the update region has normally been erased, so
8803 you are painting on the widget's background.
8805 The background can be set using setBackgroundRole() and setPalette().
8807 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8808 is no need to write double-buffering code in paintEvent() to avoid flicker.
8810 \bold{Note for the X11 platform}: It is possible to toggle global double
8811 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8813 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8815 \note Generally, you should refrain from calling update() or repaint()
8816 \bold{inside} a paintEvent(). For example, calling update() or repaint() on
8817 children inside a paintevent() results in undefined behavior; the child may
8818 or may not get a paint event.
8820 \warning If you are using a custom paint engine without Qt's backingstore,
8821 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8822 never be called; the backingstore will be used instead.
8824 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8825 {Analog Clock Example}
8828 void QWidget::paintEvent(QPaintEvent *)
8834 \fn void QWidget::moveEvent(QMoveEvent *event)
8836 This event handler can be reimplemented in a subclass to receive
8837 widget move events which are passed in the \a event parameter.
8838 When the widget receives this event, it is already at the new
8841 The old position is accessible through QMoveEvent::oldPos().
8843 \sa resizeEvent(), event(), move(), QMoveEvent
8846 void QWidget::moveEvent(QMoveEvent *)
8852 This event handler can be reimplemented in a subclass to receive
8853 widget resize events which are passed in the \a event parameter.
8854 When resizeEvent() is called, the widget already has its new
8855 geometry. The old size is accessible through
8856 QResizeEvent::oldSize().
8858 The widget will be erased and receive a paint event immediately
8859 after processing the resize event. No drawing need be (or should
8860 be) done inside this handler.
8863 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8867 void QWidget::resizeEvent(QResizeEvent * /* event */)
8871 #ifndef QT_NO_ACTION
8873 \fn void QWidget::actionEvent(QActionEvent *event)
8875 This event handler is called with the given \a event whenever the
8876 widget's actions are changed.
8878 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8880 void QWidget::actionEvent(QActionEvent *)
8887 This event handler is called with the given \a event when Qt receives a window
8888 close request for a top-level widget from the window system.
8890 By default, the event is accepted and the widget is closed. You can reimplement
8891 this function to change the way the widget responds to window close requests.
8892 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8895 Main window applications typically use reimplementations of this function to check
8896 whether the user's work has been saved and ask for permission before closing.
8897 For example, the \l{Application Example} uses a helper function to determine whether
8898 or not to close the window:
8900 \snippet mainwindows/application/mainwindow.cpp 3
8901 \snippet mainwindows/application/mainwindow.cpp 4
8903 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8906 void QWidget::closeEvent(QCloseEvent *event)
8911 #ifndef QT_NO_CONTEXTMENU
8913 This event handler, for event \a event, can be reimplemented in a
8914 subclass to receive widget context menu events.
8916 The handler is called when the widget's \l contextMenuPolicy is
8917 Qt::DefaultContextMenu.
8919 The default implementation ignores the context event.
8920 See the \l QContextMenuEvent documentation for more details.
8922 \sa event(), QContextMenuEvent customContextMenuRequested()
8925 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8929 #endif // QT_NO_CONTEXTMENU
8933 This event handler, for event \a event, can be reimplemented in a
8934 subclass to receive Input Method composition events. This handler
8935 is called when the state of the input method changes.
8937 Note that when creating custom text editing widgets, the
8938 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8939 (using the setAttribute() function) in order to receive input
8942 The default implementation calls event->ignore(), which rejects the
8943 Input Method event. See the \l QInputMethodEvent documentation for more
8946 \sa event(), QInputMethodEvent
8948 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8954 This method is only relevant for input widgets. It is used by the
8955 input method to query a set of properties of the widget to be
8956 able to support complex input method operations as support for
8957 surrounding text and reconversions.
8959 \a query specifies which property is queried.
8961 \sa inputMethodEvent(), QInputMethodEvent, QInputContext, inputMethodHints
8963 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8966 case Qt::ImCursorRectangle:
8967 return QRect(width()/2, 0, 1, height());
8970 case Qt::ImAnchorPosition:
8972 return inputMethodQuery(Qt::ImCursorPosition);
8974 return (int)inputMethodHints();
8981 \property QWidget::inputMethodHints
8982 \brief What input method specific hints the widget has.
8984 This is only relevant for input widgets. It is used by
8985 the input method to retrieve hints as to how the input method
8986 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8987 is set, the input method may change its visual components to reflect
8988 that only numbers can be entered.
8990 \note The flags are only hints, so the particular input method
8991 implementation is free to ignore them. If you want to be
8992 sure that a certain type of characters are entered,
8993 you should also set a QValidator on the widget.
8995 The default value is Qt::ImhNone.
8999 \sa inputMethodQuery(), QInputContext
9001 Qt::InputMethodHints QWidget::inputMethodHints() const
9004 const QWidgetPrivate *priv = d_func();
9005 while (priv->inheritsInputMethodHints) {
9006 priv = priv->q_func()->parentWidget()->d_func();
9009 return priv->imHints;
9015 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
9020 qApp->inputPanel()->update(Qt::ImHints);
9025 #ifndef QT_NO_DRAGANDDROP
9028 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
9030 This event handler is called when a drag is in progress and the
9031 mouse enters this widget. The event is passed in the \a event parameter.
9033 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
9036 See the \link dnd.html Drag-and-drop documentation\endlink for an
9037 overview of how to provide drag-and-drop in your application.
9039 \sa QDrag, QDragEnterEvent
9041 void QWidget::dragEnterEvent(QDragEnterEvent *)
9046 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
9048 This event handler is called if a drag is in progress, and when
9049 any of the following conditions occur: the cursor enters this widget,
9050 the cursor moves within this widget, or a modifier key is pressed on
9051 the keyboard while this widget has the focus. The event is passed
9052 in the \a event parameter.
9054 See the \link dnd.html Drag-and-drop documentation\endlink for an
9055 overview of how to provide drag-and-drop in your application.
9057 \sa QDrag, QDragMoveEvent
9059 void QWidget::dragMoveEvent(QDragMoveEvent *)
9064 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
9066 This event handler is called when a drag is in progress and the
9067 mouse leaves this widget. The event is passed in the \a event
9070 See the \link dnd.html Drag-and-drop documentation\endlink for an
9071 overview of how to provide drag-and-drop in your application.
9073 \sa QDrag, QDragLeaveEvent
9075 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
9080 \fn void QWidget::dropEvent(QDropEvent *event)
9082 This event handler is called when the drag is dropped on this
9083 widget. The event is passed in the \a event parameter.
9085 See the \link dnd.html Drag-and-drop documentation\endlink for an
9086 overview of how to provide drag-and-drop in your application.
9088 \sa QDrag, QDropEvent
9090 void QWidget::dropEvent(QDropEvent *)
9094 #endif // QT_NO_DRAGANDDROP
9097 \fn void QWidget::showEvent(QShowEvent *event)
9099 This event handler can be reimplemented in a subclass to receive
9100 widget show events which are passed in the \a event parameter.
9102 Non-spontaneous show events are sent to widgets immediately
9103 before they are shown. The spontaneous show events of windows are
9104 delivered afterwards.
9106 Note: A widget receives spontaneous show and hide events when its
9107 mapping status is changed by the window system, e.g. a spontaneous
9108 hide event when the user minimizes the window, and a spontaneous
9109 show event when the window is restored again. After receiving a
9110 spontaneous hide event, a widget is still considered visible in
9111 the sense of isVisible().
9113 \sa visible, event(), QShowEvent
9115 void QWidget::showEvent(QShowEvent *)
9120 \fn void QWidget::hideEvent(QHideEvent *event)
9122 This event handler can be reimplemented in a subclass to receive
9123 widget hide events. The event is passed in the \a event parameter.
9125 Hide events are sent to widgets immediately after they have been
9128 Note: A widget receives spontaneous show and hide events when its
9129 mapping status is changed by the window system, e.g. a spontaneous
9130 hide event when the user minimizes the window, and a spontaneous
9131 show event when the window is restored again. After receiving a
9132 spontaneous hide event, a widget is still considered visible in
9133 the sense of isVisible().
9135 \sa visible, event(), QHideEvent
9137 void QWidget::hideEvent(QHideEvent *)
9142 \fn QWidget::x11Event(MSG *)
9144 This special event handler can be reimplemented in a subclass to receive
9147 In your reimplementation of this function, if you want to stop Qt from
9148 handling the event, return true. If you return false, this native event
9149 is passed back to Qt, which translates it into a Qt event and sends it to
9152 \note Events are only delivered to this event handler if the widget is
9155 \warning This function is not portable.
9157 \sa QApplication::x11EventFilter(), QWidget::winId()
9161 #if defined(Q_WS_MAC)
9164 \fn bool QWidget::macEvent(EventHandlerCallRef caller, EventRef event)
9166 This special event handler can be reimplemented in a subclass to
9167 receive native Macintosh events.
9169 The parameters are a bit different depending if Qt is build against Carbon
9170 or Cocoa. In Carbon, \a caller and \a event are the corresponding
9171 EventHandlerCallRef and EventRef that correspond to the Carbon event
9172 handlers that are installed. In Cocoa, \a caller is always 0 and the
9173 EventRef is the EventRef generated from the NSEvent.
9175 In your reimplementation of this function, if you want to stop the
9176 event being handled by Qt, return true. If you return false, this
9177 native event is passed back to Qt, which translates the event into
9178 a Qt event and sends it to the widget.
9180 \warning This function is not portable.
9182 \warning This function was not called inside of Qt until Qt 4.4.
9183 If you need compatibility with earlier versions of Qt, consider QApplication::macEventFilter() instead.
9185 \sa QApplication::macEventFilter()
9188 bool QWidget::macEvent(EventHandlerCallRef, EventRef)
9194 #if defined(Q_WS_WIN)
9197 This special event handler can be reimplemented in a subclass to
9198 receive native Windows events which are passed in the \a message
9201 In your reimplementation of this function, if you want to stop the
9202 event being handled by Qt, return true and set \a result to the value
9203 that the window procedure should return. If you return false, this
9204 native event is passed back to Qt, which translates the event into
9205 a Qt event and sends it to the widget.
9207 \warning This function is not portable.
9209 \sa QApplication::winEventFilter()
9211 bool QWidget::winEvent(MSG *message, long *result)
9219 #if defined(Q_WS_X11)
9222 \fn bool QWidget::x11Event(XEvent *event)
9224 This special event handler can be reimplemented in a subclass to receive
9225 native X11 events passed in the \a event parameter.
9227 In your reimplementation of this function, if you want to stop Qt from
9228 handling the event, return true. If you return false, this native event
9229 is passed back to Qt, which translates it into a Qt event and sends it to
9232 \note Events are only delivered to this event handler if the widget is
9235 \warning This function is not portable.
9237 \sa QApplication::x11EventFilter(), QWidget::winId()
9239 bool QWidget::x11Event(XEvent *)
9247 Ensures that the widget has been polished by QStyle (i.e., has a
9248 proper font and palette).
9250 QWidget calls this function after it has been fully constructed
9251 but before it is shown the very first time. You can call this
9252 function if you want to ensure that the widget is polished before
9253 doing an operation, e.g., the correct font size might be needed in
9254 the widget's sizeHint() reimplementation. Note that this function
9255 \e is called from the default implementation of sizeHint().
9257 Polishing is useful for final initialization that must happen after
9258 all constructors (from base classes as well as from subclasses)
9261 If you need to change some settings when a widget is polished,
9262 reimplement event() and handle the QEvent::Polish event type.
9264 \bold{Note:} The function is declared const so that it can be called from
9265 other const functions (e.g., sizeHint()).
9269 void QWidget::ensurePolished() const
9273 const QMetaObject *m = metaObject();
9274 if (m == d->polished)
9278 QEvent e(QEvent::Polish);
9279 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9281 // polish children after 'this'
9282 QList<QObject*> children = d->children;
9283 for (int i = 0; i < children.size(); ++i) {
9284 QObject *o = children.at(i);
9285 if(!o->isWidgetType())
9287 if (QWidget *w = qobject_cast<QWidget *>(o))
9288 w->ensurePolished();
9291 if (d->parent && d->sendChildEvents) {
9292 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9293 QCoreApplication::sendEvent(d->parent, &e);
9296 if (d->extra && d->extra->topextra && d->extra->topextra->window
9297 && d->extra->topextra->window->objectName().isEmpty()) {
9298 QString on = objectName();
9300 on = QString::fromUtf8(metaObject()->className());
9301 on += QLatin1String("Class");
9303 on += QLatin1String("Window");
9304 d->extra->topextra->window->setObjectName(on);
9310 Returns the mask currently set on a widget. If no mask is set the
9311 return value will be an empty region.
9313 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9315 QRegion QWidget::mask() const
9318 return d->extra ? d->extra->mask : QRegion();
9322 Returns the layout manager that is installed on this widget, or 0
9323 if no layout manager is installed.
9325 The layout manager sets the geometry of the widget's children
9326 that have been added to the layout.
9328 \sa setLayout(), sizePolicy(), {Layout Management}
9330 QLayout *QWidget::layout() const
9332 return d_func()->layout;
9337 \fn void QWidget::setLayout(QLayout *layout)
9339 Sets the layout manager for this widget to \a layout.
9341 If there already is a layout manager installed on this widget,
9342 QWidget won't let you install another. You must first delete the
9343 existing layout manager (returned by layout()) before you can
9344 call setLayout() with the new layout.
9346 If \a layout is the layout manger on a different widget, setLayout()
9347 will reparent the layout and make it the layout manager for this widget.
9351 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9353 An alternative to calling this function is to pass this widget to
9354 the layout's constructor.
9356 The QWidget will take ownership of \a layout.
9358 \sa layout(), {Layout Management}
9361 void QWidget::setLayout(QLayout *l)
9364 qWarning("QWidget::setLayout: Cannot set layout to 0");
9369 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9370 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9371 objectName().toLocal8Bit().data());
9375 QObject *oldParent = l->parent();
9376 if (oldParent && oldParent != this) {
9377 if (oldParent->isWidgetType()) {
9378 // Steal the layout off a widget parent. Takes effect when
9379 // morphing laid-out container widgets in Designer.
9380 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9381 oldParentWidget->takeLayout();
9383 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9384 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9385 objectName().toLocal8Bit().data());
9391 l->d_func()->topLevel = true;
9393 if (oldParent != this) {
9395 l->d_func()->reparentChildWidgets(this);
9399 if (isWindow() && d->maybeTopData())
9400 d->topData()->sizeAdjusted = false;
9404 \fn QLayout *QWidget::takeLayout()
9406 Remove the layout from the widget.
9410 QLayout *QWidget::takeLayout()
9413 QLayout *l = layout();
9422 \property QWidget::sizePolicy
9423 \brief the default layout behavior of the widget
9425 If there is a QLayout that manages this widget's children, the
9426 size policy specified by that layout is used. If there is no such
9427 QLayout, the result of this function is used.
9429 The default policy is Preferred/Preferred, which means that the
9430 widget can be freely resized, but prefers to be the size
9431 sizeHint() returns. Button-like widgets set the size policy to
9432 specify that they may stretch horizontally, but are fixed
9433 vertically. The same applies to lineedit controls (such as
9434 QLineEdit, QSpinBox or an editable QComboBox) and other
9435 horizontally orientated widgets (such as QProgressBar).
9436 QToolButton's are normally square, so they allow growth in both
9437 directions. Widgets that support different directions (such as
9438 QSlider, QScrollBar or QHeader) specify stretching in the
9439 respective direction only. Widgets that can provide scroll bars
9440 (usually subclasses of QScrollArea) tend to specify that they can
9441 use additional space, and that they can make do with less than
9444 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9446 QSizePolicy QWidget::sizePolicy() const
9449 return d->size_policy;
9452 void QWidget::setSizePolicy(QSizePolicy policy)
9455 setAttribute(Qt::WA_WState_OwnSizePolicy);
9456 if (policy == d->size_policy)
9458 d->size_policy = policy;
9460 #ifndef QT_NO_GRAPHICSVIEW
9461 if (QWExtra *extra = d->extra) {
9462 if (extra->proxyWidget)
9463 extra->proxyWidget->setSizePolicy(policy);
9469 if (isWindow() && d->maybeTopData())
9470 d->topData()->sizeAdjusted = false;
9474 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9477 Sets the size policy of the widget to \a horizontal and \a
9478 vertical, with standard stretch and no height-for-width.
9480 \sa QSizePolicy::QSizePolicy()
9484 Returns the preferred height for this widget, given the width \a w.
9486 If this widget has a layout, the default implementation returns
9487 the layout's preferred height. if there is no layout, the default
9488 implementation returns -1 indicating that the preferred height
9489 does not depend on the width.
9492 int QWidget::heightForWidth(int w) const
9494 if (layout() && layout()->hasHeightForWidth())
9495 return layout()->totalHeightForWidth(w);
9505 This is a bit hackish, but ideally we would have created a virtual function
9506 in the public API (however, too late...) so that subclasses could reimplement
9508 Instead we add a virtual function to QWidgetPrivate.
9509 ### Qt5: move to public class and make virtual
9511 bool QWidgetPrivate::hasHeightForWidth() const
9513 return layout ? layout->hasHeightForWidth() : size_policy.hasHeightForWidth();
9517 \fn QWidget *QWidget::childAt(int x, int y) const
9519 Returns the visible child widget at the position (\a{x}, \a{y})
9520 in the widget's coordinate system. If there is no visible child
9521 widget at the specified position, the function returns 0.
9527 Returns the visible child widget at point \a p in the widget's own
9531 QWidget *QWidget::childAt(const QPoint &p) const
9533 return d_func()->childAt_helper(p, false);
9536 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9538 if (children.isEmpty())
9543 // Unified tool bars on the Mac require special handling since they live outside
9544 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9545 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9546 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9548 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9551 if (!pointInsideRectAndMask(p))
9553 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9556 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9559 Q_UNUSED(includeFrame);
9561 for (int i = children.size() - 1; i >= 0; --i) {
9562 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9563 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9564 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9568 // Map the point 'p' from parent coordinates to child coordinates.
9569 QPoint childPoint = p;
9571 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9572 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9573 // QWidget::mapFromParent won't do the trick.
9574 if (includeFrame && qobject_cast<QToolBar *>(child))
9575 childPoint = qt_mac_nativeMapFromParent(child, p);
9578 childPoint -= child->data->crect.topLeft();
9580 // Check if the point hits the child.
9581 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9584 // Do the same for the child's descendants.
9585 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9588 // We have found our target; namely the child at position 'p'.
9594 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9598 widgetItem->invalidateSizeCache();
9600 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9601 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9602 if (parent->d_func()->layout)
9603 parent->d_func()->layout->invalidate();
9604 else if (parent->isVisible())
9605 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9611 Notifies the layout system that this widget has changed and may
9612 need to change geometry.
9614 Call this function if the sizeHint() or sizePolicy() have changed.
9616 For explicitly hidden widgets, updateGeometry() is a no-op. The
9617 layout system will be notified as soon as the widget is shown.
9620 void QWidget::updateGeometry()
9623 d->updateGeometry_helper(false);
9626 /*! \property QWidget::windowFlags
9628 Window flags are a combination of a type (e.g. Qt::Dialog) and
9629 zero or more hints to the window system (e.g.
9630 Qt::FramelessWindowHint).
9632 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9633 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9634 0) on the desktop. If the widget is a window and becomes a
9635 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9636 relative to its parent widget.
9638 \note This function calls setParent() when changing the flags for
9639 a window, causing the widget to be hidden. You must call show() to make
9640 the widget visible again..
9642 \sa windowType(), {Window Flags Example}
9644 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9646 if (data->window_flags == flags)
9651 if ((data->window_flags | flags) & Qt::Window) {
9652 // the old type was a window and/or the new type is a window
9653 QPoint oldPos = pos();
9654 bool visible = isVisible();
9655 setParent(parentWidget(), flags);
9657 // if both types are windows or neither of them are, we restore
9659 if (!((data->window_flags ^ flags) & Qt::Window)
9660 && (visible || testAttribute(Qt::WA_Moved))) {
9663 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9664 d->adjustQuitOnCloseAttribute();
9666 data->window_flags = flags;
9671 Sets the window flags for the widget to \a flags,
9672 \e without telling the window system.
9674 \warning Do not call this function unless you really know what
9677 \sa setWindowFlags()
9679 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9681 data->window_flags = flags;
9685 \fn Qt::WindowType QWidget::windowType() const
9687 Returns the window type of this widget. This is identical to
9688 windowFlags() & Qt::WindowType_Mask.
9694 Sets the parent of the widget to \a parent, and resets the window
9695 flags. The widget is moved to position (0, 0) in its new parent.
9697 If the new parent widget is in a different window, the
9698 reparented widget and its children are appended to the end of the
9699 \l{setFocusPolicy()}{tab chain} of the new parent
9700 widget, in the same internal order as before. If one of the moved
9701 widgets had keyboard focus, setParent() calls clearFocus() for that
9704 If the new parent widget is in the same window as the
9705 old parent, setting the parent doesn't change the tab order or
9708 If the "new" parent widget is the old parent widget, this function
9711 \note The widget becomes invisible as part of changing its parent,
9712 even if it was previously visible. You must call show() to make the
9713 widget visible again.
9715 \warning It is very unlikely that you will ever need this
9716 function. If you have a widget that changes its content
9717 dynamically, it is far easier to use \l QStackedWidget.
9719 \sa setWindowFlags()
9721 void QWidget::setParent(QWidget *parent)
9723 if (parent == parentWidget())
9725 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9731 This function also takes widget flags, \a f as an argument.
9734 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9737 d->inSetParent = true;
9738 bool resized = testAttribute(Qt::WA_Resized);
9739 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9740 QWidget *oldtlw = window();
9742 QWidget *desktopWidget = 0;
9743 if (parent && parent->windowType() == Qt::Desktop)
9744 desktopWidget = parent;
9745 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9747 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
9748 if (newParent && parent && !desktopWidget) {
9749 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9750 #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
9751 // On Mac, toolbars inside the unified title bar will never overlap with
9752 // siblings in the content view. So we skip enforce native siblings in that case
9753 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9754 #endif // Q_WS_MAC && QT_MAC_USE_COCOA
9756 parent->d_func()->enforceNativeChildren();
9757 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9758 setAttribute(Qt::WA_NativeWindow);
9763 if (!testAttribute(Qt::WA_WState_Hidden)) {
9765 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9768 QEvent e(QEvent::ParentAboutToChange);
9769 QApplication::sendEvent(this, &e);
9772 if (newParent && isAncestorOf(focusWidget()))
9773 focusWidget()->clearFocus();
9775 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9776 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9778 d->setParent_sys(parent, f);
9780 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9781 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9782 if (oldBsTracker && oldBsTracker != bsTracker)
9783 oldBsTracker->unregisterWidgetSubtree(this);
9788 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9790 oldBs->removeDirtyWidget(this);
9791 // Move the widget and all its static children from
9792 // the old backing store to the new one.
9793 oldBs->moveStaticWidgets(this);
9796 if ((QApplicationPrivate::app_compile_version < 0x040200
9797 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
9798 && !testAttribute(Qt::WA_WState_Created))
9801 d->reparentFocusWidgets(oldtlw);
9802 setAttribute(Qt::WA_Resized, resized);
9803 if (!testAttribute(Qt::WA_StyleSheet)
9804 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9806 d->resolvePalette();
9808 d->resolveLayoutDirection();
9811 // Note: GL widgets under WGL or EGL will always need a ParentChange
9812 // event to handle recreation/rebinding of the GL context, hence the
9813 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9816 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9817 || (f & Qt::MSWindowsOwnDC)
9820 // propagate enabled updates enabled state to non-windows
9822 if (!testAttribute(Qt::WA_ForceDisabled))
9823 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9824 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9825 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9829 // send and post remaining QObject events
9830 if (parent && d->sendChildEvents) {
9831 QChildEvent e(QEvent::ChildAdded, this);
9832 QApplication::sendEvent(parent, &e);
9835 //### already hidden above ---> must probably do something smart on the mac
9837 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9838 // if(!qt_mac_is_macdrawer(q)) //special case
9839 // q->setAttribute(Qt::WA_WState_Hidden);
9841 // q->setAttribute(Qt::WA_WState_Hidden);
9844 if (parent && d->sendChildEvents && d->polished) {
9845 QChildEvent e(QEvent::ChildPolished, this);
9846 QCoreApplication::sendEvent(parent, &e);
9849 QEvent e(QEvent::ParentChange);
9850 QApplication::sendEvent(this, &e);
9854 if (isWindow() || parentWidget()->isVisible())
9855 setAttribute(Qt::WA_WState_Hidden, true);
9856 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9857 setAttribute(Qt::WA_WState_Hidden, false);
9860 d->updateIsOpaque();
9862 #ifndef QT_NO_GRAPHICSVIEW
9863 // Embed the widget into a proxy if the parent is embedded.
9864 // ### Doesn't handle reparenting out of an embedded widget.
9865 if (oldtlw->graphicsProxyWidget()) {
9866 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9867 ancestorProxy->d_func()->unembedSubWindow(this);
9869 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9870 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9871 ancestorProxy->d_func()->embedSubWindow(this);
9875 d->inSetParent = false;
9879 Scrolls the widget including its children \a dx pixels to the
9880 right and \a dy downward. Both \a dx and \a dy may be negative.
9882 After scrolling, the widgets will receive paint events for
9883 the areas that need to be repainted. For widgets that Qt knows to
9884 be opaque, this is only the newly exposed parts.
9885 For example, if an opaque widget is scrolled 8 pixels to the left,
9886 only an 8-pixel wide stripe at the right edge needs updating.
9888 Since widgets propagate the contents of their parents by default,
9889 you need to set the \l autoFillBackground property, or use
9890 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9893 For widgets that use contents propagation, a scroll will cause an
9894 update of the entire scroll area.
9896 \sa {Transparency and Double Buffering}
9899 void QWidget::scroll(int dx, int dy)
9901 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9903 if (dx == 0 && dy == 0)
9906 #ifndef QT_NO_GRAPHICSVIEW
9907 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9908 // Graphics View maintains its own dirty region as a list of rects;
9909 // until we can connect item updates directly to the view, we must
9910 // separately add a translated dirty region.
9911 if (!d->dirty.isEmpty()) {
9912 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9913 proxy->update(rect);
9915 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9919 d->setDirtyOpaqueRegion();
9920 d->scroll_sys(dx, dy);
9926 This version only scrolls \a r and does not move the children of
9929 If \a r is empty or invalid, the result is undefined.
9933 void QWidget::scroll(int dx, int dy, const QRect &r)
9936 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9938 if (dx == 0 && dy == 0)
9941 #ifndef QT_NO_GRAPHICSVIEW
9942 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9943 // Graphics View maintains its own dirty region as a list of rects;
9944 // until we can connect item updates directly to the view, we must
9945 // separately add a translated dirty region.
9946 if (!d->dirty.isEmpty()) {
9947 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9948 proxy->update(rect);
9950 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9954 d->scroll_sys(dx, dy, r);
9958 Repaints the widget directly by calling paintEvent() immediately,
9959 unless updates are disabled or the widget is hidden.
9961 We suggest only using repaint() if you need an immediate repaint,
9962 for example during animation. In almost all circumstances update()
9963 is better, as it permits Qt to optimize for speed and minimize
9966 \warning If you call repaint() in a function which may itself be
9967 called from paintEvent(), you may get infinite recursion. The
9968 update() function never causes recursion.
9970 \sa update(), paintEvent(), setUpdatesEnabled()
9973 void QWidget::repaint()
9980 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9983 If \a w is negative, it is replaced with \c{width() - x}, and if
9984 \a h is negative, it is replaced width \c{height() - y}.
9986 void QWidget::repaint(int x, int y, int w, int h)
9988 if (x > data->crect.width() || y > data->crect.height())
9992 w = data->crect.width() - x;
9994 h = data->crect.height() - y;
9996 repaint(QRect(x, y, w, h));
10001 This version repaints a rectangle \a rect inside the widget.
10003 void QWidget::repaint(const QRect &rect)
10007 if (testAttribute(Qt::WA_WState_ConfigPending)) {
10012 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
10015 if (hasBackingStoreSupport()) {
10016 #ifdef QT_MAC_USE_COCOA
10017 if (qt_widget_private(this)->isInUnifiedToolbar) {
10018 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10021 #endif // QT_MAC_USE_COCOA
10022 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10023 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
10024 tlwExtra->inRepaint = true;
10025 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
10026 tlwExtra->inRepaint = false;
10029 d->repaint_sys(rect);
10036 This version repaints a region \a rgn inside the widget.
10038 void QWidget::repaint(const QRegion &rgn)
10042 if (testAttribute(Qt::WA_WState_ConfigPending)) {
10047 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
10050 if (hasBackingStoreSupport()) {
10051 #ifdef QT_MAC_USE_COCOA
10052 if (qt_widget_private(this)->isInUnifiedToolbar) {
10053 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10056 #endif // QT_MAC_USE_COCOA
10057 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10058 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
10059 tlwExtra->inRepaint = true;
10060 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
10061 tlwExtra->inRepaint = false;
10064 d->repaint_sys(rgn);
10069 Updates the widget unless updates are disabled or the widget is
10072 This function does not cause an immediate repaint; instead it
10073 schedules a paint event for processing when Qt returns to the main
10074 event loop. This permits Qt to optimize for more speed and less
10075 flicker than a call to repaint() does.
10077 Calling update() several times normally results in just one
10080 Qt normally erases the widget's area before the paintEvent() call.
10081 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
10082 responsible for painting all its pixels with an opaque color.
10084 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
10086 void QWidget::update()
10091 /*! \fn void QWidget::update(int x, int y, int w, int h)
10094 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
10101 This version updates a rectangle \a rect inside the widget.
10103 void QWidget::update(const QRect &rect)
10105 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
10108 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
10109 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
10113 if (hasBackingStoreSupport()) {
10114 #ifdef QT_MAC_USE_COCOA
10115 if (qt_widget_private(this)->isInUnifiedToolbar) {
10116 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10119 #endif // QT_MAC_USE_COCOA
10120 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10121 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
10122 tlwExtra->backingStoreTracker->markDirty(rect, this);
10124 d_func()->repaint_sys(rect);
10131 This version repaints a region \a rgn inside the widget.
10133 void QWidget::update(const QRegion &rgn)
10135 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
10138 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
10139 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
10143 if (hasBackingStoreSupport()) {
10144 #ifdef QT_MAC_USE_COCOA
10145 if (qt_widget_private(this)->isInUnifiedToolbar) {
10146 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10149 #endif // QT_MAC_USE_COCOA
10150 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10151 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
10152 tlwExtra->backingStoreTracker->markDirty(rgn, this);
10154 d_func()->repaint_sys(rgn);
10162 This just sets the corresponding attribute bit to 1 or 0
10164 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
10167 if (attribute < int(8*sizeof(uint))) {
10169 data->widget_attributes |= (1<<attribute);
10171 data->widget_attributes &= ~(1<<attribute);
10173 const int x = attribute - 8*sizeof(uint);
10174 const int int_off = x / (8*sizeof(uint));
10176 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
10178 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
10183 Sets the attribute \a attribute on this widget if \a on is true;
10184 otherwise clears the attribute.
10186 \sa testAttribute()
10188 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
10190 if (testAttribute(attribute) == on)
10194 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
10195 "QWidget::setAttribute(WidgetAttribute, bool)",
10196 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
10198 // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
10199 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
10200 // see qwidget_win.cpp, ::paintEngine for details
10202 if (d->noPaintOnScreen)
10207 setAttribute_internal(attribute, on, data, d);
10209 switch (attribute) {
10211 #ifndef QT_NO_DRAGANDDROP
10212 case Qt::WA_AcceptDrops: {
10213 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
10214 setAttribute(Qt::WA_DropSiteRegistered, true);
10215 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
10216 setAttribute(Qt::WA_DropSiteRegistered, false);
10217 QEvent e(QEvent::AcceptDropsChange);
10218 QApplication::sendEvent(this, &e);
10221 case Qt::WA_DropSiteRegistered: {
10222 d->registerDropSite(on);
10223 for (int i = 0; i < d->children.size(); ++i) {
10224 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
10225 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
10226 w->setAttribute(Qt::WA_DropSiteRegistered, on);
10232 case Qt::WA_NoChildEventsForParent:
10233 d->sendChildEvents = !on;
10235 case Qt::WA_NoChildEventsFromChildren:
10236 d->receiveChildEvents = !on;
10238 case Qt::WA_MacBrushedMetal:
10240 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
10241 // fall through since changing the metal attribute affects the opaque size grip.
10242 case Qt::WA_MacOpaqueSizeGrip:
10243 d->macUpdateOpaqueSizeGrip();
10245 case Qt::WA_MacShowFocusRect:
10252 qt_mac_update_mouseTracking(this);
10255 case Qt::WA_MacAlwaysShowToolWindow:
10257 d->macUpdateHideOnSuspend();
10260 case Qt::WA_MacNormalSize:
10261 case Qt::WA_MacSmallSize:
10262 case Qt::WA_MacMiniSize:
10265 // We can only have one of these set at a time
10266 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10267 Qt::WA_MacMiniSize };
10268 for (int i = 0; i < 3; ++i) {
10269 if (MacSizes[i] != attribute)
10270 setAttribute_internal(MacSizes[i], false, data, d);
10272 d->macUpdateSizeAttribute();
10276 case Qt::WA_ShowModal:
10279 QApplicationPrivate::leaveModal(this);
10280 // reset modality type to Modeless when clearing WA_ShowModal
10281 data->window_modality = Qt::NonModal;
10282 } else if (data->window_modality == Qt::NonModal) {
10283 // determine the modality type if it hasn't been set prior
10284 // to setting WA_ShowModal. set the default to WindowModal
10285 // if we are the child of a group leader; otherwise use
10286 // ApplicationModal.
10287 QWidget *w = parentWidget();
10290 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10291 w = w->parentWidget();
10295 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10297 : Qt::ApplicationModal;
10298 // Some window managers does not allow us to enter modal after the
10299 // window is showing. Therefore, to be consistent, we cannot call
10300 // QApplicationPrivate::enterModal(this) here. The window must be
10301 // hidden before changing modality.
10303 if (testAttribute(Qt::WA_WState_Created)) {
10304 // don't call setModal_sys() before create_sys()
10308 case Qt::WA_MouseTracking: {
10309 QEvent e(QEvent::MouseTrackingChange);
10310 QApplication::sendEvent(this, &e);
10312 case Qt::WA_NativeWindow: {
10313 #if defined(Q_WS_QPA)
10314 d->createTLExtra();
10317 QWidget *focusWidget = d->effectiveFocusWidget();
10318 if (on && !internalWinId() && hasFocus()
10319 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10320 qApp->inputPanel()->commit();
10321 qApp->inputPanel()->setInputItem(0);
10323 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10324 #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA)
10325 // On Mac, toolbars inside the unified title bar will never overlap with
10326 // siblings in the content view. So we skip enforce native siblings in that case
10327 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10328 #endif // Q_WS_MAC && QT_MAC_USE_COCOA
10330 parentWidget()->d_func()->enforceNativeChildren();
10331 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10333 if (isEnabled() && focusWidget->isEnabled()
10334 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10335 qApp->inputPanel()->setInputItem(focusWidget);
10340 case Qt::WA_PaintOnScreen:
10341 d->updateIsOpaque();
10342 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
10343 // Recreate the widget if it's already created as an alien widget and
10344 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10345 // So must their children.
10347 setAttribute(Qt::WA_NativeWindow);
10348 d->enforceNativeChildren();
10352 case Qt::WA_OpaquePaintEvent:
10353 d->updateIsOpaque();
10355 case Qt::WA_NoSystemBackground:
10356 d->updateIsOpaque();
10358 case Qt::WA_UpdatesDisabled:
10359 d->updateSystemBackground();
10361 case Qt::WA_TransparentForMouseEvents:
10363 d->macUpdateIgnoreMouseEvents();
10366 case Qt::WA_InputMethodEnabled: {
10368 QWidget *focusWidget = d->effectiveFocusWidget();
10369 if (on && hasFocus() && isEnabled()
10370 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10371 qApp->inputPanel()->setInputItem(focusWidget);
10372 } else if (!on && qApp->inputPanel()->inputItem() == focusWidget) {
10373 qApp->inputPanel()->commit();
10374 qApp->inputPanel()->setInputItem(0);
10379 case Qt::WA_WindowPropagation:
10380 d->resolvePalette();
10382 d->resolveLocale();
10385 case Qt::WA_NoX11EventCompression:
10388 d->extra->compress_events = on;
10390 case Qt::WA_X11OpenGLOverlay:
10391 d->updateIsOpaque();
10393 case Qt::WA_X11DoNotAcceptFocus:
10394 if (testAttribute(Qt::WA_WState_Created))
10395 d->updateX11AcceptFocus();
10398 case Qt::WA_DontShowOnScreen: {
10399 if (on && isVisible()) {
10400 // Make sure we keep the current state and only hide the widget
10401 // from the desktop. show_sys will only update platform specific
10402 // attributes at this point.
10410 case Qt::WA_X11NetWmWindowTypeDesktop:
10411 case Qt::WA_X11NetWmWindowTypeDock:
10412 case Qt::WA_X11NetWmWindowTypeToolBar:
10413 case Qt::WA_X11NetWmWindowTypeMenu:
10414 case Qt::WA_X11NetWmWindowTypeUtility:
10415 case Qt::WA_X11NetWmWindowTypeSplash:
10416 case Qt::WA_X11NetWmWindowTypeDialog:
10417 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10418 case Qt::WA_X11NetWmWindowTypePopupMenu:
10419 case Qt::WA_X11NetWmWindowTypeToolTip:
10420 case Qt::WA_X11NetWmWindowTypeNotification:
10421 case Qt::WA_X11NetWmWindowTypeCombo:
10422 case Qt::WA_X11NetWmWindowTypeDND:
10423 if (testAttribute(Qt::WA_WState_Created))
10424 d->setNetWmWindowTypes();
10428 case Qt::WA_StaticContents:
10429 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10431 bs->addStaticWidget(this);
10433 bs->removeStaticWidget(this);
10436 case Qt::WA_TranslucentBackground:
10438 setAttribute(Qt::WA_NoSystemBackground);
10439 d->updateIsTranslucent();
10443 case Qt::WA_AcceptTouchEvents:
10444 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
10446 d->registerTouchWindow();
10449 case Qt::WA_LockPortraitOrientation:
10450 case Qt::WA_LockLandscapeOrientation:
10451 case Qt::WA_AutoOrientation: {
10452 const Qt::WidgetAttribute orientations[3] = {
10453 Qt::WA_LockPortraitOrientation,
10454 Qt::WA_LockLandscapeOrientation,
10455 Qt::WA_AutoOrientation
10459 // We can only have one of these set at a time
10460 for (int i = 0; i < 3; ++i) {
10461 if (orientations[i] != attribute)
10462 setAttribute_internal(orientations[i], false, data, d);
10467 CAknAppUiBase* appUi = static_cast<CAknAppUiBase*>(CEikonEnv::Static()->EikAppUi());
10468 const CAknAppUiBase::TAppUiOrientation s60orientations[] = {
10469 CAknAppUiBase::EAppUiOrientationPortrait,
10470 CAknAppUiBase::EAppUiOrientationLandscape,
10471 CAknAppUiBase::EAppUiOrientationAutomatic
10473 CAknAppUiBase::TAppUiOrientation s60orientation = CAknAppUiBase::EAppUiOrientationUnspecified;
10474 for (int i = 0; i < 3; ++i) {
10475 if (testAttribute(orientations[i])) {
10476 s60orientation = s60orientations[i];
10480 QT_TRAP_THROWING(appUi->SetOrientationL(s60orientation));
10481 S60->orientationSet = true;
10482 QSymbianControl *window = static_cast<QSymbianControl *>(internalWinId());
10484 window->ensureFixNativeOrientation();
10493 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10495 Returns true if attribute \a attribute is set on this widget;
10496 otherwise returns false.
10500 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10502 Q_D(const QWidget);
10503 const int x = attribute - 8*sizeof(uint);
10504 const int int_off = x / (8*sizeof(uint));
10505 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10509 \property QWidget::windowOpacity
10511 \brief The level of opacity for the window.
10513 The valid range of opacity is from 1.0 (completely opaque) to
10514 0.0 (completely transparent).
10516 By default the value of this property is 1.0.
10518 This feature is available on Embedded Linux, Mac OS X, Windows,
10519 and X11 platforms that support the Composite extension.
10521 This feature is not available on Windows CE.
10523 Note that under X11 you need to have a composite manager running,
10524 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10525 supported by the window manager you are using.
10527 \warning Changing this property from opaque to transparent might issue a
10528 paint event that needs to be processed before the window is displayed
10529 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10530 that semi-transparent windows update and resize significantly slower than
10535 qreal QWidget::windowOpacity() const
10537 Q_D(const QWidget);
10538 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10541 void QWidget::setWindowOpacity(qreal opacity)
10547 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10548 QTLWExtra *extra = d->topData();
10549 extra->opacity = uint(opacity * 255);
10550 setAttribute(Qt::WA_WState_WindowOpacitySet);
10552 if (!testAttribute(Qt::WA_WState_Created))
10555 #ifndef QT_NO_GRAPHICSVIEW
10556 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10557 // Avoid invalidating the cache if set.
10558 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10560 else if (QGraphicsScene *scene = proxy->scene())
10561 scene->update(proxy->sceneBoundingRect());
10566 d->setWindowOpacity_sys(opacity);
10570 \property QWidget::windowModified
10571 \brief whether the document shown in the window has unsaved changes
10573 A modified window is a window whose content has changed but has
10574 not been saved to disk. This flag will have different effects
10575 varied by the platform. On Mac OS X the close button will have a
10576 modified look; on other platforms, the window title will have an
10579 The window title must contain a "[*]" placeholder, which
10580 indicates where the '*' should appear. Normally, it should appear
10581 right after the file name (e.g., "document1.txt[*] - Text
10582 Editor"). If the window isn't modified, the placeholder is simply
10585 Note that if a widget is set as modified, all its ancestors will
10586 also be set as modified. However, if you call \c
10587 {setWindowModified(false)} on a widget, this will not propagate to
10588 its parent because other children of the parent might have been
10591 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10593 bool QWidget::isWindowModified() const
10595 return testAttribute(Qt::WA_WindowModified);
10598 void QWidget::setWindowModified(bool mod)
10601 setAttribute(Qt::WA_WindowModified, mod);
10604 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10605 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10607 d->setWindowTitle_helper(windowTitle());
10608 d->setWindowIconText_helper(windowIconText());
10610 d->setWindowModified_sys(mod);
10613 QEvent e(QEvent::ModifiedChange);
10614 QApplication::sendEvent(this, &e);
10617 #ifndef QT_NO_TOOLTIP
10619 \property QWidget::toolTip
10621 \brief the widget's tooltip
10623 Note that by default tooltips are only shown for widgets that are
10624 children of the active window. You can change this behavior by
10625 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10626 not on the widget with the tooltip.
10628 If you want to control a tooltip's behavior, you can intercept the
10629 event() function and catch the QEvent::ToolTip event (e.g., if you
10630 want to customize the area for which the tooltip should be shown).
10632 By default, this property contains an empty string.
10634 \sa QToolTip statusTip whatsThis
10636 void QWidget::setToolTip(const QString &s)
10641 QEvent event(QEvent::ToolTipChange);
10642 QApplication::sendEvent(this, &event);
10645 QString QWidget::toolTip() const
10647 Q_D(const QWidget);
10650 #endif // QT_NO_TOOLTIP
10653 #ifndef QT_NO_STATUSTIP
10655 \property QWidget::statusTip
10656 \brief the widget's status tip
10658 By default, this property contains an empty string.
10660 \sa toolTip whatsThis
10662 void QWidget::setStatusTip(const QString &s)
10668 QString QWidget::statusTip() const
10670 Q_D(const QWidget);
10671 return d->statusTip;
10673 #endif // QT_NO_STATUSTIP
10675 #ifndef QT_NO_WHATSTHIS
10677 \property QWidget::whatsThis
10679 \brief the widget's What's This help text.
10681 By default, this property contains an empty string.
10683 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10685 void QWidget::setWhatsThis(const QString &s)
10691 QString QWidget::whatsThis() const
10693 Q_D(const QWidget);
10694 return d->whatsThis;
10696 #endif // QT_NO_WHATSTHIS
10698 #ifndef QT_NO_ACCESSIBILITY
10700 \property QWidget::accessibleName
10702 \brief the widget's name as seen by assistive technologies
10704 This property is used by accessible clients to identify, find, or announce
10705 the widget for accessible clients.
10707 By default, this property contains an empty string.
10709 \sa QAccessibleInterface::text()
10711 void QWidget::setAccessibleName(const QString &name)
10714 d->accessibleName = name;
10715 QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged);
10718 QString QWidget::accessibleName() const
10720 Q_D(const QWidget);
10721 return d->accessibleName;
10725 \property QWidget::accessibleDescription
10727 \brief the widget's description as seen by assistive technologies
10729 By default, this property contains an empty string.
10731 \sa QAccessibleInterface::text()
10733 void QWidget::setAccessibleDescription(const QString &description)
10736 d->accessibleDescription = description;
10737 QAccessible::updateAccessibility(this, 0, QAccessible::DescriptionChanged);
10740 QString QWidget::accessibleDescription() const
10742 Q_D(const QWidget);
10743 return d->accessibleDescription;
10745 #endif // QT_NO_ACCESSIBILITY
10747 #ifndef QT_NO_SHORTCUT
10749 Adds a shortcut to Qt's shortcut system that watches for the given
10750 \a key sequence in the given \a context. If the \a context is
10751 Qt::ApplicationShortcut, the shortcut applies to the application as a
10752 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10753 or to the window itself, Qt::WindowShortcut.
10755 If the same \a key sequence has been grabbed by several widgets,
10756 when the \a key sequence occurs a QEvent::Shortcut event is sent
10757 to all the widgets to which it applies in a non-deterministic
10758 order, but with the ``ambiguous'' flag set to true.
10760 \warning You should not normally need to use this function;
10761 instead create \l{QAction}s with the shortcut key sequences you
10762 require (if you also want equivalent menu options and toolbar
10763 buttons), or create \l{QShortcut}s if you just need key sequences.
10764 Both QAction and QShortcut handle all the event filtering for you,
10765 and provide signals which are triggered when the user triggers the
10766 key sequence, so are much easier to use than this low-level
10769 \sa releaseShortcut() setShortcutEnabled()
10771 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10776 setAttribute(Qt::WA_GrabbedShortcut);
10777 return qApp->d_func()->shortcutMap.addShortcut(this, key, context);
10781 Removes the shortcut with the given \a id from Qt's shortcut
10782 system. The widget will no longer receive QEvent::Shortcut events
10783 for the shortcut's key sequence (unless it has other shortcuts
10784 with the same key sequence).
10786 \warning You should not normally need to use this function since
10787 Qt's shortcut system removes shortcuts automatically when their
10788 parent widget is destroyed. It is best to use QAction or
10789 QShortcut to handle shortcuts, since they are easier to use than
10790 this low-level function. Note also that this is an expensive
10793 \sa grabShortcut() setShortcutEnabled()
10795 void QWidget::releaseShortcut(int id)
10799 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10803 If \a enable is true, the shortcut with the given \a id is
10804 enabled; otherwise the shortcut is disabled.
10806 \warning You should not normally need to use this function since
10807 Qt's shortcut system enables/disables shortcuts automatically as
10808 widgets become hidden/visible and gain or lose focus. It is best
10809 to use QAction or QShortcut to handle shortcuts, since they are
10810 easier to use than this low-level function.
10812 \sa grabShortcut() releaseShortcut()
10814 void QWidget::setShortcutEnabled(int id, bool enable)
10818 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10824 If \a enable is true, auto repeat of the shortcut with the
10825 given \a id is enabled; otherwise it is disabled.
10827 \sa grabShortcut() releaseShortcut()
10829 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10833 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10835 #endif // QT_NO_SHORTCUT
10838 Updates the widget's micro focus.
10842 void QWidget::updateMicroFocus()
10844 // updating everything since this is currently called for any kind of state change
10845 qApp->inputPanel()->update(Qt::ImQueryAll);
10847 #ifndef QT_NO_ACCESSIBILITY
10849 // ##### is this correct
10850 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
10856 #if defined (Q_WS_WIN)
10858 Returns the window system handle of the widget, for low-level
10859 access. Using this function is not portable.
10861 An HDC acquired with getDC() has to be released with releaseDC().
10863 \warning Using this function is not portable.
10865 HDC QWidget::getDC() const
10867 Q_D(const QWidget);
10869 return (HDC) d->hd;
10870 return GetDC(winId());
10874 Releases the HDC \a hdc acquired by a previous call to getDC().
10876 \warning Using this function is not portable.
10878 void QWidget::releaseDC(HDC hdc) const
10880 Q_D(const QWidget);
10881 // If its the widgets own dc, it will be released elsewhere. If
10882 // its a different HDC we release it and issue a warning if it
10884 if (hdc != d->hd && !ReleaseDC(winId(), hdc))
10885 qErrnoWarning("QWidget::releaseDC(): failed to release HDC");
10889 Returns the window system handle of the widget, for low-level
10890 access. Using this function is not portable.
10892 The HANDLE type varies with platform; see \c qwindowdefs.h for
10895 Qt::HANDLE QWidget::handle() const
10897 Q_D(const QWidget);
10898 if (!internalWinId() && testAttribute(Qt::WA_WState_Created))
10899 (void)winId(); // enforce native window
10906 Raises this widget to the top of the parent widget's stack.
10908 After this call the widget will be visually in front of any
10909 overlapping sibling widgets.
10911 \note When using activateWindow(), you can call this function to
10912 ensure that the window is stacked on top.
10914 \sa lower(), stackUnder()
10917 void QWidget::raise()
10921 QWidget *p = parentWidget();
10922 const int parentChildCount = p->d_func()->children.size();
10923 if (parentChildCount < 2)
10925 const int from = p->d_func()->children.indexOf(this);
10926 Q_ASSERT(from >= 0);
10927 // Do nothing if the widget is already in correct stacking order _and_ created.
10928 if (from != parentChildCount -1)
10929 p->d_func()->children.move(from, parentChildCount - 1);
10930 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10932 else if (from == parentChildCount - 1)
10935 QRegion region(rect());
10936 d->subtractOpaqueSiblings(region);
10937 d->invalidateBuffer(region);
10939 if (testAttribute(Qt::WA_WState_Created))
10942 QEvent e(QEvent::ZOrderChange);
10943 QApplication::sendEvent(this, &e);
10947 Lowers the widget to the bottom of the parent widget's stack.
10949 After this call the widget will be visually behind (and therefore
10950 obscured by) any overlapping sibling widgets.
10952 \sa raise(), stackUnder()
10955 void QWidget::lower()
10959 QWidget *p = parentWidget();
10960 const int parentChildCount = p->d_func()->children.size();
10961 if (parentChildCount < 2)
10963 const int from = p->d_func()->children.indexOf(this);
10964 Q_ASSERT(from >= 0);
10965 // Do nothing if the widget is already in correct stacking order _and_ created.
10967 p->d_func()->children.move(from, 0);
10968 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10970 else if (from == 0)
10973 if (testAttribute(Qt::WA_WState_Created))
10976 QEvent e(QEvent::ZOrderChange);
10977 QApplication::sendEvent(this, &e);
10982 Places the widget under \a w in the parent widget's stack.
10984 To make this work, the widget itself and \a w must be siblings.
10986 \sa raise(), lower()
10988 void QWidget::stackUnder(QWidget* w)
10991 QWidget *p = parentWidget();
10992 if (!w || isWindow() || p != w->parentWidget() || this == w)
10995 int from = p->d_func()->children.indexOf(this);
10996 int to = p->d_func()->children.indexOf(w);
10997 Q_ASSERT(from >= 0);
11001 // Do nothing if the widget is already in correct stacking order _and_ created.
11003 p->d_func()->children.move(from, to);
11004 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
11006 else if (from == to)
11009 if (testAttribute(Qt::WA_WState_Created))
11010 d->stackUnder_sys(w);
11012 QEvent e(QEvent::ZOrderChange);
11013 QApplication::sendEvent(this, &e);
11016 void QWidget::styleChange(QStyle&) { }
11017 void QWidget::enabledChange(bool) { } // compat
11018 void QWidget::paletteChange(const QPalette &) { } // compat
11019 void QWidget::fontChange(const QFont &) { } // compat
11020 void QWidget::windowActivationChange(bool) { } // compat
11021 void QWidget::languageChange() { } // compat
11025 \enum QWidget::BackgroundOrigin
11029 \value WidgetOrigin
11030 \value ParentOrigin
11031 \value WindowOrigin
11032 \value AncestorOrigin
11037 \fn bool QWidget::isVisibleToTLW() const
11039 Use isVisible() instead.
11043 \fn void QWidget::iconify()
11045 Use showMinimized() instead.
11049 \fn void QWidget::constPolish() const
11051 Use ensurePolished() instead.
11055 \fn void QWidget::reparent(QWidget *parent, Qt::WindowFlags f, const QPoint &p, bool showIt)
11057 Use setParent() to change the parent or the widget's widget flags;
11058 use move() to move the widget, and use show() to show the widget.
11062 \fn void QWidget::reparent(QWidget *parent, const QPoint &p, bool showIt)
11064 Use setParent() to change the parent; use move() to move the
11065 widget, and use show() to show the widget.
11069 \fn void QWidget::recreate(QWidget *parent, Qt::WindowFlags f, const QPoint & p, bool showIt)
11071 Use setParent() to change the parent or the widget's widget flags;
11072 use move() to move the widget, and use show() to show the widget.
11076 \fn bool QWidget::hasMouse() const
11078 Use testAttribute(Qt::WA_UnderMouse) instead.
11082 \fn bool QWidget::ownCursor() const
11084 Use testAttribute(Qt::WA_SetCursor) instead.
11088 \fn bool QWidget::ownFont() const
11090 Use testAttribute(Qt::WA_SetFont) instead.
11094 \fn void QWidget::unsetFont()
11096 Use setFont(QFont()) instead.
11100 \fn bool QWidget::ownPalette() const
11102 Use testAttribute(Qt::WA_SetPalette) instead.
11106 \fn void QWidget::unsetPalette()
11108 Use setPalette(QPalette()) instead.
11112 \fn void QWidget::setEraseColor(const QColor &color)
11114 Use the palette instead.
11117 widget->setEraseColor(color);
11120 palette.setColor(widget->backgroundRole(), color);
11121 widget->setPalette(palette);
11126 \fn void QWidget::setErasePixmap(const QPixmap &pixmap)
11128 Use the palette instead.
11131 widget->setErasePixmap(pixmap);
11134 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11135 widget->setPalette(palette);
11140 \fn void QWidget::setPaletteForegroundColor(const QColor &color)
11142 Use the palette directly.
11145 widget->setPaletteForegroundColor(color);
11148 palette.setColor(widget->foregroundRole(), color);
11149 widget->setPalette(palette);
11154 \fn void QWidget::setPaletteBackgroundColor(const QColor &color)
11156 Use the palette directly.
11159 widget->setPaletteBackgroundColor(color);
11162 palette.setColor(widget->backgroundRole(), color);
11163 widget->setPalette(palette);
11168 \fn void QWidget::setPaletteBackgroundPixmap(const QPixmap &pixmap)
11170 Use the palette directly.
11173 widget->setPaletteBackgroundPixmap(pixmap);
11176 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11177 widget->setPalette(palette);
11182 \fn void QWidget::setBackgroundPixmap(const QPixmap &pixmap)
11184 Use the palette instead.
11187 widget->setBackgroundPixmap(pixmap);
11190 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11191 widget->setPalette(palette);
11196 \fn void QWidget::setBackgroundColor(const QColor &color)
11198 Use the palette instead.
11201 widget->setBackgroundColor(color);
11204 palette.setColor(widget->backgroundRole(), color);
11205 widget->setPalette(palette);
11211 \fn QWidget *QWidget::parentWidget(bool sameWindow) const
11213 Use the no-argument overload instead.
11217 \fn void QWidget::setKeyCompression(bool b)
11219 Use setAttribute(Qt::WA_KeyCompression, b) instead.
11223 \fn void QWidget::setFont(const QFont &f, bool b)
11225 Use the single-argument overload instead.
11229 \fn void QWidget::setPalette(const QPalette &p, bool b)
11231 Use the single-argument overload instead.
11235 \fn void QWidget::setBackgroundOrigin(BackgroundOrigin background)
11241 \fn BackgroundOrigin QWidget::backgroundOrigin() const
11245 Always returns \c WindowOrigin.
11249 \fn QPoint QWidget::backgroundOffset() const
11253 Always returns QPoint().
11257 \fn void QWidget::repaint(bool b)
11259 The boolean parameter \a b is ignored. Use the no-argument overload instead.
11263 \fn void QWidget::repaint(int x, int y, int w, int h, bool b)
11265 The boolean parameter \a b is ignored. Use the four-argument overload instead.
11269 \fn void QWidget::repaint(const QRect &r, bool b)
11271 The boolean parameter \a b is ignored. Use the single rect-argument overload instead.
11275 \fn void QWidget::repaint(const QRegion &rgn, bool b)
11277 The boolean parameter \a b is ignored. Use the single region-argument overload instead.
11281 \fn void QWidget::erase()
11283 Drawing may only take place in a QPaintEvent. Overload
11284 paintEvent() to do your erasing and call update() to schedule a
11285 replaint whenever necessary. See also QPainter.
11289 \fn void QWidget::erase(int x, int y, int w, int h)
11291 Drawing may only take place in a QPaintEvent. Overload
11292 paintEvent() to do your erasing and call update() to schedule a
11293 replaint whenever necessary. See also QPainter.
11297 \fn void QWidget::erase(const QRect &rect)
11299 Drawing may only take place in a QPaintEvent. Overload
11300 paintEvent() to do your erasing and call update() to schedule a
11301 replaint whenever necessary. See also QPainter.
11305 \fn void QWidget::drawText(const QPoint &p, const QString &s)
11307 Drawing may only take place in a QPaintEvent. Overload
11308 paintEvent() to do your drawing and call update() to schedule a
11309 replaint whenever necessary. See also QPainter.
11313 \fn void QWidget::drawText(int x, int y, const QString &s)
11315 Drawing may only take place in a QPaintEvent. Overload
11316 paintEvent() to do your drawing and call update() to schedule a
11317 replaint whenever necessary. See also QPainter.
11321 \fn QWidget *QWidget::childAt(const QPoint &p, bool includeThis) const
11323 Use the single point argument overload instead.
11327 \fn void QWidget::setCaption(const QString &c)
11329 Use setWindowTitle() instead.
11333 \fn void QWidget::setIcon(const QPixmap &i)
11335 Use setWindowIcon() instead.
11339 \fn void QWidget::setIconText(const QString &it)
11341 Use setWindowIconText() instead.
11345 \fn QString QWidget::caption() const
11347 Use windowTitle() instead.
11351 \fn QString QWidget::iconText() const
11353 Use windowIconText() instead.
11357 \fn bool QWidget::isTopLevel() const
11360 Use isWindow() instead.
11364 \fn bool QWidget::isRightToLeft() const
11369 \fn bool QWidget::isLeftToRight() const
11374 \fn void QWidget::setInputMethodEnabled(bool enabled)
11376 Use setAttribute(Qt::WA_InputMethodEnabled, \a enabled) instead.
11380 \fn bool QWidget::isInputMethodEnabled() const
11382 Use testAttribute(Qt::WA_InputMethodEnabled) instead.
11386 \fn void QWidget::setActiveWindow()
11388 Use activateWindow() instead.
11392 \fn bool QWidget::isShown() const
11394 Use !isHidden() instead (notice the exclamation mark), or use isVisible() to check whether the widget is visible.
11398 \fn bool QWidget::isDialog() const
11400 Use windowType() == Qt::Dialog instead.
11404 \fn bool QWidget::isPopup() const
11406 Use windowType() == Qt::Popup instead.
11410 \fn bool QWidget::isDesktop() const
11412 Use windowType() == Qt::Desktop instead.
11416 \fn void QWidget::polish()
11418 Use ensurePolished() instead.
11422 \fn QWidget *QWidget::childAt(int x, int y, bool includeThis) const
11424 Use the childAt() overload that doesn't have an \a includeThis parameter.
11427 return widget->childAt(x, y, true);
11429 QWidget *child = widget->childAt(x, y, true);
11432 if (widget->rect().contains(x, y))
11438 \fn void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw)
11441 Use the \l sizePolicy property and heightForWidth() function instead.
11445 \fn bool QWidget::isUpdatesEnabled() const
11448 Use the \l updatesEnabled property instead.
11452 \macro QWIDGETSIZE_MAX
11455 Defines the maximum size for a QWidget object.
11457 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
11458 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
11460 \sa QWidget::setMaximumSize()
11464 \fn QWidget::setupUi(QWidget *widget)
11466 Sets up the user interface for the specified \a widget.
11468 \note This function is available with widgets that derive from user
11469 interface descriptions created using \l{uic}.
11471 \sa {Using a Designer UI File in Your Application}
11474 QRect QWidgetPrivate::frameStrut() const
11476 Q_Q(const QWidget);
11477 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
11478 // x2 = x1 + w - 1, so w/h = 1
11479 return QRect(0, 0, 1, 1);
11482 if (data.fstrut_dirty
11484 // ### Fix properly for 4.3
11487 && q->testAttribute(Qt::WA_WState_Created))
11488 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
11490 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
11493 #ifdef QT_KEYPAD_NAVIGATION
11497 Changes the focus from the current focusWidget to a widget in
11500 Returns true, if there was a widget in that direction
11502 bool QWidgetPrivate::navigateToDirection(Direction direction)
11504 QWidget *targetWidget = widgetInNavigationDirection(direction);
11506 targetWidget->setFocus();
11507 return (targetWidget != 0);
11513 Searches for a widget that is positioned in the \a direction, starting
11514 from the current focusWidget.
11516 Returns the pointer to a found widget or 0, if there was no widget in
11519 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
11521 const QWidget *sourceWidget = QApplication::focusWidget();
11524 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
11525 const int sourceX =
11526 (direction == DirectionNorth || direction == DirectionSouth) ?
11527 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
11528 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
11529 const int sourceY =
11530 (direction == DirectionEast || direction == DirectionWest) ?
11531 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
11532 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
11533 const QPoint sourcePoint(sourceX, sourceY);
11534 const QPoint sourceCenter = sourceRect.center();
11535 const QWidget *sourceWindow = sourceWidget->window();
11537 QWidget *targetWidget = 0;
11538 int shortestDistance = INT_MAX;
11539 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
11541 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
11543 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
11544 // but the owner of the proxy cannot.
11545 // Additionally, empty widgets should be ignored.
11546 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
11549 // Only navigate to a target widget that...
11550 if ( targetCandidate != sourceWidget
11551 // ...takes the focus,
11552 && targetCandidate->focusPolicy() & Qt::TabFocus
11553 // ...is above if DirectionNorth,
11554 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
11555 // ...is on the right if DirectionEast,
11556 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
11557 // ...is below if DirectionSouth,
11558 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
11559 // ...is on the left if DirectionWest,
11560 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
11562 && targetCandidate->isEnabled()
11564 && targetCandidate->isVisible()
11565 // ...is in the same window,
11566 && targetCandidate->window() == sourceWindow) {
11567 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
11568 if (targetCandidateDistance < shortestDistance) {
11569 shortestDistance = targetCandidateDistance;
11570 targetWidget = targetCandidate;
11574 return targetWidget;
11580 Tells us if it there is currently a reachable widget by keypad navigation in
11581 a certain \a orientation.
11582 If no navigation is possible, occurring key events in that \a orientation may
11583 be used to interact with the value in the focused widget, even though it
11584 currently has not the editFocus.
11586 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
11588 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
11590 return orientation == Qt::Horizontal?
11591 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
11592 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
11593 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
11594 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
11599 Checks, if the \a widget is inside a QTabWidget. If is is inside
11600 one, left/right key events will be used to switch between tabs in keypad
11601 navigation. If there is no QTabWidget, the horizontal key events can be used
11603 interact with the value in the focused widget, even though it currently has
11606 \sa QWidget::hasEditFocus()
11608 bool QWidgetPrivate::inTabWidget(QWidget *widget)
11610 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
11611 if (qobject_cast<const QTabWidget*>(tabWidget))
11621 Sets the backing store to be the \a store specified.
11622 The QWidget will take ownership of the \a store.
11624 void QWidget::setBackingStore(QBackingStore *store)
11626 // ### createWinId() ??
11633 QTLWExtra *topData = d->topData();
11634 if (topData->backingStore == store)
11637 QBackingStore *oldStore = topData->backingStore;
11638 delete topData->backingStore;
11639 topData->backingStore = store;
11641 QWidgetBackingStore *bs = d->maybeBackingStore();
11645 if (isTopLevel()) {
11646 if (bs->store != oldStore && bs->store != store)
11655 Returns the QBackingStore this widget will be drawn into.
11657 QBackingStore *QWidget::backingStore() const
11659 Q_D(const QWidget);
11660 QTLWExtra *extra = d->maybeTopData();
11661 if (extra && extra->backingStore)
11662 return extra->backingStore;
11664 QWidgetBackingStore *bs = d->maybeBackingStore();
11666 return bs ? bs->store : 0;
11669 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
11672 *left = (int)leftLayoutItemMargin;
11674 *top = (int)topLayoutItemMargin;
11676 *right = (int)rightLayoutItemMargin;
11678 *bottom = (int)bottomLayoutItemMargin;
11681 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
11683 if (leftLayoutItemMargin == left
11684 && topLayoutItemMargin == top
11685 && rightLayoutItemMargin == right
11686 && bottomLayoutItemMargin == bottom)
11690 leftLayoutItemMargin = (signed char)left;
11691 topLayoutItemMargin = (signed char)top;
11692 rightLayoutItemMargin = (signed char)right;
11693 bottomLayoutItemMargin = (signed char)bottom;
11694 q->updateGeometry();
11697 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
11700 QStyleOption myOpt;
11703 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
11707 QRect liRect = q->style()->subElementRect(element, opt, q);
11708 if (liRect.isValid()) {
11709 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
11710 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
11711 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
11712 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
11714 leftLayoutItemMargin = 0;
11715 topLayoutItemMargin = 0;
11716 rightLayoutItemMargin = 0;
11717 bottomLayoutItemMargin = 0;
11720 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
11721 void QWidgetPrivate::adjustQuitOnCloseAttribute()
11725 if (!q->parentWidget()) {
11726 Qt::WindowType type = q->windowType();
11727 if (type == Qt::Widget || type == Qt::SubWindow)
11729 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
11730 q->setAttribute(Qt::WA_QuitOnClose, false);
11736 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
11738 return widget->data;
11741 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
11743 return widget->d_func();
11747 #ifndef QT_NO_GRAPHICSVIEW
11751 Returns the proxy widget for the corresponding embedded widget in a graphics
11752 view; otherwise returns 0.
11754 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
11755 QGraphicsScene::addWidget()
11757 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
11759 Q_D(const QWidget);
11761 return d->extra->proxyWidget;
11769 \typedef QWidgetList
11772 Synonym for QList<QWidget *>.
11775 #ifndef QT_NO_GESTURES
11777 Subscribes the widget to a given \a gesture with specific \a flags.
11779 \sa ungrabGesture(), QGestureEvent
11782 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11785 d->gestureContext.insert(gesture, flags);
11786 (void)QGestureManager::instance(); // create a gesture manager
11790 Unsubscribes the widget from a given \a gesture type
11792 \sa grabGesture(), QGestureEvent
11795 void QWidget::ungrabGesture(Qt::GestureType gesture)
11798 if (d->gestureContext.remove(gesture)) {
11799 if (QGestureManager *manager = QGestureManager::instance())
11800 manager->cleanupCachedGestures(this, gesture);
11803 #endif // QT_NO_GESTURES
11809 Platform dependent window identifier.
11813 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11815 Frees up window system resources. Destroys the widget window if \a
11816 destroyWindow is true.
11818 destroy() calls itself recursively for all the child widgets,
11819 passing \a destroySubWindows for the \a destroyWindow parameter.
11820 To have more control over destruction of subwidgets, destroy
11821 subwidgets selectively first.
11823 This function is usually called from the QWidget destructor.
11827 \fn QPaintEngine *QWidget::paintEngine() const
11829 Returns the widget's paint engine.
11831 Note that this function should not be called explicitly by the
11832 user, since it's meant for reimplementation purposes only. The
11833 function is called by Qt internally, and the default
11834 implementation may not always return a valid pointer.
11838 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11840 Translates the widget coordinate \a pos to global screen
11841 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11842 the global coordinates of the top-left pixel of the widget.
11844 \sa mapFromGlobal() mapTo() mapToParent()
11848 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11850 Translates the global screen coordinate \a pos to widget
11853 \sa mapToGlobal() mapFrom() mapFromParent()
11857 \fn void QWidget::grabMouse()
11859 Grabs the mouse input.
11861 This widget receives all mouse events until releaseMouse() is
11862 called; other widgets get no mouse events at all. Keyboard
11863 events are not affected. Use grabKeyboard() if you want to grab
11866 \warning Bugs in mouse-grabbing applications very often lock the
11867 terminal. Use this function with extreme caution, and consider
11868 using the \c -nograb command line option while debugging.
11870 It is almost never necessary to grab the mouse when using Qt, as
11871 Qt grabs and releases it sensibly. In particular, Qt grabs the
11872 mouse when a mouse button is pressed and keeps it until the last
11873 button is released.
11875 \note Only visible widgets can grab mouse input. If isVisible()
11876 returns false for a widget, that widget cannot call grabMouse().
11878 \note \bold{(Mac OS X developers)} For \e Cocoa, calling
11879 grabMouse() on a widget only works when the mouse is inside the
11880 frame of that widget. For \e Carbon, it works outside the widget's
11881 frame as well, like for Windows and X11.
11883 \sa releaseMouse() grabKeyboard() releaseKeyboard()
11887 \fn void QWidget::grabMouse(const QCursor &cursor)
11888 \overload grabMouse()
11890 Grabs the mouse input and changes the cursor shape.
11892 The cursor will assume shape \a cursor (for as long as the mouse
11893 focus is grabbed) and this widget will be the only one to receive
11894 mouse events until releaseMouse() is called().
11896 \warning Grabbing the mouse might lock the terminal.
11898 \note \bold{(Mac OS X developers)} See the note in QWidget::grabMouse().
11900 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11904 \fn void QWidget::releaseMouse()
11906 Releases the mouse grab.
11908 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11912 \fn void QWidget::grabKeyboard()
11914 Grabs the keyboard input.
11916 This widget receives all keyboard events until releaseKeyboard()
11917 is called; other widgets get no keyboard events at all. Mouse
11918 events are not affected. Use grabMouse() if you want to grab that.
11920 The focus widget is not affected, except that it doesn't receive
11921 any keyboard events. setFocus() moves the focus as usual, but the
11922 new focus widget receives keyboard events only after
11923 releaseKeyboard() is called.
11925 If a different widget is currently grabbing keyboard input, that
11926 widget's grab is released first.
11928 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11932 \fn void QWidget::releaseKeyboard()
11934 Releases the keyboard grab.
11936 \sa grabKeyboard(), grabMouse(), releaseMouse()
11940 \fn QWidget *QWidget::mouseGrabber()
11942 Returns the widget that is currently grabbing the mouse input.
11944 If no widget in this application is currently grabbing the mouse,
11947 \sa grabMouse(), keyboardGrabber()
11951 \fn QWidget *QWidget::keyboardGrabber()
11953 Returns the widget that is currently grabbing the keyboard input.
11955 If no widget in this application is currently grabbing the
11956 keyboard, 0 is returned.
11958 \sa grabMouse(), mouseGrabber()
11962 \fn void QWidget::activateWindow()
11964 Sets the top-level widget containing this widget to be the active
11967 An active window is a visible top-level window that has the
11968 keyboard input focus.
11970 This function performs the same operation as clicking the mouse on
11971 the title bar of a top-level window. On X11, the result depends on
11972 the Window Manager. If you want to ensure that the window is
11973 stacked on top as well you should also call raise(). Note that the
11974 window must be visible, otherwise activateWindow() has no effect.
11976 On Windows, if you are calling this when the application is not
11977 currently the active one then it will not make it the active
11978 window. It will change the color of the taskbar entry to indicate
11979 that the window has changed in some way. This is because Microsoft
11980 does not allow an application to interrupt what the user is currently
11981 doing in another application.
11983 \sa isActiveWindow(), window(), show()
11987 \fn int QWidget::metric(PaintDeviceMetric m) const
11989 Internal implementation of the virtual QPaintDevice::metric()
11992 \a m is the metric to get.
11995 void QWidget::init(QPainter *painter) const
11997 const QPalette &pal = palette();
11998 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
11999 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
12000 QFont f(font(), const_cast<QWidget *>(this));
12001 painter->d_func()->state->deviceFont = f;
12002 painter->d_func()->state->font = f;
12005 QPaintDevice *QWidget::redirected(QPoint *offset) const
12007 return d_func()->redirected(offset);
12010 QPainter *QWidget::sharedPainter() const
12012 // Someone sent a paint event directly to the widget
12013 if (!d_func()->redirectDev)
12016 QPainter *sp = d_func()->sharedPainter();
12017 if (!sp || !sp->isActive())
12020 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
12027 \fn void QWidget::setMask(const QRegion ®ion)
12030 Causes only the parts of the widget which overlap \a region to be
12031 visible. If the region includes pixels outside the rect() of the
12032 widget, window system controls in that area may or may not be
12033 visible, depending on the platform.
12035 Note that this effect can be slow if the region is particularly
12040 void QWidget::setMask(const QRegion &newMask)
12045 if (newMask == d->extra->mask)
12048 #ifndef QT_NO_BACKINGSTORE
12049 const QRegion oldMask(d->extra->mask);
12052 d->extra->mask = newMask;
12053 d->extra->hasMask = !newMask.isEmpty();
12055 #ifndef QT_MAC_USE_COCOA
12056 if (!testAttribute(Qt::WA_WState_Created))
12060 d->setMask_sys(newMask);
12062 #ifndef QT_NO_BACKINGSTORE
12066 if (!d->extra->hasMask) {
12067 // Mask was cleared; update newly exposed area.
12068 QRegion expose(rect());
12070 if (!expose.isEmpty()) {
12071 d->setDirtyOpaqueRegion();
12078 // Update newly exposed area on the parent widget.
12079 QRegion parentExpose(rect());
12080 parentExpose -= newMask;
12081 if (!parentExpose.isEmpty()) {
12082 d->setDirtyOpaqueRegion();
12083 parentExpose.translate(data->crect.topLeft());
12084 parentWidget()->update(parentExpose);
12087 // Update newly exposed area on this widget
12088 if (!oldMask.isEmpty())
12089 update(newMask - oldMask);
12095 \fn void QWidget::setMask(const QBitmap &bitmap)
12097 Causes only the pixels of the widget for which \a bitmap has a
12098 corresponding 1 bit to be visible. If the region includes pixels
12099 outside the rect() of the widget, window system controls in that
12100 area may or may not be visible, depending on the platform.
12102 Note that this effect can be slow if the region is particularly
12105 The following code shows how an image with an alpha channel can be
12106 used to generate a mask for a widget:
12108 \snippet doc/src/snippets/widget-mask/main.cpp 0
12110 The label shown by this code is masked using the image it contains,
12111 giving the appearance that an irregularly-shaped image is being drawn
12112 directly onto the screen.
12114 Masked widgets receive mouse events only on their visible
12117 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
12119 void QWidget::setMask(const QBitmap &bitmap)
12121 setMask(QRegion(bitmap));
12125 \fn void QWidget::clearMask()
12127 Removes any mask set by setMask().
12131 void QWidget::clearMask()
12133 setMask(QRegion());
12136 /*! \fn const QX11Info &QWidget::x11Info() const
12137 Returns information about the configuration of the X display used to display
12140 \warning This function is only available on X11.
12143 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
12144 Returns the X11 Picture handle of the widget for XRender
12145 support. Use of this function is not portable. This function will
12146 return 0 if XRender support is not compiled into Qt, if the
12147 XRender extension is not supported on the X11 display, or if the
12148 handle could not be created.
12151 #ifdef Q_OS_SYMBIAN
12152 void QWidgetPrivate::_q_delayedDestroy(WId winId)
12158 #if QT_MAC_USE_COCOA
12159 void QWidgetPrivate::syncUnifiedMode() {
12160 // The whole purpose of this method is to keep the unifiedToolbar in sync.
12161 // That means making sure we either exchange the drawing methods or we let
12162 // the toolbar know that it does not require to draw the baseline.
12164 // This function makes sense only if this is a top level
12167 OSWindowRef window = qt_mac_window_for(q);
12168 if(changeMethods) {
12169 // Ok, we are in documentMode.
12170 if(originalDrawMethod)
12171 qt_mac_replaceDrawRect(window, this);
12173 if(!originalDrawMethod)
12174 qt_mac_replaceDrawRectOriginal(window, this);
12178 #endif // QT_MAC_USE_COCOA
12182 #include "moc_qwidget.cpp"