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;
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;
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);
376 This function returns the QInputContext for this widget. By
377 default the input context is inherited from the widgets
378 parent. For toplevels it is inherited from QApplication.
380 You can override this and set a special input context for this
381 widget by using the setInputContext() method.
383 \sa setInputContext()
385 QInputContext *QWidget::inputContext()
388 if (!testAttribute(Qt::WA_InputMethodEnabled))
391 return qApp->inputContext();
394 #ifdef QT_KEYPAD_NAVIGATION
395 QPointer<QWidget> QWidgetPrivate::editingWidget;
398 Returns true if this widget currently has edit focus; otherwise false.
400 This feature is only available in Qt for Embedded Linux.
402 \sa setEditFocus(), QApplication::keypadNavigationEnabled()
404 bool QWidget::hasEditFocus() const
406 const QWidget* w = this;
407 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
408 w = w->d_func()->extra->focus_proxy;
409 return QWidgetPrivate::editingWidget == w;
413 \fn void QWidget::setEditFocus(bool enable)
415 If \a enable is true, make this widget have edit focus, in which
416 case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
417 normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
420 This feature is only available in Qt for Embedded Linux and Qt
423 \sa hasEditFocus(), QApplication::keypadNavigationEnabled()
425 void QWidget::setEditFocus(bool on)
428 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
429 f = f->d_func()->extra->focus_proxy;
431 if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
432 QWidgetPrivate::editingWidget->setEditFocus(false);
434 if (on && !f->hasFocus())
437 if ((!on && !QWidgetPrivate::editingWidget)
438 || (on && QWidgetPrivate::editingWidget == f)) {
442 if (!on && QWidgetPrivate::editingWidget == f) {
443 QWidgetPrivate::editingWidget = 0;
444 QEvent event(QEvent::LeaveEditFocus);
445 QApplication::sendEvent(f, &event);
446 QApplication::sendEvent(f->style(), &event);
448 QWidgetPrivate::editingWidget = f;
449 QEvent event(QEvent::EnterEditFocus);
450 QApplication::sendEvent(f, &event);
451 QApplication::sendEvent(f->style(), &event);
457 \property QWidget::autoFillBackground
458 \brief whether the widget background is filled automatically
461 If enabled, this property will cause Qt to fill the background of the
462 widget before invoking the paint event. The color used is defined by the
463 QPalette::Window color role from the widget's \l{QPalette}{palette}.
465 In addition, Windows are always filled with QPalette::Window, unless the
466 WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
468 This property cannot be turned off (i.e., set to false) if a widget's
469 parent has a static gradient for its background.
471 \warning Use this property with caution in conjunction with
472 \l{Qt Style Sheets}. When a widget has a style sheet with a valid
473 background or a border-image, this property is automatically disabled.
475 By default, this property is false.
477 \sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
478 {QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
480 bool QWidget::autoFillBackground() const
483 return d->extra && d->extra->autoFillBackground;
486 void QWidget::setAutoFillBackground(bool enabled)
491 if (d->extra->autoFillBackground == enabled)
494 d->extra->autoFillBackground = enabled;
502 \brief The QWidget class is the base class of all user interface objects.
504 \ingroup basicwidgets
507 The widget is the atom of the user interface: it receives mouse, keyboard
508 and other events from the window system, and paints a representation of
509 itself on the screen. Every widget is rectangular, and they are sorted in a
510 Z-order. A widget is clipped by its parent and by the widgets in front of
513 A widget that is not embedded in a parent widget is called a window.
514 Usually, windows have a frame and a title bar, although it is also possible
515 to create windows without such decoration using suitable
516 \l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
517 subclasses of QDialog are the most common window types.
519 Every widget's constructor accepts one or two standard arguments:
522 \i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
523 (the default), the new widget will be a window. If not, it will be
524 a child of \e parent, and be constrained by \e parent's geometry
525 (unless you specify Qt::Window as window flag).
526 \i \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
527 the default is suitable for almost all widgets, but to get, for
528 example, a window without a window system frame, you must use
532 QWidget has many member functions, but some of them have little direct
533 functionality; for example, QWidget has a font property, but never uses
534 this itself. There are many subclasses which provide real functionality,
535 such as QLabel, QPushButton, QListWidget, and QTabWidget.
538 \section1 Top-Level and Child Widgets
540 A widget without a parent widget is always an independent window (top-level
541 widget). For these widgets, setWindowTitle() and setWindowIcon() set the
542 title bar and icon respectively.
544 Non-window widgets are child widgets, displayed within their parent
545 widgets. Most widgets in Qt are mainly useful as child widgets. For
546 example, it is possible to display a button as a top-level window, but most
547 people prefer to put their buttons inside other widgets, such as QDialog.
549 \image parent-child-widgets.png A parent widget containing various child widgets.
551 The diagram above shows a QGroupBox widget being used to hold various child
552 widgets in a layout provided by QGridLayout. The QLabel child widgets have
553 been outlined to indicate their full sizes.
555 If you want to use a QWidget to hold child widgets you will usually want to
556 add a layout to the parent QWidget. See \l{Layout Management} for more
560 \section1 Composite Widgets
562 When a widget is used as a container to group a number of child widgets, it
563 is known as a composite widget. These can be created by constructing a
564 widget with the required visual properties - a QFrame, for example - and
565 adding child widgets to it, usually managed by a layout. The above diagram
566 shows such a composite widget that was created using \l{Qt Designer}.
568 Composite widgets can also be created by subclassing a standard widget,
569 such as QWidget or QFrame, and adding the necessary layout and child
570 widgets in the constructor of the subclass. Many of the \l{Qt Examples}
571 {examples provided with Qt} use this approach, and it is also covered in
572 the Qt \l{Tutorials}.
575 \section1 Custom Widgets and Painting
577 Since QWidget is a subclass of QPaintDevice, subclasses can be used to
578 display custom content that is composed using a series of painting
579 operations with an instance of the QPainter class. This approach contrasts
580 with the canvas-style approach used by the \l{Graphics View}
581 {Graphics View Framework} where items are added to a scene by the
582 application and are rendered by the framework itself.
584 Each widget performs all painting operations from within its paintEvent()
585 function. This is called whenever the widget needs to be redrawn, either
586 as a result of some external change or when requested by the application.
588 The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
589 can handle paint events.
592 \section1 Size Hints and Size Policies
594 When implementing a new widget, it is almost always useful to reimplement
595 sizeHint() to provide a reasonable default size for the widget and to set
596 the correct size policy with setSizePolicy().
598 By default, composite widgets which do not provide a size hint will be
599 sized according to the space requirements of their child widgets.
601 The size policy lets you supply good default behavior for the layout
602 management system, so that other widgets can contain and manage yours
603 easily. The default size policy indicates that the size hint represents
604 the preferred size of the widget, and this is often good enough for many
607 \note The size of top-level widgets are constrained to 2/3 of the desktop's
608 height and width. You can resize() the widget manually if these bounds are
614 Widgets respond to events that are typically caused by user actions. Qt
615 delivers events to widgets by calling specific event handler functions with
616 instances of QEvent subclasses containing information about each event.
618 If your widget only contains child widgets, you probably do not need to
619 implement any event handlers. If you want to detect a mouse click in a
620 child widget call the child's underMouse() function inside the widget's
623 The \l{widgets/scribble}{Scribble example} implements a wider set of
624 events to handle mouse movement, button presses, and window resizing.
626 You will need to supply the behavior and content for your own widgets, but
627 here is a brief overview of the events that are relevant to QWidget,
628 starting with the most common ones:
631 \i paintEvent() is called whenever the widget needs to be repainted.
632 Every widget displaying custom content must implement it. Painting
633 using a QPainter can only take place in a paintEvent() or a
634 function called by a paintEvent().
635 \i resizeEvent() is called when the widget has been resized.
636 \i mousePressEvent() is called when a mouse button is pressed while
637 the mouse cursor is inside the widget, or when the widget has
638 grabbed the mouse using grabMouse(). Pressing the mouse without
639 releasing it is effectively the same as calling grabMouse().
640 \i mouseReleaseEvent() is called when a mouse button is released. A
641 widget receives mouse release events when it has received the
642 corresponding mouse press event. This means that if the user
643 presses the mouse inside \e your widget, then drags the mouse
644 somewhere else before releasing the mouse button, \e your widget
645 receives the release event. There is one exception: if a popup menu
646 appears while the mouse button is held down, this popup immediately
647 steals the mouse events.
648 \i mouseDoubleClickEvent() is called when the user double-clicks in
649 the widget. If the user double-clicks, the widget receives a mouse
650 press event, a mouse release event and finally this event instead
651 of a second mouse press event. (Some mouse move events may also be
652 received if the mouse is not held steady during this operation.) It
653 is \e{not possible} to distinguish a click from a double-click
654 until the second click arrives. (This is one reason why most GUI
655 books recommend that double-clicks be an extension of
656 single-clicks, rather than trigger a different action.)
659 Widgets that accept keyboard input need to reimplement a few more event
663 \i keyPressEvent() is called whenever a key is pressed, and again when
664 a key has been held down long enough for it to auto-repeat. The
665 \key Tab and \key Shift+Tab keys are only passed to the widget if
666 they are not used by the focus-change mechanisms. To force those
667 keys to be processed by your widget, you must reimplement
669 \i focusInEvent() is called when the widget gains keyboard focus
670 (assuming you have called setFocusPolicy()). Well-behaved widgets
671 indicate that they own the keyboard focus in a clear but discreet
673 \i focusOutEvent() is called when the widget loses keyboard focus.
676 You may be required to also reimplement some of the less common event
680 \i mouseMoveEvent() is called whenever the mouse moves while a mouse
681 button is held down. This can be useful during drag and drop
682 operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
683 you get mouse move events even when no buttons are held down.
684 (See also the \l{Drag and Drop} guide.)
685 \i keyReleaseEvent() is called whenever a key is released and while it
686 is held down (if the key is auto-repeating). In that case, the
687 widget will receive a pair of key release and key press event for
688 every repeat. The \key Tab and \key Shift+Tab keys are only passed
689 to the widget if they are not used by the focus-change mechanisms.
690 To force those keys to be processed by your widget, you must
691 reimplement QWidget::event().
692 \i wheelEvent() is called whenever the user turns the mouse wheel
693 while the widget has the focus.
694 \i enterEvent() is called when the mouse enters the widget's screen
695 space. (This excludes screen space owned by any of the widget's
697 \i leaveEvent() is called when the mouse leaves the widget's screen
698 space. If the mouse enters a child widget it will not cause a
700 \i moveEvent() is called when the widget has been moved relative to
702 \i closeEvent() is called when the user closes the widget (or when
706 There are also some rather obscure events described in the documentation
707 for QEvent::Type. To handle these events, you need to reimplement event()
710 The default implementation of event() handles \key Tab and \key Shift+Tab
711 (to move the keyboard focus), and passes on most of the other events to
712 one of the more specialized handlers above.
714 Events and the mechanism used to deliver them are covered in
715 \l{The Event System}.
717 \section1 Groups of Functions and Properties
720 \header \i Context \i Functions and Properties
722 \row \i Window functions \i
729 \row \i Top-level windows \i
730 \l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
731 \l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
732 \l maximized, showMaximized(), \l fullScreen, showFullScreen(),
735 \row \i Window contents \i
741 \l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
742 \l sizePolicy, sizeHint(), minimumSizeHint(),
743 updateGeometry(), layout(),
744 \l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
746 mapFromGlobal(), mapToGlobal(),
747 mapFromParent(), mapToParent(),
748 \l maximumSize, \l minimumSize, \l sizeIncrement,
749 \l baseSize, setFixedSize()
752 \l visible, isVisibleTo(),
753 \l enabled, isEnabledTo(),
760 \row \i Look and feel \i
767 backgroundRole(), setBackgroundRole(),
768 fontInfo(), fontMetrics().
770 \row \i Keyboard focus functions \i
771 \l focus, \l focusPolicy,
772 setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
773 focusNextChild(), focusPreviousChild().
775 \row \i Mouse and keyboard grabbing \i
776 grabMouse(), releaseMouse(),
777 grabKeyboard(), releaseKeyboard(),
778 mouseGrabber(), keyboardGrabber().
780 \row \i Event handlers \i
784 mouseDoubleClickEvent(),
807 \row \i System functions \i
808 parentWidget(), window(), setParent(), winId(),
811 \row \i Interactive help \i
812 setToolTip(), setWhatsThis()
817 \section1 Widget Style Sheets
819 In addition to the standard widget styles for each platform, widgets can
820 also be styled according to rules specified in a \l{styleSheet}
821 {style sheet}. This feature enables you to customize the appearance of
822 specific widgets to provide visual cues to users about their purpose. For
823 example, a button could be styled in a particular way to indicate that it
824 performs a destructive action.
826 The use of widget style sheets is described in more detail in the
827 \l{Qt Style Sheets} document.
830 \section1 Transparency and Double Buffering
832 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
833 is no need to write double-buffering code in paintEvent() to avoid
836 Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
837 deprecated. Instead, the contents of parent widgets are propagated by
838 default to each of their children as long as Qt::WA_PaintOnScreen is not
839 set. Custom widgets can be written to take advantage of this feature by
840 updating irregular regions (to create non-rectangular child widgets), or
841 painting with colors that have less than full alpha component. The
842 following diagram shows how attributes and properties of a custom widget
843 can be fine-tuned to achieve different effects.
845 \image propagation-custom.png
847 In the above diagram, a semi-transparent rectangular child widget with an
848 area removed is constructed and added to a parent widget (a QLabel showing
849 a pixmap). Then, different properties and widget attributes are set to
850 achieve different effects:
853 \i The left widget has no additional properties or widget attributes
854 set. This default state suits most custom widgets using
855 transparency, are irregularly-shaped, or do not paint over their
856 entire area with an opaque brush.
857 \i The center widget has the \l autoFillBackground property set. This
858 property is used with custom widgets that rely on the widget to
859 supply a default background, and do not paint over their entire
860 area with an opaque brush.
861 \i The right widget has the Qt::WA_OpaquePaintEvent widget attribute
862 set. This indicates that the widget will paint over its entire area
863 with opaque colors. The widget's area will initially be
864 \e{uninitialized}, represented in the diagram with a red diagonal
865 grid pattern that shines through the overpainted area. The
866 Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
867 paint their own specialized contents quickly and do not need a
868 default filled background.
871 To rapidly update custom widgets with simple background colors, such as
872 real-time plotting or graphing widgets, it is better to define a suitable
873 background color (using setBackgroundRole() with the
874 QPalette::Window role), set the \l autoFillBackground property, and only
875 implement the necessary drawing functionality in the widget's paintEvent().
877 To rapidly update custom widgets that constantly paint over their entire
878 areas with opaque content, e.g., video streaming widgets, it is better to
879 set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
880 associated with repainting the widget's background.
882 If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
883 the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
884 attribute takes precedence. Depending on your requirements, you should
885 choose either one of them.
887 Since Qt 4.1, the contents of parent widgets are also propagated to
888 standard Qt widgets. This can lead to some unexpected results if the
889 parent widget is decorated in a non-standard way, as shown in the diagram
892 \image propagation-standard.png
894 The scope for customizing the painting behavior of standard Qt widgets,
895 without resorting to subclassing, is slightly less than that possible for
896 custom widgets. Usually, the desired appearance of a standard widget can be
897 achieved by setting its \l autoFillBackground property.
900 \section1 Creating Translucent Windows
902 Since Qt 4.5, it has been possible to create windows with translucent regions
903 on window systems that support compositing.
905 To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
906 attribute with setAttribute() and ensure that its background is painted with
907 non-opaque colors in the regions you want to be partially transparent.
912 \o X11: This feature relies on the use of an X server that supports ARGB visuals
913 and a compositing window manager.
914 \o Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
915 for the translucency to work.
919 \section1 Native Widgets vs Alien Widgets
921 Introduced in Qt 4.4, alien widgets are widgets unknown to the windowing
922 system. They do not have a native window handle associated with them. This
923 feature significantly speeds up widget painting, resizing, and removes flicker.
925 Should you require the old behavior with native windows, you can choose
926 one of the following options:
929 \i Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
930 \i Set the Qt::AA_NativeWindows attribute on your application. All
931 widgets will be native widgets.
932 \i Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
933 and all of its ancestors will become native (unless
934 Qt::WA_DontCreateNativeAncestors is set).
935 \i Call QWidget::winId to enforce a native window (this implies 3).
936 \i Set the Qt::WA_PaintOnScreen attribute to enforce a native window
940 \sa QEvent, QPainter, QGridLayout, QBoxLayout
944 Since Qt 4.6, Softkeys are usually physical keys on a device that have a corresponding label or
945 other visual representation on the screen that is generally located next to its
946 physical counterpart. They are most often found on mobile phone platforms. In
947 modern touch based user interfaces it is also possible to have softkeys that do
948 not correspond to any physical keys. Softkeys differ from other onscreen labels
949 in that they are contextual.
951 In Qt, contextual softkeys are added to a widget by calling addAction() and
952 passing a \c QAction with a softkey role set on it. When the widget
953 containing the softkey actions has focus, its softkeys should appear in
954 the user interface. Softkeys are discovered by traversing the widget
955 hierarchy so it is possible to define a single set of softkeys that are
956 present at all times by calling addAction() for a given top level widget.
958 On some platforms, this concept overlaps with \c QMenuBar such that if no
959 other softkeys are found and the top level widget is a QMainWindow containing
960 a QMenuBar, the menubar actions may appear on one of the softkeys.
962 Note: Currently softkeys are only supported on the Symbian Platform.
964 \sa addAction(), QAction, QMenuBar
968 QWidgetMapper *QWidgetPrivate::mapper = 0; // widget with wid
969 QWidgetSet *QWidgetPrivate::allWidgets = 0; // widgets with no wid
972 /*****************************************************************************
973 QWidget utility functions
974 *****************************************************************************/
976 QRegion qt_dirtyRegion(QWidget *widget)
981 QWidgetBackingStore *bs = qt_widget_private(widget)->maybeBackingStore();
985 return bs->dirtyRegion(widget);
988 /*****************************************************************************
989 QWidget member functions
990 *****************************************************************************/
995 \i Qt::WA_WState_Created The widget has a valid winId().
996 \i Qt::WA_WState_Visible The widget is currently visible.
997 \i Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
998 become visible unless you call show() on it. Qt::WA_WState_Hidden
999 implies !Qt::WA_WState_Visible.
1000 \i Qt::WA_WState_CompressKeys Compress keyboard events.
1001 \i Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
1002 \i Qt::WA_WState_InPaintEvent Currently processing a paint event.
1003 \i Qt::WA_WState_Reparented The widget has been reparented.
1004 \i Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
1005 \i Qt::WA_WState_DND (Deprecated) The widget supports drag and drop, see setAcceptDrops().
1009 struct QWidgetExceptionCleaner
1011 /* this cleans up when the constructor throws an exception */
1012 static inline void cleanup(QWidget *that, QWidgetPrivate *d)
1014 #ifdef QT_NO_EXCEPTIONS
1018 QWidgetPrivate::allWidgets->remove(that);
1019 if (d->focus_next != that) {
1021 d->focus_next->d_func()->focus_prev = d->focus_prev;
1023 d->focus_prev->d_func()->focus_next = d->focus_next;
1030 Constructs a widget which is a child of \a parent, with widget
1033 If \a parent is 0, the new widget becomes a window. If
1034 \a parent is another widget, this widget becomes a child window
1035 inside \a parent. The new widget is deleted when its \a parent is
1038 The widget flags argument, \a f, is normally 0, but it can be set
1039 to customize the frame of a window (i.e. \a
1040 parent must be 0). To customize the frame, use a value composed
1041 from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
1043 If you add a child widget to an already visible widget you must
1044 explicitly show the child to make it visible.
1046 Note that the X11 version of Qt may not be able to deliver all
1047 combinations of style flags on all systems. This is because on
1048 X11, Qt can only ask the window manager, and the window manager
1049 can override the application's settings. On Windows, Qt can set
1050 whatever flags you want.
1054 QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
1055 : QObject(*new QWidgetPrivate, 0), QPaintDevice()
1058 d_func()->init(parent, f);
1060 QWidgetExceptionCleaner::cleanup(this, d_func());
1068 QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
1069 : QObject(dd, 0), QPaintDevice()
1075 QWidgetExceptionCleaner::cleanup(this, d_func());
1083 int QWidget::devType() const
1085 return QInternal::Widget;
1089 //### w is a "this" ptr, passed as a param because QWorkspace needs special logic
1090 void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
1092 bool customize = (flags & (Qt::CustomizeWindowHint
1093 | Qt::FramelessWindowHint
1094 | Qt::WindowTitleHint
1095 | Qt::WindowSystemMenuHint
1096 | Qt::WindowMinimizeButtonHint
1097 | Qt::WindowMaximizeButtonHint
1098 | Qt::WindowCloseButtonHint
1099 | Qt::WindowContextHelpButtonHint));
1101 uint type = (flags & Qt::WindowType_Mask);
1103 if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
1105 flags |= Qt::Window;
1108 if (flags & Qt::CustomizeWindowHint) {
1109 // modify window flags to make them consistent.
1110 // Only enable this on non-Mac platforms. Since the old way of doing this would
1111 // interpret WindowSystemMenuHint as a close button and we can't change that behavior
1112 // we can't just add this in.
1114 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint)) {
1115 flags |= Qt::WindowSystemMenuHint;
1117 if (flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
1118 | Qt::WindowSystemMenuHint)) {
1120 flags |= Qt::WindowTitleHint;
1121 flags &= ~Qt::FramelessWindowHint;
1123 } else if (customize && !(flags & Qt::FramelessWindowHint)) {
1124 // if any of the window hints that affect the titlebar are set
1125 // and the window is supposed to have frame, we add a titlebar
1126 // and system menu by default.
1127 flags |= Qt::WindowSystemMenuHint;
1128 flags |= Qt::WindowTitleHint;
1131 ; // don't modify window flags if the user explicitly set them.
1132 else if (type == Qt::Dialog || type == Qt::Sheet)
1134 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint;
1136 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1138 else if (type == Qt::Tool)
1139 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
1141 flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint;
1146 void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
1149 if (QApplication::type() == QApplication::Tty)
1150 qFatal("QWidget: Cannot create a QWidget when no GUI is being used");
1152 Q_ASSERT(allWidgets);
1154 allWidgets->insert(q);
1156 QWidget *desktopWidget = 0;
1157 if (parentWidget && parentWidget->windowType() == Qt::Desktop) {
1158 desktopWidget = parentWidget;
1164 #ifndef QT_NO_THREAD
1166 Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
1167 "Widgets must be created in the GUI thread.");
1171 #if defined(Q_WS_X11)
1172 if (desktopWidget) {
1173 // make sure the widget is created on the same screen as the
1174 // programmer specified desktop widget
1175 xinfo = desktopWidget->d_func()->xinfo;
1177 #elif defined(Q_OS_SYMBIAN)
1178 if (desktopWidget) {
1179 symbianScreenNumber = qt_widget_private(desktopWidget)->symbianScreenNumber;
1181 #elif defined(Q_WS_QPA)
1182 if (desktopWidget) {
1183 int screen = desktopWidget->d_func()->topData()->screenIndex;
1184 q->windowHandle()->setScreen(QGuiApplication::screens().value(screen, 0));
1187 Q_UNUSED(desktopWidget);
1190 data.fstrut_dirty = true;
1193 data.widget_attributes = 0;
1194 data.window_flags = f;
1195 data.window_state = 0;
1196 data.focus_policy = 0;
1197 data.context_menu_policy = Qt::DefaultContextMenu;
1198 data.window_modality = Qt::NonModal;
1200 data.sizehint_forced = 0;
1201 data.is_closing = 0;
1203 data.in_set_window_state = 0;
1204 data.in_destructor = false;
1206 // Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
1207 if (f & Qt::MSWindowsOwnDC)
1208 q->setAttribute(Qt::WA_NativeWindow);
1211 // q->setAttribute(Qt::WA_NativeWindow);
1214 q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
1215 adjustQuitOnCloseAttribute();
1217 q->setAttribute(Qt::WA_WState_Hidden);
1219 //give potential windows a bigger "pre-initial" size; create_sys() will give them a new size later
1222 // Don't waste GPU mem for unnecessary large egl surface until resized by application
1223 data.crect = QRect(0,0,1,1);
1225 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,360,640);
1228 data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
1231 focus_next = focus_prev = q;
1233 if ((f & Qt::WindowType_Mask) == Qt::Desktop)
1235 else if (parentWidget)
1236 q->setParent(parentWidget, data.window_flags);
1238 adjustFlags(data.window_flags, q);
1239 resolveLayoutDirection();
1240 // opaque system background?
1241 const QBrush &background = q->palette().brush(QPalette::Window);
1242 setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
1244 data.fnt = QFont(data.fnt, q);
1245 #if defined(Q_WS_X11)
1246 data.fnt.x11SetScreen(xinfo.screen());
1249 q->setAttribute(Qt::WA_PendingMoveEvent);
1250 q->setAttribute(Qt::WA_PendingResizeEvent);
1252 if (++QWidgetPrivate::instanceCounter > QWidgetPrivate::maxInstances)
1253 QWidgetPrivate::maxInstances = QWidgetPrivate::instanceCounter;
1255 if (QApplicationPrivate::app_compile_version < 0x040200
1256 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
1260 QEvent e(QEvent::Create);
1261 QApplication::sendEvent(q, &e);
1262 QApplication::postEvent(q, new QEvent(QEvent::PolishRequest));
1264 extraPaintEngine = 0;
1267 // If we add a child to the unified toolbar, we have to redirect the painting.
1268 if (parentWidget && parentWidget->d_func() && parentWidget->d_func()->isInUnifiedToolbar) {
1269 if (parentWidget->d_func()->unifiedSurface) {
1270 QWidget *toolbar = parentWidget->d_func()->toolbar_ancestor;
1271 parentWidget->d_func()->unifiedSurface->recursiveRedirect(toolbar, toolbar, toolbar->d_func()->toolbar_offset);
1279 void QWidgetPrivate::createRecursively()
1282 q->create(0, true, true);
1283 for (int i = 0; i < children.size(); ++i) {
1284 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1285 if (child && !child->isHidden() && !child->isWindow() && !child->testAttribute(Qt::WA_WState_Created))
1286 child->d_func()->createRecursively();
1294 Creates a new widget window if \a window is 0, otherwise sets the
1295 widget's window to \a window.
1297 Initializes the window (sets the geometry etc.) if \a
1298 initializeWindow is true. If \a initializeWindow is false, no
1299 initialization is performed. This parameter only makes sense if \a
1300 window is a valid window.
1302 Destroys the old window if \a destroyOldWindow is true. If \a
1303 destroyOldWindow is false, you are responsible for destroying the
1304 window yourself (using platform native code).
1306 The QWidget constructor calls create(0,true,true) to create a
1307 window for this widget.
1310 void QWidget::create(WId window, bool initializeWindow, bool destroyOldWindow)
1313 if (testAttribute(Qt::WA_WState_Created) && window == 0 && internalWinId())
1316 if (d->data.in_destructor)
1319 Qt::WindowType type = windowType();
1320 Qt::WindowFlags &flags = data->window_flags;
1322 if ((type == Qt::Widget || type == Qt::SubWindow) && !parentWidget()) {
1324 flags |= Qt::Window;
1327 if (QWidget *parent = parentWidget()) {
1328 if (type & Qt::Window) {
1329 if (!parent->testAttribute(Qt::WA_WState_Created))
1330 parent->createWinId();
1331 } else if (testAttribute(Qt::WA_NativeWindow) && !parent->internalWinId()
1332 && !testAttribute(Qt::WA_DontCreateNativeAncestors)) {
1333 // We're about to create a native child widget that doesn't have a native parent;
1334 // enforce a native handle for the parent unless the Qt::WA_DontCreateNativeAncestors
1335 // attribute is set.
1336 d->createWinId(window);
1337 // Nothing more to do.
1338 Q_ASSERT(testAttribute(Qt::WA_WState_Created));
1339 Q_ASSERT(internalWinId());
1345 static int paintOnScreenEnv = -1;
1346 if (paintOnScreenEnv == -1)
1347 paintOnScreenEnv = qgetenv("QT_ONSCREEN_PAINT").toInt() > 0 ? 1 : 0;
1348 if (paintOnScreenEnv == 1)
1349 setAttribute(Qt::WA_PaintOnScreen);
1351 if (QApplicationPrivate::testAttribute(Qt::AA_NativeWindows))
1352 setAttribute(Qt::WA_NativeWindow);
1355 qDebug() << "QWidget::create:" << this << "parent:" << parentWidget()
1356 << "Alien?" << !testAttribute(Qt::WA_NativeWindow);
1359 #if defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1360 // Unregister the dropsite (if already registered) before we
1361 // re-create the widget with a native window.
1362 if (testAttribute(Qt::WA_WState_Created) && !internalWinId() && testAttribute(Qt::WA_NativeWindow)
1363 && d->extra && d->extra->dropTarget) {
1364 d->registerDropSite(false);
1366 #endif // defined (Q_WS_WIN) && !defined(QT_NO_DRAGANDDROP)
1368 d->updateIsOpaque();
1370 setAttribute(Qt::WA_WState_Created); // set created flag
1371 d->create_sys(window, initializeWindow, destroyOldWindow);
1373 // a real toplevel window needs a backing store
1374 if (isWindow() && windowType() != Qt::Desktop) {
1375 d->topData()->backingStoreTracker.destroy();
1376 if (hasBackingStoreSupport())
1377 d->topData()->backingStoreTracker.create(this);
1382 if (!isWindow() && parentWidget() && parentWidget()->testAttribute(Qt::WA_DropSiteRegistered))
1383 setAttribute(Qt::WA_DropSiteRegistered, true);
1386 extern void qt_eval_init_widget(QWidget *w);
1387 qt_eval_init_widget(this);
1390 // need to force the resting of the icon after changing parents
1391 if (testAttribute(Qt::WA_SetWindowIcon))
1392 d->setWindowIcon_sys(true);
1393 if (isWindow() && !d->topData()->iconText.isEmpty())
1394 d->setWindowIconText_helper(d->topData()->iconText);
1395 if (isWindow() && !d->topData()->caption.isEmpty())
1396 d->setWindowTitle_helper(d->topData()->caption);
1397 if (windowType() != Qt::Desktop) {
1398 d->updateSystemBackground();
1400 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon))
1401 d->setWindowIcon_sys();
1406 Destroys the widget.
1408 All this widget's children are deleted first. The application
1409 exits if this widget is the main widget.
1415 d->data.in_destructor = true;
1417 #if defined (QT_CHECK_STATE)
1418 if (paintingActive())
1419 qWarning("QWidget: %s (%s) deleted while being painted", className(), name());
1422 #ifndef QT_NO_GESTURES
1423 foreach (Qt::GestureType type, d->gestureContext.keys())
1424 ungrabGesture(type);
1427 // force acceptDrops false before winId is destroyed.
1428 d->registerDropSite(false);
1430 #ifndef QT_NO_ACTION
1431 // remove all actions from this widget
1432 for (int i = 0; i < d->actions.size(); ++i) {
1433 QActionPrivate *apriv = d->actions.at(i)->d_func();
1434 apriv->widgets.removeAll(this);
1439 #ifndef QT_NO_SHORTCUT
1440 // Remove all shortcuts grabbed by this
1441 // widget, unless application is closing
1442 if (!QApplicationPrivate::is_app_closing && testAttribute(Qt::WA_GrabbedShortcut))
1443 qApp->d_func()->shortcutMap.removeShortcut(0, this, QKeySequence());
1446 // delete layout while we still are a valid widget
1449 // Remove myself from focus list
1451 Q_ASSERT(d->focus_next->d_func()->focus_prev == this);
1452 Q_ASSERT(d->focus_prev->d_func()->focus_next == this);
1454 if (d->focus_next != this) {
1455 d->focus_next->d_func()->focus_prev = d->focus_prev;
1456 d->focus_prev->d_func()->focus_next = d->focus_next;
1457 d->focus_next = d->focus_prev = 0;
1464 // swallow this problem because we are in a destructor
1467 d->setDirtyOpaqueRegion();
1469 if (isWindow() && isVisible() && internalWinId()) {
1471 d->close_helper(QWidgetPrivate::CloseNoEvent);
1473 // if we're out of memory, at least hide the window.
1477 // and if that also doesn't work, then give up
1482 #if defined(Q_WS_WIN) || defined(Q_WS_X11)|| defined(Q_WS_MAC)
1483 else if (!internalWinId() && isVisible()) {
1484 qApp->d_func()->sendSyntheticEnterLeave(this);
1486 #elif defined(Q_WS_QPA)
1487 else if (isVisible()) {
1488 qApp->d_func()->sendSyntheticEnterLeave(this);
1493 if (d->extra && d->extra->topextra && d->extra->topextra->backingStore) {
1494 // Okay, we are about to destroy the top-level window that owns
1495 // the backing store. Make sure we delete the backing store right away
1496 // before the window handle is invalid. This is important because
1497 // the backing store will delete its window surface, which may or may
1498 // not have a reference to this widget that will be used later to
1499 // notify the window it no longer has a surface.
1500 d->extra->topextra->backingStore.destroy();
1503 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
1504 bs->removeDirtyWidget(this);
1505 if (testAttribute(Qt::WA_StaticContents))
1506 bs->removeStaticWidget(this);
1509 delete d->needsFlush;
1512 // set all QPointers for this object to zero
1514 QObjectPrivate::clearGuards(this);
1516 if (d->declarativeData) {
1517 QAbstractDeclarativeData::destroyed(d->declarativeData, this);
1518 d->declarativeData = 0; // don't activate again in ~QObject
1522 // QCocoaView holds a pointer back to this widget. Clear it now
1523 // to make sure it's not followed later on. The lifetime of the
1524 // QCocoaView might exceed the lifetime of this widget in cases
1525 // where Cocoa itself holds references to it.
1526 extern void qt_mac_clearCocoaViewQWidgetPointers(QWidget *);
1527 qt_mac_clearCocoaViewQWidgetPointers(this);
1530 if (!d->children.isEmpty())
1531 d->deleteChildren();
1533 QApplication::removePostedEvents(this);
1536 destroy(); // platform-dependent cleanup
1538 // if this fails we can't do anything about it but at least we are not allowed to throw.
1540 --QWidgetPrivate::instanceCounter;
1542 if (QWidgetPrivate::allWidgets) // might have been deleted by ~QApplication
1543 QWidgetPrivate::allWidgets->remove(this);
1546 QEvent e(QEvent::Destroy);
1547 QCoreApplication::sendEvent(this, &e);
1548 } QT_CATCH(const std::exception&) {
1549 // if this fails we can't do anything about it but at least we are not allowed to throw.
1553 int QWidgetPrivate::instanceCounter = 0; // Current number of widget instances
1554 int QWidgetPrivate::maxInstances = 0; // Maximum number of widget instances
1556 void QWidgetPrivate::setWinId(WId id) // set widget identifier
1559 // the user might create a widget with Qt::Desktop window
1560 // attribute (or create another QDesktopWidget instance), which
1561 // will have the same windowid (the root window id) as the
1562 // qt_desktopWidget. We should not add the second desktop widget
1564 bool userDesktopWidget = qt_desktopWidget != 0 && qt_desktopWidget != q && q->windowType() == Qt::Desktop;
1565 if (mapper && data.winid && !userDesktopWidget) {
1566 mapper->remove(data.winid);
1569 const WId oldWinId = data.winid;
1572 #if defined(Q_WS_X11)
1573 hd = id; // X11: hd == ident
1575 if (mapper && id && !userDesktopWidget) {
1576 mapper->insert(data.winid, q);
1579 if(oldWinId != id) {
1580 QEvent e(QEvent::WinIdChange);
1581 QCoreApplication::sendEvent(q, &e);
1585 void QWidgetPrivate::createTLExtra()
1589 if (!extra->topextra) {
1590 QTLWExtra* x = extra->topextra = new QTLWExtra;
1593 x->backingStore = 0;
1594 x->sharedPainter = 0;
1595 x->incw = x->inch = 0;
1596 x->basew = x->baseh = 0;
1597 x->frameStrut.setCoords(0, 0, 0, 0);
1598 x->normalGeometry = QRect(0,0,-1,-1);
1601 x->posFromMove = false;
1602 x->sizeAdjusted = false;
1603 x->inTopLevelResize = false;
1604 x->inRepaint = false;
1607 x->wasMaximized = false;
1610 #ifdef QWIDGET_EXTRA_DEBUG
1611 static int count = 0;
1612 qDebug() << "tlextra" << ++count;
1619 Creates the widget extra data.
1622 void QWidgetPrivate::createExtra()
1624 if (!extra) { // if not exists
1625 extra = new QWExtra;
1626 extra->glContext = 0;
1627 extra->topextra = 0;
1628 #ifndef QT_NO_GRAPHICSVIEW
1629 extra->proxyWidget = 0;
1631 #ifndef QT_NO_CURSOR
1636 extra->maxw = QWIDGETSIZE_MAX;
1637 extra->maxh = QWIDGETSIZE_MAX;
1638 extra->customDpiX = 0;
1639 extra->customDpiY = 0;
1640 extra->explicitMinSize = 0;
1641 extra->explicitMaxSize = 0;
1642 extra->autoFillBackground = 0;
1643 extra->nativeChildrenForced = 0;
1644 extra->inRenderWithPainter = 0;
1647 #ifdef QWIDGET_EXTRA_DEBUG
1648 static int count = 0;
1649 qDebug() << "extra" << ++count;
1657 Deletes the widget extra data.
1660 void QWidgetPrivate::deleteExtra()
1662 if (extra) { // if exists
1663 #ifndef QT_NO_CURSOR
1667 #ifndef QT_NO_STYLE_STYLESHEET
1668 // dereference the stylesheet style
1669 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(extra->style))
1672 if (extra->topextra) {
1674 extra->topextra->backingStoreTracker.destroy();
1675 delete extra->topextra->icon;
1676 delete extra->topextra->iconPixmap;
1677 delete extra->topextra->backingStore;
1678 delete extra->topextra;
1681 // extra->xic destroyed in QWidget::destroy()
1687 Returns true if there are widgets above this which overlap with
1688 \a rect, which is in parent's coordinate system (same as crect).
1691 bool QWidgetPrivate::isOverlapped(const QRect &rect) const
1695 const QWidget *w = q;
1700 QWidgetPrivate *pd = w->parentWidget()->d_func();
1702 for (int i = 0; i < pd->children.size(); ++i) {
1703 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1704 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1707 above = (sibling == w);
1711 if (qRectIntersects(sibling->d_func()->effectiveRectFor(sibling->data->crect), r)) {
1712 const QWExtra *siblingExtra = sibling->d_func()->extra;
1713 if (siblingExtra && siblingExtra->hasMask && !sibling->d_func()->graphicsEffect
1714 && !siblingExtra->mask.translated(sibling->data->crect.topLeft()).intersects(r)) {
1720 w = w->parentWidget();
1721 r.translate(pd->data.crect.topLeft());
1726 void QWidgetPrivate::syncBackingStore()
1728 if (paintOnScreen()) {
1731 } else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1736 void QWidgetPrivate::syncBackingStore(const QRegion ®ion)
1738 if (paintOnScreen())
1739 repaint_sys(region);
1740 else if (QWidgetBackingStore *bs = maybeBackingStore()) {
1741 bs->sync(q_func(), region);
1745 void QWidgetPrivate::setUpdatesEnabled_helper(bool enable)
1749 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->updatesEnabled())
1750 return; // nothing we can do
1752 if (enable != q->testAttribute(Qt::WA_UpdatesDisabled))
1753 return; // nothing to do
1755 q->setAttribute(Qt::WA_UpdatesDisabled, !enable);
1759 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceUpdatesDisabled : Qt::WA_UpdatesDisabled;
1760 for (int i = 0; i < children.size(); ++i) {
1761 QWidget *w = qobject_cast<QWidget *>(children.at(i));
1762 if (w && !w->isWindow() && !w->testAttribute(attribute))
1763 w->d_func()->setUpdatesEnabled_helper(enable);
1770 Propagate this widget's palette to all children, except style sheet
1771 widgets, and windows that don't enable window propagation (palettes don't
1772 normally propagate to windows).
1774 void QWidgetPrivate::propagatePaletteChange()
1777 // Propagate a new inherited mask to all children.
1778 #ifndef QT_NO_GRAPHICSVIEW
1779 if (!q->parentWidget() && extra && extra->proxyWidget) {
1780 QGraphicsProxyWidget *p = extra->proxyWidget;
1781 inheritedPaletteResolveMask = p->d_func()->inheritedPaletteResolveMask | p->palette().resolve();
1783 #endif //QT_NO_GRAPHICSVIEW
1784 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
1785 inheritedPaletteResolveMask = 0;
1787 int mask = data.pal.resolve() | inheritedPaletteResolveMask;
1789 QEvent pc(QEvent::PaletteChange);
1790 QApplication::sendEvent(q, &pc);
1791 for (int i = 0; i < children.size(); ++i) {
1792 QWidget *w = qobject_cast<QWidget*>(children.at(i));
1793 if (w && !w->testAttribute(Qt::WA_StyleSheet)
1794 && (!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
1795 QWidgetPrivate *wd = w->d_func();
1796 wd->inheritedPaletteResolveMask = mask;
1797 wd->resolvePalette();
1803 Returns the widget's clipping rectangle.
1805 QRect QWidgetPrivate::clipRect() const
1808 const QWidget * w = q;
1809 if (!w->isVisible())
1811 QRect r = effectiveRectFor(q->rect());
1817 && w->parentWidget()) {
1820 w = w->parentWidget();
1821 r &= QRect(ox, oy, w->width(), w->height());
1827 Returns the widget's clipping region (without siblings).
1829 QRegion QWidgetPrivate::clipRegion() const
1832 if (!q->isVisible())
1834 QRegion r(q->rect());
1835 const QWidget * w = q;
1836 const QWidget *ignoreUpTo;
1842 && w->parentWidget()) {
1846 w = w->parentWidget();
1847 r &= QRegion(ox, oy, w->width(), w->height());
1850 while(w->d_func()->children.at(i++) != static_cast<const QObject *>(ignoreUpTo))
1852 for ( ; i < w->d_func()->children.size(); ++i) {
1853 if(QWidget *sibling = qobject_cast<QWidget *>(w->d_func()->children.at(i))) {
1854 if(sibling->isVisible() && !sibling->isWindow()) {
1855 QRect siblingRect(ox+sibling->x(), oy+sibling->y(),
1856 sibling->width(), sibling->height());
1857 if (qRectIntersects(siblingRect, q->rect()))
1858 r -= QRegion(siblingRect);
1866 #ifndef QT_NO_GRAPHICSEFFECT
1867 void QWidgetPrivate::invalidateGraphicsEffectsRecursively()
1872 if (w->graphicsEffect()) {
1873 QWidgetEffectSourcePrivate *sourced =
1874 static_cast<QWidgetEffectSourcePrivate *>(w->graphicsEffect()->source()->d_func());
1875 if (!sourced->updateDueToGraphicsEffect)
1876 w->graphicsEffect()->source()->d_func()->invalidateCache();
1878 w = w->parentWidget();
1881 #endif //QT_NO_GRAPHICSEFFECT
1883 void QWidgetPrivate::setDirtyOpaqueRegion()
1887 dirtyOpaqueChildren = true;
1889 #ifndef QT_NO_GRAPHICSEFFECT
1890 invalidateGraphicsEffectsRecursively();
1891 #endif //QT_NO_GRAPHICSEFFECT
1896 QWidget *parent = q->parentWidget();
1900 // TODO: instead of setting dirtyflag, manipulate the dirtyregion directly?
1901 QWidgetPrivate *pd = parent->d_func();
1902 if (!pd->dirtyOpaqueChildren)
1903 pd->setDirtyOpaqueRegion();
1906 const QRegion &QWidgetPrivate::getOpaqueChildren() const
1908 if (!dirtyOpaqueChildren)
1909 return opaqueChildren;
1911 QWidgetPrivate *that = const_cast<QWidgetPrivate*>(this);
1912 that->opaqueChildren = QRegion();
1914 for (int i = 0; i < children.size(); ++i) {
1915 QWidget *child = qobject_cast<QWidget *>(children.at(i));
1916 if (!child || !child->isVisible() || child->isWindow())
1919 const QPoint offset = child->geometry().topLeft();
1920 QWidgetPrivate *childd = child->d_func();
1921 QRegion r = childd->isOpaque ? child->rect() : childd->getOpaqueChildren();
1922 if (childd->extra && childd->extra->hasMask)
1923 r &= childd->extra->mask;
1926 r.translate(offset);
1927 that->opaqueChildren += r;
1930 that->opaqueChildren &= q_func()->rect();
1931 that->dirtyOpaqueChildren = false;
1933 return that->opaqueChildren;
1936 void QWidgetPrivate::subtractOpaqueChildren(QRegion &source, const QRect &clipRect) const
1938 if (children.isEmpty() || clipRect.isEmpty())
1941 const QRegion &r = getOpaqueChildren();
1943 source -= (r & clipRect);
1946 //subtract any relatives that are higher up than me --- this is too expensive !!!
1947 void QWidgetPrivate::subtractOpaqueSiblings(QRegion &sourceRegion, bool *hasDirtySiblingsAbove,
1948 bool alsoNonOpaque) const
1951 static int disableSubtractOpaqueSiblings = qgetenv("QT_NO_SUBTRACTOPAQUESIBLINGS").toInt();
1952 if (disableSubtractOpaqueSiblings || q->isWindow())
1956 if (q->d_func()->isInUnifiedToolbar)
1960 QRect clipBoundingRect;
1961 bool dirtyClipBoundingRect = true;
1964 bool dirtyParentClip = true;
1966 QPoint parentOffset = data.crect.topLeft();
1968 const QWidget *w = q;
1973 QWidgetPrivate *pd = w->parentWidget()->d_func();
1974 const int myIndex = pd->children.indexOf(const_cast<QWidget *>(w));
1975 const QRect widgetGeometry = w->d_func()->effectiveRectFor(w->data->crect);
1976 for (int i = myIndex + 1; i < pd->children.size(); ++i) {
1977 QWidget *sibling = qobject_cast<QWidget *>(pd->children.at(i));
1978 if (!sibling || !sibling->isVisible() || sibling->isWindow())
1981 const QRect siblingGeometry = sibling->d_func()->effectiveRectFor(sibling->data->crect);
1982 if (!qRectIntersects(siblingGeometry, widgetGeometry))
1985 if (dirtyClipBoundingRect) {
1986 clipBoundingRect = sourceRegion.boundingRect();
1987 dirtyClipBoundingRect = false;
1990 if (!qRectIntersects(siblingGeometry, clipBoundingRect.translated(parentOffset)))
1993 if (dirtyParentClip) {
1994 parentClip = sourceRegion.translated(parentOffset);
1995 dirtyParentClip = false;
1998 const QPoint siblingPos(sibling->data->crect.topLeft());
1999 const QRect siblingClipRect(sibling->d_func()->clipRect());
2000 QRegion siblingDirty(parentClip);
2001 siblingDirty &= (siblingClipRect.translated(siblingPos));
2002 const bool hasMask = sibling->d_func()->extra && sibling->d_func()->extra->hasMask
2003 && !sibling->d_func()->graphicsEffect;
2005 siblingDirty &= sibling->d_func()->extra->mask.translated(siblingPos);
2006 if (siblingDirty.isEmpty())
2009 if (sibling->d_func()->isOpaque || alsoNonOpaque) {
2011 siblingDirty.translate(-parentOffset);
2012 sourceRegion -= siblingDirty;
2014 sourceRegion -= siblingGeometry.translated(-parentOffset);
2017 if (hasDirtySiblingsAbove)
2018 *hasDirtySiblingsAbove = true;
2019 if (sibling->d_func()->children.isEmpty())
2021 QRegion opaqueSiblingChildren(sibling->d_func()->getOpaqueChildren());
2022 opaqueSiblingChildren.translate(-parentOffset + siblingPos);
2023 sourceRegion -= opaqueSiblingChildren;
2025 if (sourceRegion.isEmpty())
2028 dirtyClipBoundingRect = true;
2029 dirtyParentClip = true;
2032 w = w->parentWidget();
2033 parentOffset += pd->data.crect.topLeft();
2034 dirtyParentClip = true;
2038 void QWidgetPrivate::clipToEffectiveMask(QRegion ®ion) const
2042 const QWidget *w = q;
2045 #ifndef QT_NO_GRAPHICSEFFECT
2046 if (graphicsEffect) {
2047 w = q->parentWidget();
2048 offset -= data.crect.topLeft();
2050 #endif //QT_NO_GRAPHICSEFFECT
2053 const QWidgetPrivate *wd = w->d_func();
2054 if (wd->extra && wd->extra->hasMask)
2055 region &= (w != q) ? wd->extra->mask.translated(offset) : wd->extra->mask;
2058 offset -= wd->data.crect.topLeft();
2059 w = w->parentWidget();
2063 bool QWidgetPrivate::paintOnScreen() const
2065 #if defined(QT_NO_BACKINGSTORE)
2069 if (q->testAttribute(Qt::WA_PaintOnScreen)
2070 || (!q->isWindow() && q->window()->testAttribute(Qt::WA_PaintOnScreen))) {
2074 return !qt_enable_backingstore;
2078 void QWidgetPrivate::updateIsOpaque()
2080 // hw: todo: only needed if opacity actually changed
2081 setDirtyOpaqueRegion();
2083 #ifndef QT_NO_GRAPHICSEFFECT
2084 if (graphicsEffect) {
2085 // ### We should probably add QGraphicsEffect::isOpaque at some point.
2089 #endif //QT_NO_GRAPHICSEFFECT
2093 if (q->testAttribute(Qt::WA_X11OpenGLOverlay)) {
2100 if (q->windowType() == Qt::Dialog && q->testAttribute(Qt::WA_TranslucentBackground)
2101 && S60->avkonComponentsSupportTransparency) {
2107 if (q->testAttribute(Qt::WA_OpaquePaintEvent) || q->testAttribute(Qt::WA_PaintOnScreen)) {
2112 const QPalette &pal = q->palette();
2114 if (q->autoFillBackground()) {
2115 const QBrush &autoFillBrush = pal.brush(q->backgroundRole());
2116 if (autoFillBrush.style() != Qt::NoBrush && autoFillBrush.isOpaque()) {
2122 if (q->isWindow() && !q->testAttribute(Qt::WA_NoSystemBackground)) {
2123 const QBrush &windowBrush = q->palette().brush(QPalette::Window);
2124 if (windowBrush.style() != Qt::NoBrush && windowBrush.isOpaque()) {
2132 void QWidgetPrivate::setOpaque(bool opaque)
2134 if (isOpaque == opaque)
2138 macUpdateIsOpaque();
2141 x11UpdateIsOpaque();
2144 winUpdateIsOpaque();
2147 s60UpdateIsOpaque();
2151 void QWidgetPrivate::updateIsTranslucent()
2154 macUpdateIsOpaque();
2157 x11UpdateIsOpaque();
2160 winUpdateIsOpaque();
2163 s60UpdateIsOpaque();
2167 static inline void fillRegion(QPainter *painter, const QRegion &rgn, const QBrush &brush)
2171 if (brush.style() == Qt::TexturePattern) {
2173 // Optimize pattern filling on mac by using HITheme directly
2174 // when filling with the standard widget background.
2175 // Defined in qmacstyle_mac.cpp
2176 extern void qt_mac_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2177 qt_mac_fill_background(painter, rgn, brush);
2179 #if !defined(QT_NO_STYLE_S60)
2180 // Defined in qs60style.cpp
2181 extern bool qt_s60_fill_background(QPainter *painter, const QRegion &rgn, const QBrush &brush);
2182 if (!qt_s60_fill_background(painter, rgn, brush))
2183 #endif // !defined(QT_NO_STYLE_S60)
2185 const QRect rect(rgn.boundingRect());
2186 painter->setClipRegion(rgn);
2187 painter->drawTiledPixmap(rect, brush.texture(), rect.topLeft());
2191 } else if (brush.gradient()
2192 && brush.gradient()->coordinateMode() == QGradient::ObjectBoundingMode) {
2194 painter->setClipRegion(rgn);
2195 painter->fillRect(0, 0, painter->device()->width(), painter->device()->height(), brush);
2198 const QVector<QRect> &rects = rgn.rects();
2199 for (int i = 0; i < rects.size(); ++i)
2200 painter->fillRect(rects.at(i), brush);
2204 void QWidgetPrivate::paintBackground(QPainter *painter, const QRegion &rgn, int flags) const
2208 #ifndef QT_NO_SCROLLAREA
2209 bool resetBrushOrigin = false;
2210 QPointF oldBrushOrigin;
2211 //If we are painting the viewport of a scrollarea, we must apply an offset to the brush in case we are drawing a texture
2212 QAbstractScrollArea *scrollArea = qobject_cast<QAbstractScrollArea *>(parent);
2213 if (scrollArea && scrollArea->viewport() == q) {
2214 QObjectData *scrollPrivate = static_cast<QWidget *>(scrollArea)->d_ptr.data();
2215 QAbstractScrollAreaPrivate *priv = static_cast<QAbstractScrollAreaPrivate *>(scrollPrivate);
2216 oldBrushOrigin = painter->brushOrigin();
2217 resetBrushOrigin = true;
2218 painter->setBrushOrigin(-priv->contentsOffset());
2221 #endif // QT_NO_SCROLLAREA
2223 const QBrush autoFillBrush = q->palette().brush(q->backgroundRole());
2225 if ((flags & DrawAsRoot) && !(q->autoFillBackground() && autoFillBrush.isOpaque())) {
2226 const QBrush bg = q->palette().brush(QPalette::Window);
2227 fillRegion(painter, rgn, bg);
2230 if (q->autoFillBackground())
2231 fillRegion(painter, rgn, autoFillBrush);
2233 if (q->testAttribute(Qt::WA_StyledBackground)) {
2234 painter->setClipRegion(rgn);
2237 q->style()->drawPrimitive(QStyle::PE_Widget, &opt, painter, q);
2240 #ifndef QT_NO_SCROLLAREA
2241 if (resetBrushOrigin)
2242 painter->setBrushOrigin(oldBrushOrigin);
2243 #endif // QT_NO_SCROLLAREA
2248 This function is called when a widget is hidden or destroyed.
2249 It resets some application global pointers that should only refer active,
2254 extern QPointer<QWidget> qt_button_down;
2256 extern QWidget *qt_button_down;
2259 void QWidgetPrivate::deactivateWidgetCleanup()
2262 // If this was the active application window, reset it
2263 if (QApplication::activeWindow() == q)
2264 QApplication::setActiveWindow(0);
2265 // If the is the active mouse press widget, reset it
2266 if (q == qt_button_down)
2272 Returns a pointer to the widget with window identifer/handle \a
2275 The window identifier type depends on the underlying window
2276 system, see \c qwindowdefs.h for the actual definition. If there
2277 is no widget with this identifier, 0 is returned.
2280 QWidget *QWidget::find(WId id)
2282 return QWidgetPrivate::mapper ? QWidgetPrivate::mapper->value(id, 0) : 0;
2288 \fn WId QWidget::internalWinId() const
2290 Returns the window system identifier of the widget, or 0 if the widget is not created yet.
2295 \fn WId QWidget::winId() const
2297 Returns the window system identifier of the widget.
2299 Portable in principle, but if you use it you are probably about to
2300 do something non-portable. Be careful.
2302 If a widget is non-native (alien) and winId() is invoked on it, that widget
2303 will be provided a native handle.
2305 On Mac OS X, the type returned depends on which framework Qt was linked
2306 against. If Qt is using Carbon, the {WId} is actually an HIViewRef. If Qt
2307 is using Cocoa, {WId} is a pointer to an NSView.
2309 This value may change at run-time. An event with type QEvent::WinIdChange
2310 will be sent to the widget following a change in window system identifier.
2314 WId QWidget::winId() const
2316 if (!testAttribute(Qt::WA_WState_Created) || !internalWinId()) {
2318 qDebug() << "QWidget::winId: creating native window for" << this;
2320 QWidget *that = const_cast<QWidget*>(this);
2321 that->setAttribute(Qt::WA_NativeWindow);
2322 that->d_func()->createWinId();
2323 return that->data->winid;
2329 void QWidgetPrivate::createWinId(WId winid)
2334 qDebug() << "QWidgetPrivate::createWinId for" << q << winid;
2336 const bool forceNativeWindow = q->testAttribute(Qt::WA_NativeWindow);
2337 if (!q->testAttribute(Qt::WA_WState_Created) || (forceNativeWindow && !q->internalWinId())) {
2338 if (!q->isWindow()) {
2339 QWidget *parent = q->parentWidget();
2340 QWidgetPrivate *pd = parent->d_func();
2341 if (forceNativeWindow && !q->testAttribute(Qt::WA_DontCreateNativeAncestors))
2342 parent->setAttribute(Qt::WA_NativeWindow);
2343 if (!parent->internalWinId()) {
2347 for (int i = 0; i < pd->children.size(); ++i) {
2348 QWidget *w = qobject_cast<QWidget *>(pd->children.at(i));
2349 if (w && !w->isWindow() && (!w->testAttribute(Qt::WA_WState_Created)
2350 || (!w->internalWinId() && w->testAttribute(Qt::WA_NativeWindow)))) {
2355 // if the window has already been created, we
2356 // need to raise it to its proper stacking position
2371 Ensures that the widget has a window system identifier, i.e. that it is known to the windowing system.
2375 void QWidget::createWinId()
2379 qDebug() << "QWidget::createWinId" << this;
2381 // qWarning("QWidget::createWinId is obsolete, please fix your code.");
2388 Returns the effective window system identifier of the widget, i.e. the
2389 native parent's window system identifier.
2391 If the widget is native, this function returns the native widget ID.
2392 Otherwise, the window ID of the first native parent widget, i.e., the
2393 top-level widget that contains this widget, is returned.
2395 \note We recommend that you do not store this value as it is likely to
2398 \sa nativeParentWidget()
2400 WId QWidget::effectiveWinId() const
2402 WId id = internalWinId();
2403 if (id || !testAttribute(Qt::WA_WState_Created))
2405 QWidget *realParent = nativeParentWidget();
2406 if (!realParent && d_func()->inSetParent) {
2407 // In transitional state. This is really just a workaround. The real problem
2408 // is that QWidgetPrivate::setParent_sys (platform specific code) first sets
2409 // the window id to 0 (setWinId(0)) before it sets the Qt::WA_WState_Created
2410 // attribute to false. The correct way is to do it the other way around, and
2411 // in that case the Qt::WA_WState_Created logic above will kick in and
2412 // return 0 whenever the widget is in a transitional state. However, changing
2413 // the original logic for all platforms is far more intrusive and might
2414 // break existing applications.
2415 // Note: The widget can only be in a transitional state when changing its
2416 // parent -- everything else is an internal error -- hence explicitly checking
2417 // against 'inSetParent' rather than doing an unconditional return whenever
2418 // 'realParent' is 0 (which may cause strange artifacts and headache later).
2421 // This widget *must* have a native parent widget.
2422 Q_ASSERT(realParent);
2423 Q_ASSERT(realParent->internalWinId());
2424 return realParent->internalWinId();
2427 #ifndef QT_NO_STYLE_STYLESHEET
2430 \property QWidget::styleSheet
2431 \brief the widget's style sheet
2434 The style sheet contains a textual description of customizations to the
2435 widget's style, as described in the \l{Qt Style Sheets} document.
2437 Since Qt 4.5, Qt style sheets fully supports Mac OS X.
2439 \warning Qt style sheets are currently not supported for custom QStyle
2440 subclasses. We plan to address this in some future release.
2442 \sa setStyle(), QApplication::styleSheet, {Qt Style Sheets}
2444 QString QWidget::styleSheet() const
2449 return d->extra->styleSheet;
2452 void QWidget::setStyleSheet(const QString& styleSheet)
2457 QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(d->extra->style);
2458 d->extra->styleSheet = styleSheet;
2459 if (styleSheet.isEmpty()) { // stylesheet removed
2467 if (proxy) { // style sheet update
2468 proxy->repolish(this);
2472 if (testAttribute(Qt::WA_SetStyle)) {
2473 d->setStyle_helper(new QStyleSheetStyle(d->extra->style), true);
2475 d->setStyle_helper(new QStyleSheetStyle(0), true);
2479 #endif // QT_NO_STYLE_STYLESHEET
2482 \sa QWidget::setStyle(), QApplication::setStyle(), QApplication::style()
2485 QStyle *QWidget::style() const
2489 if (d->extra && d->extra->style)
2490 return d->extra->style;
2491 return QApplication::style();
2495 Sets the widget's GUI style to \a style. The ownership of the style
2496 object is not transferred.
2498 If no style is set, the widget uses the application's style,
2499 QApplication::style() instead.
2501 Setting a widget's style has no effect on existing or future child
2504 \warning This function is particularly useful for demonstration
2505 purposes, where you want to show Qt's styling capabilities. Real
2506 applications should avoid it and use one consistent GUI style
2509 \warning Qt style sheets are currently not supported for custom QStyle
2510 subclasses. We plan to address this in some future release.
2512 \sa style(), QStyle, QApplication::style(), QApplication::setStyle()
2515 void QWidget::setStyle(QStyle *style)
2518 setAttribute(Qt::WA_SetStyle, style != 0);
2520 #ifndef QT_NO_STYLE_STYLESHEET
2521 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(style)) {
2522 //if for some reason someone try to set a QStyleSheetStyle, ref it
2523 //(this may happen for exemple in QButtonDialogBox which propagates its style)
2525 d->setStyle_helper(style, false);
2526 } else if (qobject_cast<QStyleSheetStyle *>(d->extra->style) || !qApp->styleSheet().isEmpty()) {
2527 // if we have an application stylesheet or have a proxy already, propagate
2528 d->setStyle_helper(new QStyleSheetStyle(style), true);
2531 d->setStyle_helper(style, false);
2534 void QWidgetPrivate::setStyle_helper(QStyle *newStyle, bool propagate, bool
2541 QStyle *oldStyle = q->style();
2542 #ifndef QT_NO_STYLE_STYLESHEET
2543 QWeakPointer<QStyle> origStyle;
2547 // the metalhack boolean allows Qt/Mac to do a proper re-polish depending
2548 // on how the Qt::WA_MacBrushedMetal attribute is set. It is only ever
2549 // set when changing that attribute and passes the widget's CURRENT style.
2550 // therefore no need to do a reassignment.
2556 #ifndef QT_NO_STYLE_STYLESHEET
2557 origStyle = extra->style.data();
2559 extra->style = newStyle;
2563 if (q->windowType() != Qt::Desktop) {
2565 oldStyle->unpolish(q);
2568 macUpdateMetalAttribute();
2570 q->style()->polish(q);
2572 } else if (metalHack) {
2573 macUpdateMetalAttribute();
2579 for (int i = 0; i < children.size(); ++i) {
2580 QWidget *c = qobject_cast<QWidget*>(children.at(i));
2582 c->d_func()->inheritStyle();
2586 #ifndef QT_NO_STYLE_STYLESHEET
2587 if (!qobject_cast<QStyleSheetStyle*>(newStyle)) {
2588 if (const QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(origStyle.data())) {
2589 cssStyle->clearWidgetFont(q);
2594 QEvent e(QEvent::StyleChange);
2595 QApplication::sendEvent(q, &e);
2597 #ifndef QT_NO_STYLE_STYLESHEET
2598 // dereference the old stylesheet style
2599 if (QStyleSheetStyle *proxy = qobject_cast<QStyleSheetStyle *>(origStyle.data()))
2604 // Inherits style from the current parent and propagates it as necessary
2605 void QWidgetPrivate::inheritStyle()
2607 #ifndef QT_NO_STYLE_STYLESHEET
2610 QStyleSheetStyle *proxy = extra ? qobject_cast<QStyleSheetStyle *>(extra->style) : 0;
2612 if (!q->styleSheet().isEmpty()) {
2618 QStyle *origStyle = proxy ? proxy->base : (extra ? (QStyle*)extra->style : 0);
2619 QWidget *parent = q->parentWidget();
2620 QStyle *parentStyle = (parent && parent->d_func()->extra) ? (QStyle*)parent->d_func()->extra->style : 0;
2621 // If we have stylesheet on app or parent has stylesheet style, we need
2622 // to be running a proxy
2623 if (!qApp->styleSheet().isEmpty() || qobject_cast<QStyleSheetStyle *>(parentStyle)) {
2624 QStyle *newStyle = parentStyle;
2625 if (q->testAttribute(Qt::WA_SetStyle))
2626 newStyle = new QStyleSheetStyle(origStyle);
2627 else if (QStyleSheetStyle *newProxy = qobject_cast<QStyleSheetStyle *>(parentStyle))
2630 setStyle_helper(newStyle, true);
2634 // So, we have no stylesheet on parent/app and we have an empty stylesheet
2635 // we just need our original style back
2636 if (origStyle == (extra ? (QStyle*)extra->style : 0)) // is it any different?
2639 // We could have inherited the proxy from our parent (which has a custom style)
2640 // In such a case we need to start following the application style (i.e revert
2641 // the propagation behavior of QStyleSheetStyle)
2642 if (!q->testAttribute(Qt::WA_SetStyle))
2645 setStyle_helper(origStyle, true);
2646 #endif // QT_NO_STYLE_STYLESHEET
2651 \fn bool QWidget::isWindow() const
2653 Returns true if the widget is an independent window, otherwise
2656 A window is a widget that isn't visually the child of any other
2657 widget and that usually has a frame and a
2658 \l{QWidget::setWindowTitle()}{window title}.
2660 A window can have a \l{QWidget::parentWidget()}{parent widget}.
2661 It will then be grouped with its parent and deleted when the
2662 parent is deleted, minimized when the parent is minimized etc. If
2663 supported by the window manager, it will also have a common
2664 taskbar entry with its parent.
2666 QDialog and QMainWindow widgets are by default windows, even if a
2667 parent widget is specified in the constructor. This behavior is
2668 specified by the Qt::Window flag.
2670 \sa window(), isModal(), parentWidget()
2674 \property QWidget::modal
2675 \brief whether the widget is a modal widget
2677 This property only makes sense for windows. A modal widget
2678 prevents widgets in all other windows from getting any input.
2680 By default, this property is false.
2682 \sa isWindow(), windowModality, QDialog
2686 \property QWidget::windowModality
2687 \brief which windows are blocked by the modal widget
2690 This property only makes sense for windows. A modal widget
2691 prevents widgets in other windows from getting input. The value of
2692 this property controls which windows are blocked when the widget
2693 is visible. Changing this property while the window is visible has
2694 no effect; you must hide() the widget first, then show() it again.
2696 By default, this property is Qt::NonModal.
2698 \sa isWindow(), QWidget::modal, QDialog
2701 Qt::WindowModality QWidget::windowModality() const
2703 return static_cast<Qt::WindowModality>(data->window_modality);
2706 void QWidget::setWindowModality(Qt::WindowModality windowModality)
2708 data->window_modality = windowModality;
2709 // setModal_sys() will be called by setAttribute()
2710 setAttribute(Qt::WA_ShowModal, (data->window_modality != Qt::NonModal));
2711 setAttribute(Qt::WA_SetWindowModality, true);
2715 \fn bool QWidget::underMouse() const
2717 Returns true if the widget is under the mouse cursor; otherwise
2720 This value is not updated properly during drag and drop
2723 \sa enterEvent(), leaveEvent()
2727 \property QWidget::minimized
2728 \brief whether this widget is minimized (iconified)
2730 This property is only relevant for windows.
2732 By default, this property is false.
2734 \sa showMinimized(), visible, show(), hide(), showNormal(), maximized
2736 bool QWidget::isMinimized() const
2737 { return data->window_state & Qt::WindowMinimized; }
2740 Shows the widget minimized, as an icon.
2742 Calling this function only affects \l{isWindow()}{windows}.
2744 \sa showNormal(), showMaximized(), show(), hide(), isVisible(),
2747 void QWidget::showMinimized()
2749 bool isMin = isMinimized();
2750 if (isMin && isVisible())
2756 setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
2761 \property QWidget::maximized
2762 \brief whether this widget is maximized
2764 This property is only relevant for windows.
2766 \note Due to limitations on some window systems, this does not always
2767 report the expected results (e.g., if the user on X11 maximizes the
2768 window via the window manager, Qt has no way of distinguishing this
2769 from any other resize). This is expected to improve as window manager
2772 By default, this property is false.
2774 \sa windowState(), showMaximized(), visible, show(), hide(), showNormal(), minimized
2776 bool QWidget::isMaximized() const
2777 { return data->window_state & Qt::WindowMaximized; }
2782 Returns the current window state. The window state is a OR'ed
2783 combination of Qt::WindowState: Qt::WindowMinimized,
2784 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2786 \sa Qt::WindowState setWindowState()
2788 Qt::WindowStates QWidget::windowState() const
2790 return Qt::WindowStates(data->window_state);
2795 The function sets the window state on child widgets similar to
2796 setWindowState(). The difference is that the window state changed
2797 event has the isOverride() flag set. It exists mainly to keep
2798 Q3Workspace working.
2800 void QWidget::overrideWindowState(Qt::WindowStates newstate)
2802 QWindowStateChangeEvent e(Qt::WindowStates(data->window_state), true);
2803 data->window_state = newstate;
2804 QApplication::sendEvent(this, &e);
2808 \fn void QWidget::setWindowState(Qt::WindowStates windowState)
2810 Sets the window state to \a windowState. The window state is a OR'ed
2811 combination of Qt::WindowState: Qt::WindowMinimized,
2812 Qt::WindowMaximized, Qt::WindowFullScreen, and Qt::WindowActive.
2814 If the window is not visible (i.e. isVisible() returns false), the
2815 window state will take effect when show() is called. For visible
2816 windows, the change is immediate. For example, to toggle between
2817 full-screen and normal mode, use the following code:
2819 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 0
2821 In order to restore and activate a minimized window (while
2822 preserving its maximized and/or full-screen state), use the following:
2824 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 1
2826 Calling this function will hide the widget. You must call show() to make
2827 the widget visible again.
2829 \note On some window systems Qt::WindowActive is not immediate, and may be
2830 ignored in certain cases.
2832 When the window state changes, the widget receives a changeEvent()
2833 of type QEvent::WindowStateChange.
2835 \sa Qt::WindowState windowState()
2839 \property QWidget::fullScreen
2840 \brief whether the widget is shown in full screen mode
2842 A widget in full screen mode occupies the whole screen area and does not
2843 display window decorations, such as a title bar.
2845 By default, this property is false.
2847 \sa windowState(), minimized, maximized
2849 bool QWidget::isFullScreen() const
2850 { return data->window_state & Qt::WindowFullScreen; }
2853 Shows the widget in full-screen mode.
2855 Calling this function only affects \l{isWindow()}{windows}.
2857 To return from full-screen mode, call showNormal().
2859 Full-screen mode works fine under Windows, but has certain
2860 problems under X. These problems are due to limitations of the
2861 ICCCM protocol that specifies the communication between X11
2862 clients and the window manager. ICCCM simply does not understand
2863 the concept of non-decorated full-screen windows. Therefore, the
2864 best we can do is to request a borderless window and place and
2865 resize it to fill the entire screen. Depending on the window
2866 manager, this may or may not work. The borderless window is
2867 requested using MOTIF hints, which are at least partially
2868 supported by virtually all modern window managers.
2870 An alternative would be to bypass the window manager entirely and
2871 create a window with the Qt::X11BypassWindowManagerHint flag. This
2872 has other severe problems though, like totally broken keyboard focus
2873 and very strange effects on desktop changes or when the user raises
2876 X11 window managers that follow modern post-ICCCM specifications
2877 support full-screen mode properly.
2879 \sa showNormal(), showMaximized(), show(), hide(), isVisible()
2881 void QWidget::showFullScreen()
2884 // If the unified toolbar is enabled, we have to disable it before going fullscreen.
2885 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2886 if (mainWindow && mainWindow->unifiedTitleAndToolBarOnMac()) {
2887 mainWindow->setUnifiedTitleAndToolBarOnMac(false);
2888 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2889 mainLayout->activateUnifiedToolbarAfterFullScreen = true;
2894 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowMaximized))
2895 | Qt::WindowFullScreen);
2901 Shows the widget maximized.
2903 Calling this function only affects \l{isWindow()}{windows}.
2905 On X11, this function may not work properly with certain window
2906 managers. See the \l{Window Geometry} documentation for an explanation.
2908 \sa setWindowState(), showNormal(), showMinimized(), show(), hide(), isVisible()
2910 void QWidget::showMaximized()
2914 setWindowState((windowState() & ~(Qt::WindowMinimized | Qt::WindowFullScreen))
2915 | Qt::WindowMaximized);
2917 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2918 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2921 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2922 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2923 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2924 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2932 Restores the widget after it has been maximized or minimized.
2934 Calling this function only affects \l{isWindow()}{windows}.
2936 \sa setWindowState(), showMinimized(), showMaximized(), show(), hide(), isVisible()
2938 void QWidget::showNormal()
2942 setWindowState(windowState() & ~(Qt::WindowMinimized
2943 | Qt::WindowMaximized
2944 | Qt::WindowFullScreen));
2946 // If the unified toolbar was enabled before going fullscreen, we have to enable it back.
2947 QMainWindow *mainWindow = qobject_cast<QMainWindow*>(this);
2950 QMainWindowLayout *mainLayout = qobject_cast<QMainWindowLayout*>(mainWindow->layout());
2951 if (mainLayout->activateUnifiedToolbarAfterFullScreen) {
2952 mainWindow->setUnifiedTitleAndToolBarOnMac(true);
2953 mainLayout->activateUnifiedToolbarAfterFullScreen = false;
2961 Returns true if this widget would become enabled if \a ancestor is
2962 enabled; otherwise returns false.
2966 This is the case if neither the widget itself nor every parent up
2967 to but excluding \a ancestor has been explicitly disabled.
2969 isEnabledTo(0) is equivalent to isEnabled().
2971 \sa setEnabled() enabled
2974 bool QWidget::isEnabledTo(QWidget* ancestor) const
2976 const QWidget * w = this;
2977 while (!w->testAttribute(Qt::WA_ForceDisabled)
2979 && w->parentWidget()
2980 && w->parentWidget() != ancestor)
2981 w = w->parentWidget();
2982 return !w->testAttribute(Qt::WA_ForceDisabled);
2985 #ifndef QT_NO_ACTION
2987 Appends the action \a action to this widget's list of actions.
2989 All QWidgets have a list of \l{QAction}s, however they can be
2990 represented graphically in many different ways. The default use of
2991 the QAction list (as returned by actions()) is to create a context
2994 A QWidget should only have one of each action and adding an action
2995 it already has will not cause the same action to be in the widget twice.
2997 The ownership of \a action is not transferred to this QWidget.
2999 \sa removeAction(), insertAction(), actions(), QMenu
3001 void QWidget::addAction(QAction *action)
3003 insertAction(0, action);
3007 Appends the actions \a actions to this widget's list of actions.
3009 \sa removeAction(), QMenu, addAction()
3011 void QWidget::addActions(QList<QAction*> actions)
3013 for(int i = 0; i < actions.count(); i++)
3014 insertAction(0, actions.at(i));
3018 Inserts the action \a action to this widget's list of actions,
3019 before the action \a before. It appends the action if \a before is 0 or
3020 \a before is not a valid action for this widget.
3022 A QWidget should only have one of each action.
3024 \sa removeAction(), addAction(), QMenu, contextMenuPolicy, actions()
3026 void QWidget::insertAction(QAction *before, QAction *action)
3029 qWarning("QWidget::insertAction: Attempt to insert null action");
3034 if(d->actions.contains(action))
3035 removeAction(action);
3037 int pos = d->actions.indexOf(before);
3040 pos = d->actions.size();
3042 d->actions.insert(pos, action);
3044 QActionPrivate *apriv = action->d_func();
3045 apriv->widgets.append(this);
3047 QActionEvent e(QEvent::ActionAdded, action, before);
3048 QApplication::sendEvent(this, &e);
3052 Inserts the actions \a actions to this widget's list of actions,
3053 before the action \a before. It appends the action if \a before is 0 or
3054 \a before is not a valid action for this widget.
3056 A QWidget can have at most one of each action.
3058 \sa removeAction(), QMenu, insertAction(), contextMenuPolicy
3060 void QWidget::insertActions(QAction *before, QList<QAction*> actions)
3062 for(int i = 0; i < actions.count(); ++i)
3063 insertAction(before, actions.at(i));
3067 Removes the action \a action from this widget's list of actions.
3068 \sa insertAction(), actions(), insertAction()
3070 void QWidget::removeAction(QAction *action)
3077 QActionPrivate *apriv = action->d_func();
3078 apriv->widgets.removeAll(this);
3080 if (d->actions.removeAll(action)) {
3081 QActionEvent e(QEvent::ActionRemoved, action);
3082 QApplication::sendEvent(this, &e);
3087 Returns the (possibly empty) list of this widget's actions.
3089 \sa contextMenuPolicy, insertAction(), removeAction()
3091 QList<QAction*> QWidget::actions() const
3096 #endif // QT_NO_ACTION
3099 \fn bool QWidget::isEnabledToTLW() const
3102 This function is deprecated. It is equivalent to isEnabled()
3106 \property QWidget::enabled
3107 \brief whether the widget is enabled
3109 An enabled widget handles keyboard and mouse events; a disabled
3112 Some widgets display themselves differently when they are
3113 disabled. For example a button might draw its label grayed out. If
3114 your widget needs to know when it becomes enabled or disabled, you
3115 can use the changeEvent() with type QEvent::EnabledChange.
3117 Disabling a widget implicitly disables all its children. Enabling
3118 respectively enables all child widgets unless they have been
3119 explicitly disabled.
3121 By default, this property is true.
3123 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3125 void QWidget::setEnabled(bool enable)
3128 setAttribute(Qt::WA_ForceDisabled, !enable);
3129 d->setEnabled_helper(enable);
3132 void QWidgetPrivate::setEnabled_helper(bool enable)
3136 if (enable && !q->isWindow() && q->parentWidget() && !q->parentWidget()->isEnabled())
3137 return; // nothing we can do
3139 if (enable != q->testAttribute(Qt::WA_Disabled))
3140 return; // nothing to do
3142 q->setAttribute(Qt::WA_Disabled, !enable);
3143 updateSystemBackground();
3145 if (!enable && q->window()->focusWidget() == q) {
3146 bool parentIsEnabled = (!q->parentWidget() || q->parentWidget()->isEnabled());
3147 if (!parentIsEnabled || !q->focusNextChild())
3151 Qt::WidgetAttribute attribute = enable ? Qt::WA_ForceDisabled : Qt::WA_Disabled;
3152 for (int i = 0; i < children.size(); ++i) {
3153 QWidget *w = qobject_cast<QWidget *>(children.at(i));
3154 if (w && !w->testAttribute(attribute))
3155 w->d_func()->setEnabled_helper(enable);
3157 #if defined(Q_WS_X11)
3158 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3159 // enforce the windows behavior of clearing the cursor on
3161 qt_x11_enforce_cursor(q);
3163 #elif defined(Q_WS_QPA)
3164 if (q->testAttribute(Qt::WA_SetCursor) || q->isWindow()) {
3165 // enforce the windows behavior of clearing the cursor on
3167 qt_qpa_set_cursor(q, false);
3170 #if defined(Q_WS_MAC)
3171 setEnabled_helper_sys(enable);
3174 if (q->testAttribute(Qt::WA_InputMethodEnabled) && q->hasFocus()) {
3175 QWidget *focusWidget = effectiveFocusWidget();
3178 if (focusWidget->testAttribute(Qt::WA_InputMethodEnabled))
3179 qApp->inputPanel()->setInputItem(focusWidget);
3181 qApp->inputPanel()->commit();
3182 qApp->inputPanel()->setInputItem(0);
3186 QEvent e(QEvent::EnabledChange);
3187 QApplication::sendEvent(q, &e);
3191 \property QWidget::acceptDrops
3192 \brief whether drop events are enabled for this widget
3194 Setting this property to true announces to the system that this
3195 widget \e may be able to accept drop events.
3197 If the widget is the desktop (windowType() == Qt::Desktop), this may
3198 fail if another application is using the desktop; you can call
3199 acceptDrops() to test if this occurs.
3201 \warning Do not modify this property in a drag and drop event handler.
3203 By default, this property is false.
3207 bool QWidget::acceptDrops() const
3209 return testAttribute(Qt::WA_AcceptDrops);
3212 void QWidget::setAcceptDrops(bool on)
3214 setAttribute(Qt::WA_AcceptDrops, on);
3220 Disables widget input events if \a disable is true; otherwise
3221 enables input events.
3223 See the \l enabled documentation for more information.
3225 \sa isEnabledTo(), QKeyEvent, QMouseEvent, changeEvent()
3227 void QWidget::setDisabled(bool disable)
3229 setEnabled(!disable);
3233 \property QWidget::frameGeometry
3234 \brief geometry of the widget relative to its parent including any
3237 See the \l{Window Geometry} documentation for an overview of geometry
3238 issues with windows.
3240 By default, this property contains a value that depends on the user's
3241 platform and screen geometry.
3243 \sa geometry() x() y() pos()
3245 QRect QWidget::frameGeometry() const
3248 if (isWindow() && ! (windowType() == Qt::Popup)) {
3249 QRect fs = d->frameStrut();
3250 return QRect(data->crect.x() - fs.left(),
3251 data->crect.y() - fs.top(),
3252 data->crect.width() + fs.left() + fs.right(),
3253 data->crect.height() + fs.top() + fs.bottom());
3259 \property QWidget::x
3261 \brief the x coordinate of the widget relative to its parent including
3264 See the \l{Window Geometry} documentation for an overview of geometry
3265 issues with windows.
3267 By default, this property has a value of 0.
3269 \sa frameGeometry, y, pos
3271 int QWidget::x() const
3274 if (isWindow() && ! (windowType() == Qt::Popup))
3275 return data->crect.x() - d->frameStrut().left();
3276 return data->crect.x();
3280 \property QWidget::y
3281 \brief the y coordinate of the widget relative to its parent and
3282 including any window frame
3284 See the \l{Window Geometry} documentation for an overview of geometry
3285 issues with windows.
3287 By default, this property has a value of 0.
3289 \sa frameGeometry, x, pos
3291 int QWidget::y() const
3294 if (isWindow() && ! (windowType() == Qt::Popup))
3295 return data->crect.y() - d->frameStrut().top();
3296 return data->crect.y();
3300 \property QWidget::pos
3301 \brief the position of the widget within its parent widget
3303 If the widget is a window, the position is that of the widget on
3304 the desktop, including its frame.
3306 When changing the position, the widget, if visible, receives a
3307 move event (moveEvent()) immediately. If the widget is not
3308 currently visible, it is guaranteed to receive an event before it
3311 By default, this property contains a position that refers to the
3314 \warning Calling move() or setGeometry() inside moveEvent() can
3315 lead to infinite recursion.
3317 See the \l{Window Geometry} documentation for an overview of geometry
3318 issues with windows.
3320 \sa frameGeometry, size x(), y()
3322 QPoint QWidget::pos() const
3325 if (isWindow() && ! (windowType() == Qt::Popup)) {
3326 QRect fs = d->frameStrut();
3327 return QPoint(data->crect.x() - fs.left(), data->crect.y() - fs.top());
3329 return data->crect.topLeft();
3333 \property QWidget::geometry
3334 \brief the geometry of the widget relative to its parent and
3335 excluding the window frame
3337 When changing the geometry, the widget, if visible, receives a
3338 move event (moveEvent()) and/or a resize event (resizeEvent())
3339 immediately. If the widget is not currently visible, it is
3340 guaranteed to receive appropriate events before it is shown.
3342 The size component is adjusted if it lies outside the range
3343 defined by minimumSize() and maximumSize().
3345 \warning Calling setGeometry() inside resizeEvent() or moveEvent()
3346 can lead to infinite recursion.
3348 See the \l{Window Geometry} documentation for an overview of geometry
3349 issues with windows.
3351 By default, this property contains a value that depends on the user's
3352 platform and screen geometry.
3354 \sa frameGeometry(), rect(), move(), resize(), moveEvent(),
3355 resizeEvent(), minimumSize(), maximumSize()
3359 \property QWidget::normalGeometry
3361 \brief the geometry of the widget as it will appear when shown as
3362 a normal (not maximized or full screen) top-level widget
3364 For child widgets this property always holds an empty rectangle.
3366 By default, this property contains an empty rectangle.
3368 \sa QWidget::windowState(), QWidget::geometry
3372 \property QWidget::size
3373 \brief the size of the widget excluding any window frame
3375 If the widget is visible when it is being resized, it receives a resize event
3376 (resizeEvent()) immediately. If the widget is not currently
3377 visible, it is guaranteed to receive an event before it is shown.
3379 The size is adjusted if it lies outside the range defined by
3380 minimumSize() and maximumSize().
3382 By default, this property contains a value that depends on the user's
3383 platform and screen geometry.
3385 \warning Calling resize() or setGeometry() inside resizeEvent() can
3386 lead to infinite recursion.
3388 \note Setting the size to \c{QSize(0, 0)} will cause the widget to not
3389 appear on screen. This also applies to windows.
3391 \sa pos, geometry, minimumSize, maximumSize, resizeEvent(), adjustSize()
3395 \property QWidget::width
3396 \brief the width of the widget excluding any window frame
3398 See the \l{Window Geometry} documentation for an overview of geometry
3399 issues with windows.
3401 \note Do not use this function to find the width of a screen on
3402 a \l{QDesktopWidget}{multiple screen desktop}. Read
3403 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3405 By default, this property contains a value that depends on the user's
3406 platform and screen geometry.
3408 \sa geometry, height, size
3412 \property QWidget::height
3413 \brief the height of the widget excluding any window frame
3415 See the \l{Window Geometry} documentation for an overview of geometry
3416 issues with windows.
3418 \note Do not use this function to find the height of a screen
3419 on a \l{QDesktopWidget}{multiple screen desktop}. Read
3420 \l{QDesktopWidget#Screen Geometry}{this note} for details.
3422 By default, this property contains a value that depends on the user's
3423 platform and screen geometry.
3425 \sa geometry, width, size
3429 \property QWidget::rect
3430 \brief the internal geometry of the widget excluding any window
3433 The rect property equals QRect(0, 0, width(), height()).
3435 See the \l{Window Geometry} documentation for an overview of geometry
3436 issues with windows.
3438 By default, this property contains a value that depends on the user's
3439 platform and screen geometry.
3445 QRect QWidget::normalGeometry() const
3448 if (!d->extra || !d->extra->topextra)
3451 if (!isMaximized() && !isFullScreen())
3454 return d->topData()->normalGeometry;
3459 \property QWidget::childrenRect
3460 \brief the bounding rectangle of the widget's children
3462 Hidden children are excluded.
3464 By default, for a widget with no children, this property contains a
3465 rectangle with zero width and height located at the origin.
3467 \sa childrenRegion() geometry()
3470 QRect QWidget::childrenRect() const
3473 QRect r(0, 0, 0, 0);
3474 for (int i = 0; i < d->children.size(); ++i) {
3475 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3476 if (w && !w->isWindow() && !w->isHidden())
3483 \property QWidget::childrenRegion
3484 \brief the combined region occupied by the widget's children
3486 Hidden children are excluded.
3488 By default, for a widget with no children, this property contains an
3491 \sa childrenRect() geometry() mask()
3494 QRegion QWidget::childrenRegion() const
3498 for (int i = 0; i < d->children.size(); ++i) {
3499 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
3500 if (w && !w->isWindow() && !w->isHidden()) {
3501 QRegion mask = w->mask();
3505 r |= mask.translated(w->pos());
3513 \property QWidget::minimumSize
3514 \brief the widget's minimum size
3516 The widget cannot be resized to a smaller size than the minimum
3517 widget size. The widget's size is forced to the minimum size if
3518 the current size is smaller.
3520 The minimum size set by this function will override the minimum size
3521 defined by QLayout. In order to unset the minimum size, use a
3522 value of \c{QSize(0, 0)}.
3524 By default, this property contains a size with zero width and height.
3526 \sa minimumWidth, minimumHeight, maximumSize, sizeIncrement
3529 QSize QWidget::minimumSize() const
3532 return d->extra ? QSize(d->extra->minw, d->extra->minh) : QSize(0, 0);
3536 \property QWidget::maximumSize
3537 \brief the widget's maximum size in pixels
3539 The widget cannot be resized to a larger size than the maximum
3542 By default, this property contains a size in which both width and height
3543 have values of 16777215.
3545 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3548 \sa maximumWidth, maximumHeight, minimumSize, sizeIncrement
3551 QSize QWidget::maximumSize() const
3554 return d->extra ? QSize(d->extra->maxw, d->extra->maxh)
3555 : QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
3560 \property QWidget::minimumWidth
3561 \brief the widget's minimum width in pixels
3563 This property corresponds to the width held by the \l minimumSize property.
3565 By default, this property has a value of 0.
3567 \sa minimumSize, minimumHeight
3571 \property QWidget::minimumHeight
3572 \brief the widget's minimum height in pixels
3574 This property corresponds to the height held by the \l minimumSize property.
3576 By default, this property has a value of 0.
3578 \sa minimumSize, minimumWidth
3582 \property QWidget::maximumWidth
3583 \brief the widget's maximum width in pixels
3585 This property corresponds to the width held by the \l maximumSize property.
3587 By default, this property contains a value of 16777215.
3589 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3592 \sa maximumSize, maximumHeight
3596 \property QWidget::maximumHeight
3597 \brief the widget's maximum height in pixels
3599 This property corresponds to the height held by the \l maximumSize property.
3601 By default, this property contains a value of 16777215.
3603 \note The definition of the \c QWIDGETSIZE_MAX macro limits the maximum size
3606 \sa maximumSize, maximumWidth
3610 \property QWidget::sizeIncrement
3611 \brief the size increment of the widget
3613 When the user resizes the window, the size will move in steps of
3614 sizeIncrement().width() pixels horizontally and
3615 sizeIncrement.height() pixels vertically, with baseSize() as the
3616 basis. Preferred widget sizes are for non-negative integers \e i
3618 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 2
3620 Note that while you can set the size increment for all widgets, it
3621 only affects windows.
3623 By default, this property contains a size with zero width and height.
3625 \warning The size increment has no effect under Windows, and may
3626 be disregarded by the window manager on X11.
3628 \sa size, minimumSize, maximumSize
3630 QSize QWidget::sizeIncrement() const
3633 return (d->extra && d->extra->topextra)
3634 ? QSize(d->extra->topextra->incw, d->extra->topextra->inch)
3639 \property QWidget::baseSize
3640 \brief the base size of the widget
3642 The base size is used to calculate a proper widget size if the
3643 widget defines sizeIncrement().
3645 By default, for a newly-created widget, this property contains a size with
3646 zero width and height.
3648 \sa setSizeIncrement()
3651 QSize QWidget::baseSize() const
3654 return (d->extra != 0 && d->extra->topextra != 0)
3655 ? QSize(d->extra->topextra->basew, d->extra->topextra->baseh)
3659 bool QWidgetPrivate::setMinimumSize_helper(int &minw, int &minh)
3663 int mw = minw, mh = minh;
3664 if (mw == QWIDGETSIZE_MAX)
3666 if (mh == QWIDGETSIZE_MAX)
3668 if (minw > QWIDGETSIZE_MAX || minh > QWIDGETSIZE_MAX) {
3669 qWarning("QWidget::setMinimumSize: (%s/%s) "
3670 "The largest allowed size is (%d,%d)",
3671 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3673 minw = mw = qMin<int>(minw, QWIDGETSIZE_MAX);
3674 minh = mh = qMin<int>(minh, QWIDGETSIZE_MAX);
3676 if (minw < 0 || minh < 0) {
3677 qWarning("QWidget::setMinimumSize: (%s/%s) Negative sizes (%d,%d) "
3679 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), minw, minh);
3680 minw = mw = qMax(minw, 0);
3681 minh = mh = qMax(minh, 0);
3684 if (extra->minw == mw && extra->minh == mh)
3688 extra->explicitMinSize = (mw ? Qt::Horizontal : 0) | (mh ? Qt::Vertical : 0);
3695 This function corresponds to setMinimumSize(QSize(minw, minh)).
3696 Sets the minimum width to \a minw and the minimum height to \a
3700 void QWidget::setMinimumSize(int minw, int minh)
3703 if (!d->setMinimumSize_helper(minw, minh))
3707 d->setConstraints_sys();
3708 if (minw > width() || minh > height()) {
3709 bool resized = testAttribute(Qt::WA_Resized);
3710 bool maximized = isMaximized();
3711 resize(qMax(minw,width()), qMax(minh,height()));
3712 setAttribute(Qt::WA_Resized, resized); //not a user resize
3714 data->window_state = data->window_state | Qt::WindowMaximized;
3716 #ifndef QT_NO_GRAPHICSVIEW
3718 if (d->extra->proxyWidget)
3719 d->extra->proxyWidget->setMinimumSize(minw, minh);
3722 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3725 bool QWidgetPrivate::setMaximumSize_helper(int &maxw, int &maxh)
3728 if (maxw > QWIDGETSIZE_MAX || maxh > QWIDGETSIZE_MAX) {
3729 qWarning("QWidget::setMaximumSize: (%s/%s) "
3730 "The largest allowed size is (%d,%d)",
3731 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), QWIDGETSIZE_MAX,
3733 maxw = qMin<int>(maxw, QWIDGETSIZE_MAX);
3734 maxh = qMin<int>(maxh, QWIDGETSIZE_MAX);
3736 if (maxw < 0 || maxh < 0) {
3737 qWarning("QWidget::setMaximumSize: (%s/%s) Negative sizes (%d,%d) "
3739 q->objectName().toLocal8Bit().data(), q->metaObject()->className(), maxw, maxh);
3740 maxw = qMax(maxw, 0);
3741 maxh = qMax(maxh, 0);
3744 if (extra->maxw == maxw && extra->maxh == maxh)
3748 extra->explicitMaxSize = (maxw != QWIDGETSIZE_MAX ? Qt::Horizontal : 0) |
3749 (maxh != QWIDGETSIZE_MAX ? Qt::Vertical : 0);
3756 This function corresponds to setMaximumSize(QSize(\a maxw, \a
3757 maxh)). Sets the maximum width to \a maxw and the maximum height
3760 void QWidget::setMaximumSize(int maxw, int maxh)
3763 if (!d->setMaximumSize_helper(maxw, maxh))
3767 d->setConstraints_sys();
3768 if (maxw < width() || maxh < height()) {
3769 bool resized = testAttribute(Qt::WA_Resized);
3770 resize(qMin(maxw,width()), qMin(maxh,height()));
3771 setAttribute(Qt::WA_Resized, resized); //not a user resize
3774 #ifndef QT_NO_GRAPHICSVIEW
3776 if (d->extra->proxyWidget)
3777 d->extra->proxyWidget->setMaximumSize(maxw, maxh);
3781 d->updateGeometry_helper(d->extra->minw == d->extra->maxw && d->extra->minh == d->extra->maxh);
3787 Sets the x (width) size increment to \a w and the y (height) size
3790 void QWidget::setSizeIncrement(int w, int h)
3794 QTLWExtra* x = d->topData();
3795 if (x->incw == w && x->inch == h)
3800 d->setConstraints_sys();
3806 This corresponds to setBaseSize(QSize(\a basew, \a baseh)). Sets
3807 the widgets base size to width \a basew and height \a baseh.
3809 void QWidget::setBaseSize(int basew, int baseh)
3813 QTLWExtra* x = d->topData();
3814 if (x->basew == basew && x->baseh == baseh)
3819 d->setConstraints_sys();
3823 Sets both the minimum and maximum sizes of the widget to \a s,
3824 thereby preventing it from ever growing or shrinking.
3826 This will override the default size constraints set by QLayout.
3828 To remove constraints, set the size to QWIDGETSIZE_MAX.
3830 Alternatively, if you want the widget to have a
3831 fixed size based on its contents, you can call
3832 QLayout::setSizeConstraint(QLayout::SetFixedSize);
3834 \sa maximumSize, minimumSize
3837 void QWidget::setFixedSize(const QSize & s)
3839 setFixedSize(s.width(), s.height());
3844 \fn void QWidget::setFixedSize(int w, int h)
3847 Sets the width of the widget to \a w and the height to \a h.
3850 void QWidget::setFixedSize(int w, int h)
3853 bool minSizeSet = d->setMinimumSize_helper(w, h);
3854 bool maxSizeSet = d->setMaximumSize_helper(w, h);
3855 if (!minSizeSet && !maxSizeSet)
3859 d->setConstraints_sys();
3861 d->updateGeometry_helper(true);
3863 if (w != QWIDGETSIZE_MAX || h != QWIDGETSIZE_MAX)
3867 void QWidget::setMinimumWidth(int w)
3871 uint expl = d->extra->explicitMinSize | (w ? Qt::Horizontal : 0);
3872 setMinimumSize(w, minimumSize().height());
3873 d->extra->explicitMinSize = expl;
3876 void QWidget::setMinimumHeight(int h)
3880 uint expl = d->extra->explicitMinSize | (h ? Qt::Vertical : 0);
3881 setMinimumSize(minimumSize().width(), h);
3882 d->extra->explicitMinSize = expl;
3885 void QWidget::setMaximumWidth(int w)
3889 uint expl = d->extra->explicitMaxSize | (w == QWIDGETSIZE_MAX ? 0 : Qt::Horizontal);
3890 setMaximumSize(w, maximumSize().height());
3891 d->extra->explicitMaxSize = expl;
3894 void QWidget::setMaximumHeight(int h)
3898 uint expl = d->extra->explicitMaxSize | (h == QWIDGETSIZE_MAX ? 0 : Qt::Vertical);
3899 setMaximumSize(maximumSize().width(), h);
3900 d->extra->explicitMaxSize = expl;
3904 Sets both the minimum and maximum width of the widget to \a w
3905 without changing the heights. Provided for convenience.
3907 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3910 void QWidget::setFixedWidth(int w)
3914 uint explMin = d->extra->explicitMinSize | Qt::Horizontal;
3915 uint explMax = d->extra->explicitMaxSize | Qt::Horizontal;
3916 setMinimumSize(w, minimumSize().height());
3917 setMaximumSize(w, maximumSize().height());
3918 d->extra->explicitMinSize = explMin;
3919 d->extra->explicitMaxSize = explMax;
3924 Sets both the minimum and maximum heights of the widget to \a h
3925 without changing the widths. Provided for convenience.
3927 \sa sizeHint() minimumSize() maximumSize() setFixedSize()
3930 void QWidget::setFixedHeight(int h)
3934 uint explMin = d->extra->explicitMinSize | Qt::Vertical;
3935 uint explMax = d->extra->explicitMaxSize | Qt::Vertical;
3936 setMinimumSize(minimumSize().width(), h);
3937 setMaximumSize(maximumSize().width(), h);
3938 d->extra->explicitMinSize = explMin;
3939 d->extra->explicitMaxSize = explMax;
3944 Translates the widget coordinate \a pos to the coordinate system
3945 of \a parent. The \a parent must not be 0 and must be a parent
3946 of the calling widget.
3948 \sa mapFrom() mapToParent() mapToGlobal() underMouse()
3951 QPoint QWidget::mapTo(QWidget * parent, const QPoint & pos) const
3955 const QWidget * w = this;
3956 while (w != parent) {
3957 Q_ASSERT_X(w, "QWidget::mapTo(QWidget *parent, const QPoint &pos)",
3958 "parent must be in parent hierarchy");
3959 p = w->mapToParent(p);
3960 w = w->parentWidget();
3968 Translates the widget coordinate \a pos from the coordinate system
3969 of \a parent to this widget's coordinate system. The \a parent
3970 must not be 0 and must be a parent of the calling widget.
3972 \sa mapTo() mapFromParent() mapFromGlobal() underMouse()
3975 QPoint QWidget::mapFrom(QWidget * parent, const QPoint & pos) const
3979 const QWidget * w = this;
3980 while (w != parent) {
3981 Q_ASSERT_X(w, "QWidget::mapFrom(QWidget *parent, const QPoint &pos)",
3982 "parent must be in parent hierarchy");
3984 p = w->mapFromParent(p);
3985 w = w->parentWidget();
3993 Translates the widget coordinate \a pos to a coordinate in the
3996 Same as mapToGlobal() if the widget has no parent.
3998 \sa mapFromParent() mapTo() mapToGlobal() underMouse()
4001 QPoint QWidget::mapToParent(const QPoint &pos) const
4003 return pos + data->crect.topLeft();
4007 Translates the parent widget coordinate \a pos to widget
4010 Same as mapFromGlobal() if the widget has no parent.
4012 \sa mapToParent() mapFrom() mapFromGlobal() underMouse()
4015 QPoint QWidget::mapFromParent(const QPoint &pos) const
4017 return pos - data->crect.topLeft();
4022 Returns the window for this widget, i.e. the next ancestor widget
4023 that has (or could have) a window-system frame.
4025 If the widget is a window, the widget itself is returned.
4027 Typical usage is changing the window title:
4029 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 3
4034 QWidget *QWidget::window() const
4036 QWidget *w = (QWidget *)this;
4037 QWidget *p = w->parentWidget();
4038 while (!w->isWindow() && p) {
4040 p = p->parentWidget();
4048 Returns the native parent for this widget, i.e. the next ancestor widget
4049 that has a system identifier, or 0 if it does not have any native parent.
4051 \sa effectiveWinId()
4053 QWidget *QWidget::nativeParentWidget() const
4055 QWidget *parent = parentWidget();
4056 while (parent && !parent->internalWinId())
4057 parent = parent->parentWidget();
4061 /*! \fn QWidget *QWidget::topLevelWidget() const
4064 Use window() instead.
4070 Returns the background role of the widget.
4072 The background role defines the brush from the widget's \l palette that
4073 is used to render the background.
4075 If no explicit background role is set, the widget inherts its parent
4076 widget's background role.
4078 \sa setBackgroundRole(), foregroundRole()
4080 QPalette::ColorRole QWidget::backgroundRole() const
4083 const QWidget *w = this;
4085 QPalette::ColorRole role = w->d_func()->bg_role;
4086 if (role != QPalette::NoRole)
4088 if (w->isWindow() || w->windowType() == Qt::SubWindow)
4090 w = w->parentWidget();
4092 return QPalette::Window;
4096 Sets the background role of the widget to \a role.
4098 The background role defines the brush from the widget's \l palette that
4099 is used to render the background.
4101 If \a role is QPalette::NoRole, then the widget inherits its
4102 parent's background role.
4104 Note that styles are free to choose any color from the palette.
4105 You can modify the palette or set a style sheet if you don't
4106 achieve the result you want with setBackgroundRole().
4108 \sa backgroundRole(), foregroundRole()
4111 void QWidget::setBackgroundRole(QPalette::ColorRole role)
4115 d->updateSystemBackground();
4116 d->propagatePaletteChange();
4117 d->updateIsOpaque();
4121 Returns the foreground role.
4123 The foreground role defines the color from the widget's \l palette that
4124 is used to draw the foreground.
4126 If no explicit foreground role is set, the function returns a role
4127 that contrasts with the background role.
4129 \sa setForegroundRole(), backgroundRole()
4131 QPalette::ColorRole QWidget::foregroundRole() const
4134 QPalette::ColorRole rl = QPalette::ColorRole(d->fg_role);
4135 if (rl != QPalette::NoRole)
4137 QPalette::ColorRole role = QPalette::WindowText;
4138 switch (backgroundRole()) {
4139 case QPalette::Button:
4140 role = QPalette::ButtonText;
4142 case QPalette::Base:
4143 role = QPalette::Text;
4145 case QPalette::Dark:
4146 case QPalette::Shadow:
4147 role = QPalette::Light;
4149 case QPalette::Highlight:
4150 role = QPalette::HighlightedText;
4152 case QPalette::ToolTipBase:
4153 role = QPalette::ToolTipText;
4162 Sets the foreground role of the widget to \a role.
4164 The foreground role defines the color from the widget's \l palette that
4165 is used to draw the foreground.
4167 If \a role is QPalette::NoRole, the widget uses a foreground role
4168 that contrasts with the background role.
4170 Note that styles are free to choose any color from the palette.
4171 You can modify the palette or set a style sheet if you don't
4172 achieve the result you want with setForegroundRole().
4174 \sa foregroundRole(), backgroundRole()
4176 void QWidget::setForegroundRole(QPalette::ColorRole role)
4180 d->updateSystemBackground();
4181 d->propagatePaletteChange();
4185 \property QWidget::palette
4186 \brief the widget's palette
4188 This property describes the widget's palette. The palette is used by the
4189 widget's style when rendering standard components, and is available as a
4190 means to ensure that custom widgets can maintain consistency with the
4191 native platform's look and feel. It's common that different platforms, or
4192 different styles, have different palettes.
4194 When you assign a new palette to a widget, the color roles from this
4195 palette are combined with the widget's default palette to form the
4196 widget's final palette. The palette entry for the widget's background role
4197 is used to fill the widget's background (see QWidget::autoFillBackground),
4198 and the foreground role initializes QPainter's pen.
4200 The default depends on the system environment. QApplication maintains a
4201 system/theme palette which serves as a default for all widgets. There may
4202 also be special palette defaults for certain types of widgets (e.g., on
4203 Windows XP and Vista, all classes that derive from QMenuBar have a special
4204 default palette). You can also define default palettes for widgets
4205 yourself by passing a custom palette and the name of a widget to
4206 QApplication::setPalette(). Finally, the style always has the option of
4207 polishing the palette as it's assigned (see QStyle::polish()).
4209 QWidget propagates explicit palette roles from parent to child. If you
4210 assign a brush or color to a specific role on a palette and assign that
4211 palette to a widget, that role will propagate to all the widget's
4212 children, overriding any system defaults for that role. Note that palettes
4213 by default don't propagate to windows (see isWindow()) unless the
4214 Qt::WA_WindowPropagation attribute is enabled.
4216 QWidget's palette propagation is similar to its font propagation.
4218 The current style, which is used to render the content of all standard Qt
4219 widgets, is free to choose colors and brushes from the widget palette, or
4220 in some cases, to ignore the palette (partially, or completely). In
4221 particular, certain styles like GTK style, Mac style, Windows XP, and
4222 Vista style, depend on third party APIs to render the content of widgets,
4223 and these styles typically do not follow the palette. Because of this,
4224 assigning roles to a widget's palette is not guaranteed to change the
4225 appearance of the widget. Instead, you may choose to apply a \l
4226 styleSheet. You can refer to our Knowledge Base article
4227 \l{http://qt.nokia.com/developer/knowledgebase/22}{here} for more
4230 \warning Do not use this function in conjunction with \l{Qt Style Sheets}.
4231 When using style sheets, the palette of a widget can be customized using
4232 the "color", "background-color", "selection-color",
4233 "selection-background-color" and "alternate-background-color".
4235 \sa QApplication::palette(), QWidget::font()
4237 const QPalette &QWidget::palette() const
4240 data->pal.setCurrentColorGroup(QPalette::Disabled);
4241 } else if ((!isVisible() || isActiveWindow())
4242 #if defined(Q_OS_WIN) && !defined(Q_WS_WINCE)
4243 && !QApplicationPrivate::isBlockedByModal(const_cast<QWidget *>(this))
4246 data->pal.setCurrentColorGroup(QPalette::Active);
4249 extern bool qt_mac_can_clickThrough(const QWidget *); //qwidget_mac.cpp
4250 if (qt_mac_can_clickThrough(this))
4251 data->pal.setCurrentColorGroup(QPalette::Active);
4254 data->pal.setCurrentColorGroup(QPalette::Inactive);
4259 void QWidget::setPalette(const QPalette &palette)
4262 setAttribute(Qt::WA_SetPalette, palette.resolve() != 0);
4264 // Determine which palette is inherited from this widget's ancestors and
4265 // QApplication::palette, resolve this against \a palette (attributes from
4266 // the inherited palette are copied over this widget's palette). Then
4267 // propagate this palette to this widget's children.
4268 QPalette naturalPalette = d->naturalWidgetPalette(d->inheritedPaletteResolveMask);
4269 QPalette resolvedPalette = palette.resolve(naturalPalette);
4270 d->setPalette_helper(resolvedPalette);
4276 Returns the palette that the widget \a w inherits from its ancestors and
4277 QApplication::palette. \a inheritedMask is the combination of the widget's
4278 ancestors palette request masks (i.e., which attributes from the parent
4279 widget's palette are implicitly imposed on this widget by the user). Note
4280 that this font does not take into account the palette set on \a w itself.
4282 QPalette QWidgetPrivate::naturalWidgetPalette(uint inheritedMask) const
4285 QPalette naturalPalette = QApplication::palette(q);
4286 if (!q->testAttribute(Qt::WA_StyleSheet)
4287 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4288 #ifndef QT_NO_GRAPHICSVIEW
4289 || (extra && extra->proxyWidget)
4290 #endif //QT_NO_GRAPHICSVIEW
4292 if (QWidget *p = q->parentWidget()) {
4293 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4294 if (!naturalPalette.isCopyOf(QApplication::palette())) {
4295 QPalette inheritedPalette = p->palette();
4296 inheritedPalette.resolve(inheritedMask);
4297 naturalPalette = inheritedPalette.resolve(naturalPalette);
4299 naturalPalette = p->palette();
4303 #ifndef QT_NO_GRAPHICSVIEW
4304 else if (extra && extra->proxyWidget) {
4305 QPalette inheritedPalette = extra->proxyWidget->palette();
4306 inheritedPalette.resolve(inheritedMask);
4307 naturalPalette = inheritedPalette.resolve(naturalPalette);
4309 #endif //QT_NO_GRAPHICSVIEW
4311 naturalPalette.resolve(0);
4312 return naturalPalette;
4317 Determine which palette is inherited from this widget's ancestors and
4318 QApplication::palette, resolve this against this widget's palette
4319 (attributes from the inherited palette are copied over this widget's
4320 palette). Then propagate this palette to this widget's children.
4322 void QWidgetPrivate::resolvePalette()
4324 QPalette naturalPalette = naturalWidgetPalette(inheritedPaletteResolveMask);
4325 QPalette resolvedPalette = data.pal.resolve(naturalPalette);
4326 setPalette_helper(resolvedPalette);
4329 void QWidgetPrivate::setPalette_helper(const QPalette &palette)
4332 if (data.pal == palette && data.pal.resolve() == palette.resolve())
4335 updateSystemBackground();
4336 propagatePaletteChange();
4343 \property QWidget::font
4344 \brief the font currently set for the widget
4346 This property describes the widget's requested font. The font is used by
4347 the widget's style when rendering standard components, and is available as
4348 a means to ensure that custom widgets can maintain consistency with the
4349 native platform's look and feel. It's common that different platforms, or
4350 different styles, define different fonts for an application.
4352 When you assign a new font to a widget, the properties from this font are
4353 combined with the widget's default font to form the widget's final
4354 font. You can call fontInfo() to get a copy of the widget's final
4355 font. The final font is also used to initialize QPainter's font.
4357 The default depends on the system environment. QApplication maintains a
4358 system/theme font which serves as a default for all widgets. There may
4359 also be special font defaults for certain types of widgets. You can also
4360 define default fonts for widgets yourself by passing a custom font and the
4361 name of a widget to QApplication::setFont(). Finally, the font is matched
4362 against Qt's font database to find the best match.
4364 QWidget propagates explicit font properties from parent to child. If you
4365 change a specific property on a font and assign that font to a widget,
4366 that property will propagate to all the widget's children, overriding any
4367 system defaults for that property. Note that fonts by default don't
4368 propagate to windows (see isWindow()) unless the Qt::WA_WindowPropagation
4369 attribute is enabled.
4371 QWidget's font propagation is similar to its palette propagation.
4373 The current style, which is used to render the content of all standard Qt
4374 widgets, is free to choose to use the widget font, or in some cases, to
4375 ignore it (partially, or completely). In particular, certain styles like
4376 GTK style, Mac style, Windows XP, and Vista style, apply special
4377 modifications to the widget font to match the platform's native look and
4378 feel. Because of this, assigning properties to a widget's font is not
4379 guaranteed to change the appearance of the widget. Instead, you may choose
4380 to apply a \l styleSheet.
4382 \note If \l{Qt Style Sheets} are used on the same widget as setFont(),
4383 style sheets will take precedence if the settings conflict.
4385 \sa fontInfo(), fontMetrics()
4388 void QWidget::setFont(const QFont &font)
4392 #ifndef QT_NO_STYLE_STYLESHEET
4393 const QStyleSheetStyle* style;
4394 if (d->extra && (style = qobject_cast<const QStyleSheetStyle*>(d->extra->style))) {
4395 style->saveWidgetFont(this, font);
4399 setAttribute(Qt::WA_SetFont, font.resolve() != 0);
4401 // Determine which font is inherited from this widget's ancestors and
4402 // QApplication::font, resolve this against \a font (attributes from the
4403 // inherited font are copied over). Then propagate this font to this
4404 // widget's children.
4405 QFont naturalFont = d->naturalWidgetFont(d->inheritedFontResolveMask);
4406 QFont resolvedFont = font.resolve(naturalFont);
4407 d->setFont_helper(resolvedFont);
4413 Returns the font that the widget \a w inherits from its ancestors and
4414 QApplication::font. \a inheritedMask is the combination of the widget's
4415 ancestors font request masks (i.e., which attributes from the parent
4416 widget's font are implicitly imposed on this widget by the user). Note
4417 that this font does not take into account the font set on \a w itself.
4419 ### Stylesheet has a different font propagation mechanism. When a stylesheet
4420 is applied, fonts are not propagated anymore
4422 QFont QWidgetPrivate::naturalWidgetFont(uint inheritedMask) const
4425 QFont naturalFont = QApplication::font(q);
4426 if (!q->testAttribute(Qt::WA_StyleSheet)
4427 && (!q->isWindow() || q->testAttribute(Qt::WA_WindowPropagation)
4428 #ifndef QT_NO_GRAPHICSVIEW
4429 || (extra && extra->proxyWidget)
4430 #endif //QT_NO_GRAPHICSVIEW
4432 if (QWidget *p = q->parentWidget()) {
4433 if (!p->testAttribute(Qt::WA_StyleSheet)) {
4434 if (!naturalFont.isCopyOf(QApplication::font())) {
4435 QFont inheritedFont = p->font();
4436 inheritedFont.resolve(inheritedMask);
4437 naturalFont = inheritedFont.resolve(naturalFont);
4439 naturalFont = p->font();
4443 #ifndef QT_NO_GRAPHICSVIEW
4444 else if (extra && extra->proxyWidget) {
4445 QFont inheritedFont = extra->proxyWidget->font();
4446 inheritedFont.resolve(inheritedMask);
4447 naturalFont = inheritedFont.resolve(naturalFont);
4449 #endif //QT_NO_GRAPHICSVIEW
4451 naturalFont.resolve(0);
4458 Determine which font is implicitly imposed on this widget by its ancestors
4459 and QApplication::font, resolve this against its own font (attributes from
4460 the implicit font are copied over). Then propagate this font to this
4463 void QWidgetPrivate::resolveFont()
4465 QFont naturalFont = naturalWidgetFont(inheritedFontResolveMask);
4466 QFont resolvedFont = data.fnt.resolve(naturalFont);
4467 setFont_helper(resolvedFont);
4473 Assign \a font to this widget, and propagate it to all children, except
4474 style sheet widgets (handled differently) and windows that don't enable
4475 window propagation. \a implicitMask is the union of all ancestor widgets'
4476 font request masks, and determines which attributes from this widget's
4477 font should propagate.
4479 void QWidgetPrivate::updateFont(const QFont &font)
4482 #ifndef QT_NO_STYLE_STYLESHEET
4483 const QStyleSheetStyle* cssStyle;
4484 cssStyle = extra ? qobject_cast<const QStyleSheetStyle*>(extra->style) : 0;
4487 data.fnt = QFont(font, q);
4488 #if defined(Q_WS_X11)
4489 // make sure the font set on this widget is associated with the correct screen
4490 data.fnt.x11SetScreen(xinfo.screen());
4492 // Combine new mask with natural mask and propagate to children.
4493 #ifndef QT_NO_GRAPHICSVIEW
4494 if (!q->parentWidget() && extra && extra->proxyWidget) {
4495 QGraphicsProxyWidget *p = extra->proxyWidget;
4496 inheritedFontResolveMask = p->d_func()->inheritedFontResolveMask | p->font().resolve();
4498 #endif //QT_NO_GRAPHICSVIEW
4499 if (q->isWindow() && !q->testAttribute(Qt::WA_WindowPropagation)) {
4500 inheritedFontResolveMask = 0;
4502 uint newMask = data.fnt.resolve() | inheritedFontResolveMask;
4504 for (int i = 0; i < children.size(); ++i) {
4505 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4508 #ifndef QT_NO_STYLE_STYLESHEET
4509 } else if (w->testAttribute(Qt::WA_StyleSheet)) {
4510 // Style sheets follow a different font propagation scheme.
4512 cssStyle->updateStyleSheetFont(w);
4514 } else if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))) {
4515 // Propagate font changes.
4516 QWidgetPrivate *wd = w->d_func();
4517 wd->inheritedFontResolveMask = newMask;
4523 #ifndef QT_NO_STYLE_STYLESHEET
4525 cssStyle->updateStyleSheetFont(q);
4529 QEvent e(QEvent::FontChange);
4530 QApplication::sendEvent(q, &e);
4533 void QWidgetPrivate::setLayoutDirection_helper(Qt::LayoutDirection direction)
4537 if ( (direction == Qt::RightToLeft) == q->testAttribute(Qt::WA_RightToLeft))
4539 q->setAttribute(Qt::WA_RightToLeft, (direction == Qt::RightToLeft));
4540 if (!children.isEmpty()) {
4541 for (int i = 0; i < children.size(); ++i) {
4542 QWidget *w = qobject_cast<QWidget*>(children.at(i));
4543 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_SetLayoutDirection))
4544 w->d_func()->setLayoutDirection_helper(direction);
4547 QEvent e(QEvent::LayoutDirectionChange);
4548 QApplication::sendEvent(q, &e);
4551 void QWidgetPrivate::resolveLayoutDirection()
4554 if (!q->testAttribute(Qt::WA_SetLayoutDirection))
4555 setLayoutDirection_helper(q->isWindow() ? QApplication::layoutDirection() : q->parentWidget()->layoutDirection());
4559 \property QWidget::layoutDirection
4561 \brief the layout direction for this widget
4563 By default, this property is set to Qt::LeftToRight.
4565 When the layout direction is set on a widget, it will propagate to
4566 the widget's children, but not to a child that is a window and not
4567 to a child for which setLayoutDirection() has been explicitly
4568 called. Also, child widgets added \e after setLayoutDirection()
4569 has been called for the parent do not inherit the parent's layout
4572 This method no longer affects text layout direction since Qt 4.7.
4574 \sa QApplication::layoutDirection
4576 void QWidget::setLayoutDirection(Qt::LayoutDirection direction)
4580 if (direction == Qt::LayoutDirectionAuto) {
4581 unsetLayoutDirection();
4585 setAttribute(Qt::WA_SetLayoutDirection);
4586 d->setLayoutDirection_helper(direction);
4589 Qt::LayoutDirection QWidget::layoutDirection() const
4591 return testAttribute(Qt::WA_RightToLeft) ? Qt::RightToLeft : Qt::LeftToRight;
4594 void QWidget::unsetLayoutDirection()
4597 setAttribute(Qt::WA_SetLayoutDirection, false);
4598 d->resolveLayoutDirection();
4602 \fn QFontMetrics QWidget::fontMetrics() const
4604 Returns the font metrics for the widget's current font.
4605 Equivalent to QFontMetrics(widget->font()).
4607 \sa font(), fontInfo(), setFont()
4611 \fn QFontInfo QWidget::fontInfo() const
4613 Returns the font info for the widget's current font.
4614 Equivalent to QFontInto(widget->font()).
4616 \sa font(), fontMetrics(), setFont()
4621 \property QWidget::cursor
4622 \brief the cursor shape for this widget
4624 The mouse cursor will assume this shape when it's over this
4625 widget. See the \link Qt::CursorShape list of predefined cursor
4626 objects\endlink for a range of useful shapes.
4628 An editor widget might use an I-beam cursor:
4629 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 6
4631 If no cursor has been set, or after a call to unsetCursor(), the
4632 parent's cursor is used.
4634 By default, this property contains a cursor with the Qt::ArrowCursor
4637 Some underlying window implementations will reset the cursor if it
4638 leaves a widget even if the mouse is grabbed. If you want to have
4639 a cursor set for all widgets, even when outside the window, consider
4640 QApplication::setOverrideCursor().
4642 \sa QApplication::setOverrideCursor()
4645 #ifndef QT_NO_CURSOR
4646 QCursor QWidget::cursor() const
4649 if (testAttribute(Qt::WA_SetCursor))
4650 return (d->extra && d->extra->curs)
4652 : QCursor(Qt::ArrowCursor);
4653 if (isWindow() || !parentWidget())
4654 return QCursor(Qt::ArrowCursor);
4655 return parentWidget()->cursor();
4658 void QWidget::setCursor(const QCursor &cursor)
4661 // On Mac we must set the cursor even if it is the ArrowCursor.
4662 #if !defined(Q_WS_MAC)
4663 if (cursor.shape() != Qt::ArrowCursor
4664 || (d->extra && d->extra->curs))
4668 QCursor *newCursor = new QCursor(cursor);
4669 delete d->extra->curs;
4670 d->extra->curs = newCursor;
4672 setAttribute(Qt::WA_SetCursor);
4673 d->setCursor_sys(cursor);
4675 QEvent event(QEvent::CursorChange);
4676 QApplication::sendEvent(this, &event);
4679 void QWidget::unsetCursor()
4683 delete d->extra->curs;
4687 setAttribute(Qt::WA_SetCursor, false);
4688 d->unsetCursor_sys();
4690 QEvent event(QEvent::CursorChange);
4691 QApplication::sendEvent(this, &event);
4697 \enum QWidget::RenderFlag
4699 This enum describes how to render the widget when calling QWidget::render().
4701 \value DrawWindowBackground If you enable this option, the widget's background
4702 is rendered into the target even if autoFillBackground is not set. By default,
4703 this option is enabled.
4705 \value DrawChildren If you enable this option, the widget's children
4706 are rendered recursively into the target. By default, this option is enabled.
4708 \value IgnoreMask If you enable this option, the widget's QWidget::mask()
4709 is ignored when rendering into the target. By default, this option is disabled.
4717 Renders the \a sourceRegion of this widget into the \a target
4718 using \a renderFlags to determine how to render. Rendering
4719 starts at \a targetOffset in the \a target. For example:
4721 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 7
4723 If \a sourceRegion is a null region, this function will use QWidget::rect() as
4724 the region, i.e. the entire widget.
4726 Ensure that you call QPainter::end() for the \a target device's
4727 active painter (if any) before rendering. For example:
4729 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 8
4731 \note To obtain the contents of an OpenGL widget, use QGLWidget::grabFrameBuffer()
4732 or QGLWidget::renderPixmap() instead.
4734 void QWidget::render(QPaintDevice *target, const QPoint &targetOffset,
4735 const QRegion &sourceRegion, RenderFlags renderFlags)
4737 d_func()->render(target, targetOffset, sourceRegion, renderFlags, false);
4743 Renders the widget into the \a painter's QPainter::device().
4745 Transformations and settings applied to the \a painter will be used
4748 \note The \a painter must be active. On Mac OS X the widget will be
4749 rendered into a QPixmap and then drawn by the \a painter.
4751 \sa QPainter::device()
4753 void QWidget::render(QPainter *painter, const QPoint &targetOffset,
4754 const QRegion &sourceRegion, RenderFlags renderFlags)
4757 qWarning("QWidget::render: Null pointer to painter");
4761 if (!painter->isActive()) {
4762 qWarning("QWidget::render: Cannot render with an inactive painter");
4766 const qreal opacity = painter->opacity();
4767 if (qFuzzyIsNull(opacity))
4768 return; // Fully transparent.
4771 const bool inRenderWithPainter = d->extra && d->extra->inRenderWithPainter;
4772 const QRegion toBePainted = !inRenderWithPainter ? d->prepareToRender(sourceRegion, renderFlags)
4774 if (toBePainted.isEmpty())
4779 d->extra->inRenderWithPainter = true;
4782 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4784 QPaintEngine *engine = painter->paintEngine();
4786 QPaintEnginePrivate *enginePriv = engine->d_func();
4787 Q_ASSERT(enginePriv);
4788 QPaintDevice *target = engine->paintDevice();
4791 // Render via a pixmap when dealing with non-opaque painters or printers.
4792 if (!inRenderWithPainter && (opacity < 1.0 || (target->devType() == QInternal::Printer))) {
4793 d->render_helper(painter, targetOffset, toBePainted, renderFlags);
4794 d->extra->inRenderWithPainter = false;
4798 // Set new shared painter.
4799 QPainter *oldPainter = d->sharedPainter();
4800 d->setSharedPainter(painter);
4802 // Save current system clip, viewport and transform,
4803 const QTransform oldTransform = enginePriv->systemTransform;
4804 const QRegion oldSystemClip = enginePriv->systemClip;
4805 const QRegion oldSystemViewport = enginePriv->systemViewport;
4807 // This ensures that all painting triggered by render() is clipped to the current engine clip.
4808 if (painter->hasClipping()) {
4809 const QRegion painterClip = painter->deviceTransform().map(painter->clipRegion());
4810 enginePriv->setSystemViewport(oldSystemClip.isEmpty() ? painterClip : oldSystemClip & painterClip);
4812 enginePriv->setSystemViewport(oldSystemClip);
4815 render(target, targetOffset, toBePainted, renderFlags);
4817 // Restore system clip, viewport and transform.
4818 enginePriv->systemClip = oldSystemClip;
4819 enginePriv->setSystemViewport(oldSystemViewport);
4820 enginePriv->setSystemTransform(oldTransform);
4822 // Restore shared painter.
4823 d->setSharedPainter(oldPainter);
4826 d->extra->inRenderWithPainter = false;
4829 static void sendResizeEvents(QWidget *target)
4831 QResizeEvent e(target->size(), QSize());
4832 QApplication::sendEvent(target, &e);
4834 const QObjectList children = target->children();
4835 for (int i = 0; i < children.size(); ++i) {
4836 QWidget *child = static_cast<QWidget*>(children.at(i));
4837 if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent))
4838 sendResizeEvents(child);
4845 Renders the widget into a pixmap restricted by the
4846 given \a rectangle. If the \a widget has any children, then
4847 they are also painted in the appropriate positions.
4849 If no rectangle is specified (the default) the entire widget is
4852 Replacement for Qt 4's QPixmap::grabWidget().
4854 \sa render(), QPixmap
4857 /* INVOKABLE since used by QPixmap::grabWidget(). */
4858 QPixmap QWidget::grab(const QRect &rectangle)
4861 if (testAttribute(Qt::WA_PendingResizeEvent) || !testAttribute(Qt::WA_WState_Created))
4862 sendResizeEvents(this);
4868 r.setWidth(width() - rectangle.x());
4870 r.setHeight(height() - rectangle.y());
4872 if (!r.intersects(rect()))
4875 QPixmap res(r.size());
4877 res.fill(Qt::transparent);
4878 render(&res, QPoint(), QRegion(r), QWidget::DrawWindowBackground
4879 | QWidget::DrawChildren | QWidget::IgnoreMask);
4884 \brief The graphicsEffect function returns a pointer to the
4885 widget's graphics effect.
4887 If the widget has no graphics effect, 0 is returned.
4891 \sa setGraphicsEffect()
4893 #ifndef QT_NO_GRAPHICSEFFECT
4894 QGraphicsEffect *QWidget::graphicsEffect() const
4897 return d->graphicsEffect;
4899 #endif //QT_NO_GRAPHICSEFFECT
4903 \brief The setGraphicsEffect function is for setting the widget's graphics effect.
4905 Sets \a effect as the widget's effect. If there already is an effect installed
4906 on this widget, QWidget will delete the existing effect before installing
4909 If \a effect is the installed on a different widget, setGraphicsEffect() will remove
4910 the effect from the widget and install it on this widget.
4912 QWidget takes ownership of \a effect.
4914 \note This function will apply the effect on itself and all its children.
4918 \sa graphicsEffect()
4920 #ifndef QT_NO_GRAPHICSEFFECT
4921 void QWidget::setGraphicsEffect(QGraphicsEffect *effect)
4924 if (d->graphicsEffect == effect)
4927 if (d->graphicsEffect) {
4928 d->invalidateBuffer(rect());
4929 delete d->graphicsEffect;
4930 d->graphicsEffect = 0;
4935 QGraphicsEffectSourcePrivate *sourced = new QWidgetEffectSourcePrivate(this);
4936 QGraphicsEffectSource *source = new QGraphicsEffectSource(*sourced);
4937 d->graphicsEffect = effect;
4938 effect->d_func()->setGraphicsEffectSource(source);
4942 d->updateIsOpaque();
4944 #endif //QT_NO_GRAPHICSEFFECT
4946 bool QWidgetPrivate::isAboutToShow() const
4955 // The widget will be shown if any of its ancestors are about to show.
4956 QWidget *parent = q->parentWidget();
4957 return parent ? parent->d_func()->isAboutToShow() : false;
4960 QRegion QWidgetPrivate::prepareToRender(const QRegion ®ion, QWidget::RenderFlags renderFlags)
4963 const bool isVisible = q->isVisible();
4965 // Make sure the widget is laid out correctly.
4966 if (!isVisible && !isAboutToShow()) {
4967 QWidget *topLevel = q->window();
4968 (void)topLevel->d_func()->topData(); // Make sure we at least have top-data.
4969 topLevel->ensurePolished();
4971 // Invalidate the layout of hidden ancestors (incl. myself) and pretend
4972 // they're not explicitly hidden.
4973 QWidget *widget = q;
4974 QWidgetList hiddenWidgets;
4976 if (widget->isHidden()) {
4977 widget->setAttribute(Qt::WA_WState_Hidden, false);
4978 hiddenWidgets.append(widget);
4979 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
4980 widget->d_func()->updateGeometry_helper(true);
4982 widget = widget->parentWidget();
4985 // Activate top-level layout.
4986 if (topLevel->d_func()->layout)
4987 topLevel->d_func()->layout->activate();
4989 // Adjust size if necessary.
4990 QTLWExtra *topLevelExtra = topLevel->d_func()->maybeTopData();
4991 if (topLevelExtra && !topLevelExtra->sizeAdjusted
4992 && !topLevel->testAttribute(Qt::WA_Resized)) {
4993 topLevel->adjustSize();
4994 topLevel->setAttribute(Qt::WA_Resized, false);
4997 // Activate child layouts.
4998 topLevel->d_func()->activateChildLayoutsRecursively();
5000 // We're not cheating with WA_WState_Hidden anymore.
5001 for (int i = 0; i < hiddenWidgets.size(); ++i) {
5002 QWidget *widget = hiddenWidgets.at(i);
5003 widget->setAttribute(Qt::WA_WState_Hidden);
5004 if (!widget->isWindow() && widget->parentWidget()->d_func()->layout)
5005 widget->parentWidget()->d_func()->layout->invalidate();
5007 } else if (isVisible) {
5008 q->window()->d_func()->sendPendingMoveAndResizeEvents(true, true);
5011 // Calculate the region to be painted.
5012 QRegion toBePainted = !region.isEmpty() ? region : QRegion(q->rect());
5013 if (!(renderFlags & QWidget::IgnoreMask) && extra && extra->hasMask)
5014 toBePainted &= extra->mask;
5018 void QWidgetPrivate::render_helper(QPainter *painter, const QPoint &targetOffset, const QRegion &toBePainted,
5019 QWidget::RenderFlags renderFlags)
5022 Q_ASSERT(!toBePainted.isEmpty());
5026 const QTransform originalTransform = painter->worldTransform();
5027 const bool useDeviceCoordinates = originalTransform.isScaling();
5028 if (!useDeviceCoordinates) {
5030 // Render via a pixmap.
5031 const QRect rect = toBePainted.boundingRect();
5032 const QSize size = rect.size();
5036 QPixmap pixmap(size);
5037 if (!(renderFlags & QWidget::DrawWindowBackground) || !isOpaque)
5038 pixmap.fill(Qt::transparent);
5039 q->render(&pixmap, QPoint(), toBePainted, renderFlags);
5041 const bool restore = !(painter->renderHints() & QPainter::SmoothPixmapTransform);
5042 painter->setRenderHints(QPainter::SmoothPixmapTransform, true);
5044 painter->drawPixmap(targetOffset, pixmap);
5047 painter->setRenderHints(QPainter::SmoothPixmapTransform, false);
5051 // Render via a pixmap in device coordinates (to avoid pixmap scaling).
5052 QTransform transform = originalTransform;
5053 transform.translate(targetOffset.x(), targetOffset.y());
5055 QPaintDevice *device = painter->device();
5058 // Calculate device rect.
5059 const QRectF rect(toBePainted.boundingRect());
5060 QRect deviceRect = transform.mapRect(QRectF(0, 0, rect.width(), rect.height())).toAlignedRect();
5061 deviceRect &= QRect(0, 0, device->width(), device->height());
5063 QPixmap pixmap(deviceRect.size());
5064 pixmap.fill(Qt::transparent);
5066 // Create a pixmap device coordinate painter.
5067 QPainter pixmapPainter(&pixmap);
5068 pixmapPainter.setRenderHints(painter->renderHints());
5069 transform *= QTransform::fromTranslate(-deviceRect.x(), -deviceRect.y());
5070 pixmapPainter.setTransform(transform);
5072 q->render(&pixmapPainter, QPoint(), toBePainted, renderFlags);
5073 pixmapPainter.end();
5075 // And then draw the pixmap.
5076 painter->setTransform(QTransform());
5077 painter->drawPixmap(deviceRect.topLeft(), pixmap);
5078 painter->setTransform(originalTransform);
5083 void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QPoint &offset, int flags,
5084 QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5090 if (qt_mac_clearDirtyOnWidgetInsideDrawWidget)
5091 dirtyOnWidget = QRegion();
5093 // We disable the rendering of QToolBar in the backingStore if
5094 // it's supposed to be in the unified toolbar on Mac OS X.
5095 if (backingStore && isInUnifiedToolbar)
5101 #ifndef QT_NO_GRAPHICSEFFECT
5102 if (graphicsEffect && graphicsEffect->isEnabled()) {
5103 QGraphicsEffectSource *source = graphicsEffect->d_func()->source;
5104 QWidgetEffectSourcePrivate *sourced = static_cast<QWidgetEffectSourcePrivate *>
5106 if (!sourced->context) {
5107 QWidgetPaintContext context(pdev, rgn, offset, flags, sharedPainter, backingStore);
5108 sourced->context = &context;
5109 if (!sharedPainter) {
5110 QPaintEngine *paintEngine = pdev->paintEngine();
5111 paintEngine->d_func()->systemClip = rgn.translated(offset);
5113 p.translate(offset);
5114 context.painter = &p;
5115 graphicsEffect->draw(&p);
5116 paintEngine->d_func()->systemClip = QRegion();
5118 context.painter = sharedPainter;
5119 if (sharedPainter->worldTransform() != sourced->lastEffectTransform) {
5120 sourced->invalidateCache();
5121 sourced->lastEffectTransform = sharedPainter->worldTransform();
5123 sharedPainter->save();
5124 sharedPainter->translate(offset);
5125 graphicsEffect->draw(sharedPainter);
5126 sharedPainter->restore();
5128 sourced->context = 0;
5132 #endif //QT_NO_GRAFFICSEFFECT
5134 const bool asRoot = flags & DrawAsRoot;
5135 const bool alsoOnScreen = flags & DrawPaintOnScreen;
5136 const bool recursive = flags & DrawRecursive;
5137 const bool alsoInvisible = flags & DrawInvisible;
5139 Q_ASSERT(sharedPainter ? sharedPainter->isActive() : true);
5141 QRegion toBePainted(rgn);
5142 if (asRoot && !alsoInvisible)
5143 toBePainted &= clipRect(); //(rgn & visibleRegion());
5144 if (!(flags & DontSubtractOpaqueChildren))
5145 subtractOpaqueChildren(toBePainted, q->rect());
5147 if (!toBePainted.isEmpty()) {
5148 bool onScreen = paintOnScreen();
5149 if (!onScreen || alsoOnScreen) {
5150 //update the "in paint event" flag
5151 if (q->testAttribute(Qt::WA_WState_InPaintEvent))
5152 qWarning("QWidget::repaint: Recursive repaint detected");
5153 q->setAttribute(Qt::WA_WState_InPaintEvent);
5155 //clip away the new area
5156 #ifndef QT_NO_PAINT_DEBUG
5157 bool flushed = QWidgetBackingStore::flushPaint(q, toBePainted);
5159 QPaintEngine *paintEngine = pdev->paintEngine();
5161 setRedirected(pdev, -offset);
5164 // (Alien support) Special case for Mac when redirecting: If the paint device
5165 // is of the Widget type we need to set WA_WState_InPaintEvent since painting
5166 // outside the paint event is not supported on QWidgets. The attributeis
5167 // restored further down.
5168 if (pdev->devType() == QInternal::Widget)
5169 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent);
5173 paintEngine->d_func()->systemClip = toBePainted;
5175 paintEngine->d_func()->systemRect = q->data->crect;
5177 //paint the background
5178 if ((asRoot || q->autoFillBackground() || onScreen || q->testAttribute(Qt::WA_StyledBackground))
5179 && !q->testAttribute(Qt::WA_OpaquePaintEvent) && !q->testAttribute(Qt::WA_NoSystemBackground)) {
5181 paintBackground(&p, toBePainted, (asRoot || onScreen) ? flags | DrawAsRoot : 0);
5185 paintEngine->d_func()->systemClip = toBePainted.translated(offset);
5187 if (!onScreen && !asRoot && !isOpaque && q->testAttribute(Qt::WA_TintedBackground)) {
5189 QColor tint = q->palette().window().color();
5190 tint.setAlphaF(qreal(.6));
5191 p.fillRect(toBePainted.boundingRect(), tint);
5196 qDebug() << "painting" << q << "opaque ==" << isOpaque();
5197 qDebug() << "clipping to" << toBePainted << "location == " << offset
5198 << "geometry ==" << QRect(q->mapTo(q->window(), QPoint(0, 0)), q->size());
5201 //actually send the paint event
5202 QPaintEvent e(toBePainted);
5203 QCoreApplication::sendSpontaneousEvent(q, &e);
5204 #if !defined(Q_WS_QPA)
5205 if (backingStore && !onScreen && !asRoot && (q->internalWinId() || !q->nativeParentWidget()->isWindow()))
5206 backingStore->markDirtyOnScreen(toBePainted, q, offset);
5212 if (pdev->devType() == QInternal::Widget)
5213 static_cast<QWidget *>(pdev)->setAttribute(Qt::WA_WState_InPaintEvent, false);
5215 restoreRedirected();
5217 paintEngine->d_func()->systemRect = QRect();
5219 paintEngine->d_func()->currentClipDevice = 0;
5220 paintEngine->d_func()->systemClip = QRegion();
5222 q->setAttribute(Qt::WA_WState_InPaintEvent, false);
5223 if (q->paintingActive() && !q->testAttribute(Qt::WA_PaintOutsidePaintEvent))
5224 qWarning("QWidget::repaint: It is dangerous to leave painters active on a widget outside of the PaintEvent");
5226 if (paintEngine && paintEngine->autoDestruct()) {
5230 #ifndef QT_NO_PAINT_DEBUG
5232 QWidgetBackingStore::unflushPaint(q, toBePainted);
5234 } else if (q->isWindow()) {
5235 QPaintEngine *engine = pdev->paintEngine();
5238 p.setClipRegion(toBePainted);
5239 const QBrush bg = q->palette().brush(QPalette::Window);
5240 if (bg.style() == Qt::TexturePattern)
5241 p.drawTiledPixmap(q->rect(), bg.texture());
5243 p.fillRect(q->rect(), bg);
5245 if (engine->autoDestruct())
5251 if (recursive && !children.isEmpty()) {
5252 paintSiblingsRecursive(pdev, children, children.size() - 1, rgn, offset, flags & ~DrawAsRoot
5253 , sharedPainter, backingStore);
5257 void QWidgetPrivate::render(QPaintDevice *target, const QPoint &targetOffset,
5258 const QRegion &sourceRegion, QWidget::RenderFlags renderFlags,
5262 qWarning("QWidget::render: null pointer to paint device");
5266 const bool inRenderWithPainter = extra && extra->inRenderWithPainter;
5267 QRegion paintRegion = !inRenderWithPainter && !readyToRender
5268 ? prepareToRender(sourceRegion, renderFlags)
5270 if (paintRegion.isEmpty())
5274 QPainter *oldSharedPainter = inRenderWithPainter ? sharedPainter() : 0;
5276 // Use the target's shared painter if set (typically set when doing
5277 // "other->render(widget);" in the widget's paintEvent.
5278 if (target->devType() == QInternal::Widget) {
5279 QWidgetPrivate *targetPrivate = static_cast<QWidget *>(target)->d_func();
5280 if (targetPrivate->extra && targetPrivate->extra->inRenderWithPainter) {
5281 QPainter *targetPainter = targetPrivate->sharedPainter();
5282 if (targetPainter && targetPainter->isActive())
5283 setSharedPainter(targetPainter);
5288 // Use the target's redirected device if set and adjust offset and paint
5289 // region accordingly. This is typically the case when people call render
5290 // from the paintEvent.
5291 QPoint offset = targetOffset;
5292 offset -= paintRegion.boundingRect().topLeft();
5293 QPoint redirectionOffset;
5294 QPaintDevice *redirected = 0;
5296 if (target->devType() == QInternal::Widget)
5297 redirected = static_cast<QWidget *>(target)->d_func()->redirected(&redirectionOffset);
5299 redirected = QPainter::redirected(target, &redirectionOffset);
5302 target = redirected;
5303 offset -= redirectionOffset;
5306 if (!inRenderWithPainter) { // Clip handled by shared painter (in qpainter.cpp).
5307 if (QPaintEngine *targetEngine = target->paintEngine()) {
5308 const QRegion targetSystemClip = targetEngine->systemClip();
5309 if (!targetSystemClip.isEmpty())
5310 paintRegion &= targetSystemClip.translated(-offset);
5314 // Set backingstore flags.
5315 int flags = DrawPaintOnScreen | DrawInvisible;
5316 if (renderFlags & QWidget::DrawWindowBackground)
5317 flags |= DrawAsRoot;
5319 if (renderFlags & QWidget::DrawChildren)
5320 flags |= DrawRecursive;
5322 flags |= DontSubtractOpaqueChildren;
5324 if (target->devType() == QInternal::Printer) {
5326 render_helper(&p, targetOffset, paintRegion, renderFlags);
5331 // Render via backingstore.
5332 drawWidget(target, paintRegion, offset, flags, sharedPainter());
5334 // Restore shared painter.
5335 if (oldSharedPainter)
5336 setSharedPainter(oldSharedPainter);
5338 // Render via backingstore (no shared painter).
5339 drawWidget(target, paintRegion, offset, flags, 0);
5343 void QWidgetPrivate::paintSiblingsRecursive(QPaintDevice *pdev, const QObjectList& siblings, int index, const QRegion &rgn,
5344 const QPoint &offset, int flags
5345 , QPainter *sharedPainter, QWidgetBackingStore *backingStore)
5349 bool dirtyBoundingRect = true;
5350 const bool exludeOpaqueChildren = (flags & DontDrawOpaqueChildren);
5351 const bool excludeNativeChildren = (flags & DontDrawNativeChildren);
5354 QWidget *x = qobject_cast<QWidget*>(siblings.at(index));
5355 if (x && !(exludeOpaqueChildren && x->d_func()->isOpaque) && !x->isHidden() && !x->isWindow()
5356 && !(excludeNativeChildren && x->internalWinId())) {
5357 if (dirtyBoundingRect) {
5358 boundingRect = rgn.boundingRect();
5359 dirtyBoundingRect = false;
5362 if (qRectIntersects(boundingRect, x->d_func()->effectiveRectFor(x->data->crect))) {
5368 } while (index >= 0);
5373 QWidgetPrivate *wd = w->d_func();
5374 const QPoint widgetPos(w->data->crect.topLeft());
5375 const bool hasMask = wd->extra && wd->extra->hasMask && !wd->graphicsEffect;
5379 wr -= hasMask ? wd->extra->mask.translated(widgetPos) : w->data->crect;
5380 paintSiblingsRecursive(pdev, siblings, --index, wr, offset, flags
5381 , sharedPainter, backingStore);
5384 if (w->updatesEnabled()
5385 #ifndef QT_NO_GRAPHICSVIEW
5386 && (!w->d_func()->extra || !w->d_func()->extra->proxyWidget)
5387 #endif //QT_NO_GRAPHICSVIEW
5389 QRegion wRegion(rgn);
5390 wRegion &= wd->effectiveRectFor(w->data->crect);
5391 wRegion.translate(-widgetPos);
5393 wRegion &= wd->extra->mask;
5394 wd->drawWidget(pdev, wRegion, offset + widgetPos, flags, sharedPainter, backingStore);
5398 #ifndef QT_NO_GRAPHICSEFFECT
5399 QRectF QWidgetEffectSourcePrivate::boundingRect(Qt::CoordinateSystem system) const
5401 if (system != Qt::DeviceCoordinates)
5402 return m_widget->rect();
5405 // Device coordinates without context not yet supported.
5406 qWarning("QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
5410 return context->painter->worldTransform().mapRect(m_widget->rect());
5413 void QWidgetEffectSourcePrivate::draw(QPainter *painter)
5415 if (!context || context->painter != painter) {
5416 m_widget->render(painter);
5420 // The region saved in the context is neither clipped to the rect
5421 // nor the mask, so we have to clip it here before calling drawWidget.
5422 QRegion toBePainted = context->rgn;
5423 toBePainted &= m_widget->rect();
5424 QWidgetPrivate *wd = qt_widget_private(m_widget);
5425 if (wd->extra && wd->extra->hasMask)
5426 toBePainted &= wd->extra->mask;
5428 wd->drawWidget(context->pdev, toBePainted, context->offset, context->flags,
5429 context->sharedPainter, context->backingStore);
5432 QPixmap QWidgetEffectSourcePrivate::pixmap(Qt::CoordinateSystem system, QPoint *offset,
5433 QGraphicsEffect::PixmapPadMode mode) const
5435 const bool deviceCoordinates = (system == Qt::DeviceCoordinates);
5436 if (!context && deviceCoordinates) {
5437 // Device coordinates without context not yet supported.
5438 qWarning("QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
5442 QPoint pixmapOffset;
5443 QRectF sourceRect = m_widget->rect();
5445 if (deviceCoordinates) {
5446 const QTransform &painterTransform = context->painter->worldTransform();
5447 sourceRect = painterTransform.mapRect(sourceRect);
5448 pixmapOffset = painterTransform.map(pixmapOffset);
5453 if (mode == QGraphicsEffect::PadToEffectiveBoundingRect)
5454 effectRect = m_widget->graphicsEffect()->boundingRectFor(sourceRect).toAlignedRect();
5455 else if (mode == QGraphicsEffect::PadToTransparentBorder)
5456 effectRect = sourceRect.adjusted(-1, -1, 1, 1).toAlignedRect();
5458 effectRect = sourceRect.toAlignedRect();
5461 *offset = effectRect.topLeft();
5463 pixmapOffset -= effectRect.topLeft();
5465 QPixmap pixmap(effectRect.size());
5466 pixmap.fill(Qt::transparent);
5467 m_widget->render(&pixmap, pixmapOffset, QRegion(), QWidget::DrawChildren);
5470 #endif //QT_NO_GRAPHICSEFFECT
5472 #ifndef QT_NO_GRAPHICSVIEW
5476 Finds the nearest widget embedded in a graphics proxy widget along the chain formed by this
5477 widget and its ancestors. The search starts at \a origin (inclusive).
5478 If successful, the function returns the proxy that embeds the widget, or 0 if no embedded
5481 QGraphicsProxyWidget * QWidgetPrivate::nearestGraphicsProxyWidget(const QWidget *origin)
5484 QWExtra *extra = origin->d_func()->extra;
5485 if (extra && extra->proxyWidget)
5486 return extra->proxyWidget;
5487 return nearestGraphicsProxyWidget(origin->parentWidget());
5494 \property QWidget::locale
5495 \brief the widget's locale
5498 As long as no special locale has been set, this is either
5499 the parent's locale or (if this widget is a top level widget),
5502 If the widget displays dates or numbers, these should be formatted
5503 using the widget's locale.
5505 \sa QLocale QLocale::setDefault()
5508 void QWidgetPrivate::setLocale_helper(const QLocale &loc, bool forceUpdate)
5511 if (locale == loc && !forceUpdate)
5516 if (!children.isEmpty()) {
5517 for (int i = 0; i < children.size(); ++i) {
5518 QWidget *w = qobject_cast<QWidget*>(children.at(i));
5521 if (w->testAttribute(Qt::WA_SetLocale))
5523 if (w->isWindow() && !w->testAttribute(Qt::WA_WindowPropagation))
5525 w->d_func()->setLocale_helper(loc, forceUpdate);
5528 QEvent e(QEvent::LocaleChange);
5529 QApplication::sendEvent(q, &e);
5532 void QWidget::setLocale(const QLocale &locale)
5536 setAttribute(Qt::WA_SetLocale);
5537 d->setLocale_helper(locale);
5540 QLocale QWidget::locale() const
5547 void QWidgetPrivate::resolveLocale()
5551 if (!q->testAttribute(Qt::WA_SetLocale)) {
5552 setLocale_helper(q->isWindow()
5554 : q->parentWidget()->locale());
5558 void QWidget::unsetLocale()
5561 setAttribute(Qt::WA_SetLocale, false);
5565 static QString constructWindowTitleFromFilePath(const QString &filePath)
5567 QFileInfo fi(filePath);
5568 QString windowTitle = fi.fileName() + QLatin1String("[*]");
5570 QString appName = QApplication::applicationName();
5571 if (!appName.isEmpty())
5572 windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName;
5578 \property QWidget::windowTitle
5579 \brief the window title (caption)
5581 This property only makes sense for top-level widgets, such as
5582 windows and dialogs. If no caption has been set, the title is based of the
5583 \l windowFilePath. If neither of these is set, then the title is
5586 If you use the \l windowModified mechanism, the window title must
5587 contain a "[*]" placeholder, which indicates where the '*' should
5588 appear. Normally, it should appear right after the file name
5589 (e.g., "document1.txt[*] - Text Editor"). If the \l
5590 windowModified property is false (the default), the placeholder
5593 \sa windowIcon, windowIconText, windowModified, windowFilePath
5595 QString QWidget::windowTitle() const
5598 if (d->extra && d->extra->topextra) {
5599 if (!d->extra->topextra->caption.isEmpty())
5600 return d->extra->topextra->caption;
5601 if (!d->extra->topextra->filePath.isEmpty())
5602 return constructWindowTitleFromFilePath(d->extra->topextra->filePath);
5608 Returns a modified window title with the [*] place holder
5609 replaced according to the rules described in QWidget::setWindowTitle
5611 This function assumes that "[*]" can be quoted by another
5612 "[*]", so it will replace two place holders by one and
5613 a single last one by either "*" or nothing depending on
5618 QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widget)
5623 extern QString qt_eval_adapt_window_title(const QString &title);
5624 QString cap = qt_eval_adapt_window_title(title);
5626 QString cap = title;
5632 QLatin1String placeHolder("[*]");
5633 int placeHolderLength = 3; // QLatin1String doesn't have length()
5635 int index = cap.indexOf(placeHolder);
5637 // here the magic begins
5638 while (index != -1) {
5639 index += placeHolderLength;
5641 while (cap.indexOf(placeHolder, index) == index) {
5643 index += placeHolderLength;
5646 if (count%2) { // odd number of [*] -> replace last one
5647 int lastIndex = cap.lastIndexOf(placeHolder, index - 1);
5648 if (widget->isWindowModified()
5649 && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget))
5650 cap.replace(lastIndex, 3, QWidget::tr("*"));
5652 cap.remove(lastIndex, 3);
5655 index = cap.indexOf(placeHolder, index);
5658 cap.replace(QLatin1String("[*][*]"), placeHolder);
5663 void QWidgetPrivate::setWindowTitle_helper(const QString &title)
5666 if (q->testAttribute(Qt::WA_WState_Created))
5667 setWindowTitle_sys(qt_setWindowTitle_helperHelper(title, q));
5670 void QWidgetPrivate::setWindowIconText_helper(const QString &title)
5673 if (q->testAttribute(Qt::WA_WState_Created))
5674 setWindowIconText_sys(qt_setWindowTitle_helperHelper(title, q));
5677 void QWidget::setWindowIconText(const QString &iconText)
5679 if (QWidget::windowIconText() == iconText)
5683 d->topData()->iconText = iconText;
5684 d->setWindowIconText_helper(iconText);
5686 QEvent e(QEvent::IconTextChange);
5687 QApplication::sendEvent(this, &e);
5690 void QWidget::setWindowTitle(const QString &title)
5692 if (QWidget::windowTitle() == title && !title.isEmpty() && !title.isNull())
5696 d->topData()->caption = title;
5697 d->setWindowTitle_helper(title);
5699 QEvent e(QEvent::WindowTitleChange);
5700 QApplication::sendEvent(this, &e);
5705 \property QWidget::windowIcon
5706 \brief the widget's icon
5708 This property only makes sense for windows. If no icon
5709 has been set, windowIcon() returns the application icon
5710 (QApplication::windowIcon()).
5712 \sa windowIconText, windowTitle
5714 QIcon QWidget::windowIcon() const
5716 const QWidget *w = this;
5718 const QWidgetPrivate *d = w->d_func();
5719 if (d->extra && d->extra->topextra && d->extra->topextra->icon)
5720 return *d->extra->topextra->icon;
5721 w = w->parentWidget();
5723 return QApplication::windowIcon();
5726 void QWidgetPrivate::setWindowIcon_helper()
5728 QEvent e(QEvent::WindowIconChange);
5729 QApplication::sendEvent(q_func(), &e);
5730 for (int i = 0; i < children.size(); ++i) {
5731 QWidget *w = qobject_cast<QWidget *>(children.at(i));
5732 if (w && !w->isWindow())
5733 QApplication::sendEvent(w, &e);
5737 void QWidget::setWindowIcon(const QIcon &icon)
5741 setAttribute(Qt::WA_SetWindowIcon, !icon.isNull());
5744 if (!d->extra->topextra->icon)
5745 d->extra->topextra->icon = new QIcon();
5746 *d->extra->topextra->icon = icon;
5748 delete d->extra->topextra->iconPixmap;
5749 d->extra->topextra->iconPixmap = 0;
5751 d->setWindowIcon_sys();
5752 d->setWindowIcon_helper();
5757 \property QWidget::windowIconText
5758 \brief the widget's icon text
5760 This property only makes sense for windows. If no icon
5761 text has been set, this functions returns an empty string.
5763 \sa windowIcon, windowTitle
5766 QString QWidget::windowIconText() const
5769 return (d->extra && d->extra->topextra) ? d->extra->topextra->iconText : QString();
5773 \property QWidget::windowFilePath
5775 \brief the file path associated with a widget
5777 This property only makes sense for windows. It associates a file path with
5778 a window. If you set the file path, but have not set the window title, Qt
5779 sets the window title to contain a string created using the following
5785 \o The file name of the specified path, obtained using QFileInfo::fileName().
5791 \o The file name of the specified path, obtained using QFileInfo::fileName().
5792 \o An optional \c{*} character, if the \l windowModified property is set.
5793 \o The \c{0x2014} unicode character, padded either side by spaces.
5794 \o The application name, obtained from the application's
5795 \l{QCoreApplication::}{applicationName} property.
5798 If the window title is set at any point, then the window title takes precedence and
5799 will be shown instead of the file path string.
5801 Additionally, on Mac OS X, this has an added benefit that it sets the
5802 \l{http://developer.apple.com/documentation/UserExperience/Conceptual/OSXHIGuidelines/XHIGWindows/chapter_17_section_3.html}{proxy icon}
5803 for the window, assuming that the file path exists.
5805 If no file path is set, this property contains an empty string.
5807 By default, this property contains an empty string.
5809 \sa windowTitle, windowIcon
5812 QString QWidget::windowFilePath() const
5815 return (d->extra && d->extra->topextra) ? d->extra->topextra->filePath : QString();
5818 void QWidget::setWindowFilePath(const QString &filePath)
5820 if (filePath == windowFilePath())
5826 d->extra->topextra->filePath = filePath;
5827 d->setWindowFilePath_helper(filePath);
5830 void QWidgetPrivate::setWindowFilePath_helper(const QString &filePath)
5832 if (extra->topextra && extra->topextra->caption.isEmpty()) {
5834 setWindowTitle_helper(QFileInfo(filePath).fileName());
5838 setWindowTitle_helper(q->windowTitle());
5842 setWindowFilePath_sys(filePath);
5847 Returns the window's role, or an empty string.
5849 \sa windowIcon, windowTitle
5852 QString QWidget::windowRole() const
5855 return (d->extra && d->extra->topextra) ? d->extra->topextra->role : QString();
5859 Sets the window's role to \a role. This only makes sense for
5862 void QWidget::setWindowRole(const QString &role)
5864 #if defined(Q_WS_X11)
5866 d->topData()->role = role;
5874 \property QWidget::mouseTracking
5875 \brief whether mouse tracking is enabled for the widget
5877 If mouse tracking is disabled (the default), the widget only
5878 receives mouse move events when at least one mouse button is
5879 pressed while the mouse is being moved.
5881 If mouse tracking is enabled, the widget receives mouse move
5882 events even if no buttons are pressed.
5884 \sa mouseMoveEvent()
5889 Sets the widget's focus proxy to widget \a w. If \a w is 0, the
5890 function resets this widget to have no focus proxy.
5892 Some widgets can "have focus", but create a child widget, such as
5893 QLineEdit, to actually handle the focus. In this case, the widget
5894 can set the line edit to be its focus proxy.
5896 setFocusProxy() sets the widget which will actually get focus when
5897 "this widget" gets it. If there is a focus proxy, setFocus() and
5898 hasFocus() operate on the focus proxy.
5903 void QWidget::setFocusProxy(QWidget * w)
5906 if (!w && !d->extra)
5909 for (QWidget* fp = w; fp; fp = fp->focusProxy()) {
5911 qWarning("QWidget: %s (%s) already in focus proxy chain", metaObject()->className(), objectName().toLocal8Bit().constData());
5917 d->extra->focus_proxy = w;
5922 Returns the focus proxy, or 0 if there is no focus proxy.
5927 QWidget * QWidget::focusProxy() const
5930 return d->extra ? (QWidget *)d->extra->focus_proxy : 0;
5935 \property QWidget::focus
5936 \brief whether this widget (or its focus proxy) has the keyboard
5939 By default, this property is false.
5941 \note Obtaining the value of this property for a widget is effectively equivalent
5942 to checking whether QApplication::focusWidget() refers to the widget.
5944 \sa setFocus(), clearFocus(), setFocusPolicy(), QApplication::focusWidget()
5946 bool QWidget::hasFocus() const
5948 const QWidget* w = this;
5949 while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
5950 w = w->d_func()->extra->focus_proxy;
5951 if (QWidget *window = w->window()) {
5952 #ifndef QT_NO_GRAPHICSVIEW
5953 QWExtra *e = window->d_func()->extra;
5954 if (e && e->proxyWidget && e->proxyWidget->hasFocus() && window->focusWidget() == w)
5958 return (QApplication::focusWidget() == w);
5962 Gives the keyboard input focus to this widget (or its focus
5963 proxy) if this widget or one of its parents is the \link
5964 isActiveWindow() active window\endlink. The \a reason argument will
5965 be passed into any focus event sent from this function, it is used
5966 to give an explanation of what caused the widget to get focus.
5967 If the window is not active, the widget will be given the focus when
5968 the window becomes active.
5970 First, a focus out event is sent to the focus widget (if any) to
5971 tell it that it is about to lose the focus. Then a focus in event
5972 is sent to this widget to tell it that it just received the focus.
5973 (Nothing happens if the focus in and focus out widgets are the
5976 \note On embedded platforms, setFocus() will not cause an input panel
5977 to be opened by the input method. If you want this to happen, you
5978 have to send a QEvent::RequestSoftwareInputPanel event to the
5981 setFocus() gives focus to a widget regardless of its focus policy,
5982 but does not clear any keyboard grab (see grabKeyboard()).
5984 Be aware that if the widget is hidden, it will not accept focus
5987 \warning If you call setFocus() in a function which may itself be
5988 called from focusOutEvent() or focusInEvent(), you may get an
5991 \sa hasFocus(), clearFocus(), focusInEvent(), focusOutEvent(),
5992 setFocusPolicy(), focusWidget(), QApplication::focusWidget(), grabKeyboard(),
5993 grabMouse(), {Keyboard Focus}, QEvent::RequestSoftwareInputPanel
5996 void QWidget::setFocus(Qt::FocusReason reason)
6002 while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
6003 f = f->d_func()->extra->focus_proxy;
6005 if (QApplication::focusWidget() == f
6006 #if defined(Q_WS_WIN)
6007 && GetFocus() == f->internalWinId()
6012 #ifndef QT_NO_GRAPHICSVIEW
6013 QWidget *previousProxyFocus = 0;
6014 if (QWExtra *topData = window()->d_func()->extra) {
6015 if (topData->proxyWidget && topData->proxyWidget->hasFocus()) {
6016 previousProxyFocus = topData->proxyWidget->widget()->focusWidget();
6017 if (previousProxyFocus && previousProxyFocus->focusProxy())
6018 previousProxyFocus = previousProxyFocus->focusProxy();
6019 if (previousProxyFocus == this && !topData->proxyWidget->d_func()->proxyIsGivingFocus)
6027 while (w && w->isHidden()) {
6028 w->d_func()->focus_child = f;
6029 w = w->isWindow() ? 0 : w->parentWidget();
6033 w->d_func()->focus_child = f;
6034 w = w->isWindow() ? 0 : w->parentWidget();
6038 #ifndef QT_NO_GRAPHICSVIEW
6039 // Update proxy state
6040 if (QWExtra *topData = window()->d_func()->extra) {
6041 if (topData->proxyWidget && !topData->proxyWidget->hasFocus()) {
6042 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 1;
6043 topData->proxyWidget->setFocus(reason);
6044 topData->proxyWidget->d_func()->focusFromWidgetToProxy = 0;
6049 if (f->isActiveWindow()) {
6050 QApplicationPrivate::setFocusWidget(f, reason);
6051 #ifndef QT_NO_ACCESSIBILITY
6053 // The negation of the condition in setFocus_sys
6054 if (!(testAttribute(Qt::WA_WState_Created) && window()->windowType() != Qt::Popup && internalWinId()))
6055 //setFocusWidget will already post a focus event for us (that the AT client receives) on Windows
6058 // menus update the focus manually and this would create bogus events
6059 if (!(f->inherits("QMenuBar") || f->inherits("QMenu") || f->inherits("QMenuItem")))
6061 QAccessible::updateAccessibility(f, 0, QAccessible::Focus);
6063 #ifndef QT_NO_GRAPHICSVIEW
6064 if (QWExtra *topData = window()->d_func()->extra) {
6065 if (topData->proxyWidget) {
6066 if (previousProxyFocus && previousProxyFocus != f) {
6067 // Send event to self
6068 QFocusEvent event(QEvent::FocusOut, reason);
6069 QPointer<QWidget> that = previousProxyFocus;
6070 QApplication::sendEvent(previousProxyFocus, &event);
6072 QApplication::sendEvent(that->style(), &event);
6075 #ifndef QT_NO_GRAPHICSVIEW
6076 // Update proxy state
6077 if (QWExtra *topData = window()->d_func()->extra)
6078 if (topData->proxyWidget && topData->proxyWidget->hasFocus())
6079 topData->proxyWidget->d_func()->updateProxyInputMethodAcceptanceFromWidget();
6081 // Send event to self
6082 QFocusEvent event(QEvent::FocusIn, reason);
6083 QPointer<QWidget> that = f;
6084 QApplication::sendEvent(f, &event);
6086 QApplication::sendEvent(that->style(), &event);
6095 \fn void QWidget::setFocus()
6098 Gives the keyboard input focus to this widget (or its focus
6099 proxy) if this widget or one of its parents is the
6100 \l{isActiveWindow()}{active window}.
6104 Takes keyboard input focus from the widget.
6106 If the widget has active focus, a \link focusOutEvent() focus out
6107 event\endlink is sent to this widget to tell it that it is about
6110 This widget must enable focus setting in order to get the keyboard
6111 input focus, i.e. it must call setFocusPolicy().
6113 \sa hasFocus(), setFocus(), focusInEvent(), focusOutEvent(),
6114 setFocusPolicy(), QApplication::focusWidget()
6117 void QWidget::clearFocus()
6121 if (w->d_func()->focus_child == this)
6122 w->d_func()->focus_child = 0;
6123 w = w->parentWidget();
6125 #ifndef QT_NO_GRAPHICSVIEW
6126 QWExtra *topData = d_func()->extra;
6127 if (topData && topData->proxyWidget)
6128 topData->proxyWidget->clearFocus();
6132 // Update proxy state
6133 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
6134 #if defined(Q_WS_WIN)
6135 if (!(windowType() == Qt::Popup) && GetFocus() == internalWinId())
6140 #ifndef QT_NO_ACCESSIBILITY
6141 QAccessible::updateAccessibility(this, 0, QAccessible::Focus);
6149 \fn bool QWidget::focusNextChild()
6151 Finds a new widget to give the keyboard focus to, as appropriate
6152 for \key Tab, and returns true if it can find a new widget, or
6155 \sa focusPreviousChild()
6159 \fn bool QWidget::focusPreviousChild()
6161 Finds a new widget to give the keyboard focus to, as appropriate
6162 for \key Shift+Tab, and returns true if it can find a new widget,
6163 or false if it can't.
6165 \sa focusNextChild()
6169 Finds a new widget to give the keyboard focus to, as appropriate
6170 for Tab and Shift+Tab, and returns true if it can find a new
6171 widget, or false if it can't.
6173 If \a next is true, this function searches forward, if \a next
6174 is false, it searches backward.
6176 Sometimes, you will want to reimplement this function. For
6177 example, a web browser might reimplement it to move its "current
6178 active link" forward or backward, and call
6179 focusNextPrevChild() only when it reaches the last or
6180 first link on the "page".
6182 Child widgets call focusNextPrevChild() on their parent widgets,
6183 but only the window that contains the child widgets decides where
6184 to redirect focus. By reimplementing this function for an object,
6185 you thus gain control of focus traversal for all child widgets.
6187 \sa focusNextChild(), focusPreviousChild()
6190 bool QWidget::focusNextPrevChild(bool next)
6193 QWidget* p = parentWidget();
6194 bool isSubWindow = (windowType() == Qt::SubWindow);
6195 if (!isWindow() && !isSubWindow && p)
6196 return p->focusNextPrevChild(next);
6197 #ifndef QT_NO_GRAPHICSVIEW
6198 if (d->extra && d->extra->proxyWidget)
6199 return d->extra->proxyWidget->focusNextPrevChild(next);
6201 QWidget *w = QApplicationPrivate::focusNextPrevChild_helper(this, next);
6202 if (!w) return false;
6204 w->setFocus(next ? Qt::TabFocusReason : Qt::BacktabFocusReason);
6209 Returns the last child of this widget that setFocus had been
6210 called on. For top level widgets this is the widget that will get
6211 focus in case this window gets activated
6213 This is not the same as QApplication::focusWidget(), which returns
6214 the focus widget in the currently active window.
6217 QWidget *QWidget::focusWidget() const
6219 return const_cast<QWidget *>(d_func()->focus_child);
6223 Returns the next widget in this widget's focus chain.
6225 \sa previousInFocusChain()
6227 QWidget *QWidget::nextInFocusChain() const
6229 return const_cast<QWidget *>(d_func()->focus_next);
6233 \brief The previousInFocusChain function returns the previous
6234 widget in this widget's focus chain.
6236 \sa nextInFocusChain()
6240 QWidget *QWidget::previousInFocusChain() const
6242 return const_cast<QWidget *>(d_func()->focus_prev);
6246 \property QWidget::isActiveWindow
6247 \brief whether this widget's window is the active window
6249 The active window is the window that contains the widget that has
6250 keyboard focus (The window may still have focus if it has no
6251 widgets or none of its widgets accepts keyboard focus).
6253 When popup windows are visible, this property is true for both the
6254 active window \e and for the popup.
6256 By default, this property is false.
6258 \sa activateWindow(), QApplication::activeWindow()
6260 bool QWidget::isActiveWindow() const
6262 QWidget *tlw = window();
6263 if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup)))
6266 #ifndef QT_NO_GRAPHICSVIEW
6267 if (QWExtra *tlwExtra = tlw->d_func()->extra) {
6268 if (isVisible() && tlwExtra->proxyWidget)
6269 return tlwExtra->proxyWidget->isActiveWindow();
6274 extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
6275 if(qt_mac_is_macdrawer(tlw) &&
6276 tlw->parentWidget() && tlw->parentWidget()->isActiveWindow())
6279 extern bool qt_mac_insideKeyWindow(const QWidget *); //qwidget_mac.cpp
6280 if (QApplication::testAttribute(Qt::AA_MacPluginApplication) && qt_mac_insideKeyWindow(tlw))
6283 if(style()->styleHint(QStyle::SH_Widget_ShareActivation, 0, this)) {
6284 if(tlw->windowType() == Qt::Tool &&
6286 (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow()))
6288 QWidget *w = QApplication::activeWindow();
6289 while(w && tlw->windowType() == Qt::Tool &&
6290 !w->isModal() && w->parentWidget()) {
6291 w = w->parentWidget()->window();
6296 #if defined(Q_WS_WIN32)
6297 HWND active = GetActiveWindow();
6298 if (!tlw->testAttribute(Qt::WA_WState_Created))
6300 return active == tlw->internalWinId() || ::IsChild(active, tlw->internalWinId());
6307 Puts the \a second widget after the \a first widget in the focus order.
6309 Note that since the tab order of the \a second widget is changed, you
6310 should order a chain like this:
6312 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 9
6316 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 10
6318 If \a first or \a second has a focus proxy, setTabOrder()
6319 correctly substitutes the proxy.
6321 \sa setFocusPolicy(), setFocusProxy(), {Keyboard Focus}
6323 void QWidget::setTabOrder(QWidget* first, QWidget *second)
6325 if (!first || !second || first->focusPolicy() == Qt::NoFocus || second->focusPolicy() == Qt::NoFocus)
6328 if (first->window() != second->window()) {
6329 qWarning("QWidget::setTabOrder: 'first' and 'second' must be in the same window");
6333 QWidget *fp = first->focusProxy();
6335 // If first is redirected, set first to the last child of first
6336 // that can take keyboard focus so that second is inserted after
6337 // that last child, and the focus order within first is (more
6338 // likely to be) preserved.
6339 QList<QWidget *> l = first->findChildren<QWidget *>();
6340 for (int i = l.size()-1; i >= 0; --i) {
6341 QWidget * next = l.at(i);
6342 if (next->window() == fp->window()) {
6344 if (fp->focusPolicy() != Qt::NoFocus)
6354 if (QWidget *sp = second->focusProxy())
6357 // QWidget *fp = first->d_func()->focus_prev;
6358 QWidget *fn = first->d_func()->focus_next;
6360 if (fn == second || first == second)
6363 QWidget *sp = second->d_func()->focus_prev;
6364 QWidget *sn = second->d_func()->focus_next;
6366 fn->d_func()->focus_prev = second;
6367 first->d_func()->focus_next = second;
6369 second->d_func()->focus_next = fn;
6370 second->d_func()->focus_prev = first;
6372 sp->d_func()->focus_next = sn;
6373 sn->d_func()->focus_prev = sp;
6376 Q_ASSERT(first->d_func()->focus_next->d_func()->focus_prev == first);
6377 Q_ASSERT(first->d_func()->focus_prev->d_func()->focus_next == first);
6379 Q_ASSERT(second->d_func()->focus_next->d_func()->focus_prev == second);
6380 Q_ASSERT(second->d_func()->focus_prev->d_func()->focus_next == second);
6385 Moves the relevant subwidgets of this widget from the \a oldtlw's
6386 tab chain to that of the new parent, if there's anything to move and
6389 This function is called from QWidget::reparent() *after* the widget
6390 has been reparented.
6395 void QWidgetPrivate::reparentFocusWidgets(QWidget * oldtlw)
6398 if (oldtlw == q->window())
6399 return; // nothing to do
6402 focus_child->clearFocus();
6404 // separate the focus chain into new (children of myself) and old (the rest)
6405 QWidget *firstOld = 0;
6406 //QWidget *firstNew = q; //invariant
6407 QWidget *o = 0; // last in the old list
6408 QWidget *n = q; // last in the new list
6410 bool prevWasNew = true;
6411 QWidget *w = focus_next;
6413 //Note: for efficiency, we do not maintain the list invariant inside the loop
6414 //we append items to the relevant list, and we optimize by not changing pointers
6415 //when subsequent items are going into the same list.
6417 bool currentIsNew = q->isAncestorOf(w);
6420 //prev was old -- append to new list
6421 n->d_func()->focus_next = w;
6422 w->d_func()->focus_prev = n;
6427 //prev was new -- append to old list, if there is one
6429 o->d_func()->focus_next = w;
6430 w->d_func()->focus_prev = o;
6432 // "create" the old list
6438 w = w->d_func()->focus_next;
6439 prevWasNew = currentIsNew;
6442 //repair the old list:
6444 o->d_func()->focus_next = firstOld;
6445 firstOld->d_func()->focus_prev = o;
6448 if (!q->isWindow()) {
6449 QWidget *topLevel = q->window();
6450 //insert new chain into toplevel's chain
6452 QWidget *prev = topLevel->d_func()->focus_prev;
6454 topLevel->d_func()->focus_prev = n;
6455 prev->d_func()->focus_next = q;
6458 n->d_func()->focus_next = topLevel;
6460 //repair the new list
6461 n->d_func()->focus_next = q;
6469 Measures the shortest distance from a point to a rect.
6471 This function is called from QDesktopwidget::screen(QPoint) to find the
6472 closest screen for a point.
6473 In directional KeypadNavigation, it is called to find the closest
6474 widget to the current focus widget center.
6476 int QWidgetPrivate::pointToRect(const QPoint &p, const QRect &r)
6480 if (p.x() < r.left())
6481 dx = r.left() - p.x();
6482 else if (p.x() > r.right())
6483 dx = p.x() - r.right();
6484 if (p.y() < r.top())
6485 dy = r.top() - p.y();
6486 else if (p.y() > r.bottom())
6487 dy = p.y() - r.bottom();
6492 \property QWidget::frameSize
6493 \brief the size of the widget including any window frame
6495 By default, this property contains a value that depends on the user's
6496 platform and screen geometry.
6498 QSize QWidget::frameSize() const
6501 if (isWindow() && !(windowType() == Qt::Popup)) {
6502 QRect fs = d->frameStrut();
6503 return QSize(data->crect.width() + fs.left() + fs.right(),
6504 data->crect.height() + fs.top() + fs.bottom());
6506 return data->crect.size();
6509 /*! \fn void QWidget::move(int x, int y)
6513 This corresponds to move(QPoint(\a x, \a y)).
6516 void QWidget::move(const QPoint &p)
6519 setAttribute(Qt::WA_Moved);
6521 d->topData()->posFromMove = true;
6522 if (testAttribute(Qt::WA_WState_Created)) {
6523 d->setGeometry_sys(p.x() + geometry().x() - QWidget::x(),
6524 p.y() + geometry().y() - QWidget::y(),
6525 width(), height(), true);
6526 d->setDirtyOpaqueRegion();
6528 data->crect.moveTopLeft(p); // no frame yet
6529 setAttribute(Qt::WA_PendingMoveEvent);
6533 /*! \fn void QWidget::resize(int w, int h)
6536 This corresponds to resize(QSize(\a w, \a h)).
6539 void QWidget::resize(const QSize &s)
6542 setAttribute(Qt::WA_Resized);
6543 if (testAttribute(Qt::WA_WState_Created)) {
6544 d->setGeometry_sys(geometry().x(), geometry().y(), s.width(), s.height(), false);
6545 d->setDirtyOpaqueRegion();
6547 data->crect.setSize(s.boundedTo(maximumSize()).expandedTo(minimumSize()));
6548 setAttribute(Qt::WA_PendingResizeEvent);
6552 void QWidget::setGeometry(const QRect &r)
6555 setAttribute(Qt::WA_Resized);
6556 setAttribute(Qt::WA_Moved);
6558 d->topData()->posFromMove = false;
6559 if (testAttribute(Qt::WA_WState_Created)) {
6560 d->setGeometry_sys(r.x(), r.y(), r.width(), r.height(), true);
6561 d->setDirtyOpaqueRegion();
6563 data->crect.setTopLeft(r.topLeft());
6564 data->crect.setSize(r.size().boundedTo(maximumSize()).expandedTo(minimumSize()));
6565 setAttribute(Qt::WA_PendingMoveEvent);
6566 setAttribute(Qt::WA_PendingResizeEvent);
6572 Saves the current geometry and state for top-level widgets.
6574 To save the geometry when the window closes, you can
6575 implement a close event like this:
6577 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 11
6579 See the \l{Window Geometry} documentation for an overview of geometry
6580 issues with windows.
6582 Use QMainWindow::saveState() to save the geometry and the state of
6583 toolbars and dock widgets.
6585 \sa restoreGeometry(), QMainWindow::saveState(), QMainWindow::restoreState()
6587 QByteArray QWidget::saveGeometry() const
6590 // We check if the window was maximized during this invocation. If so, we need to record the
6591 // starting position as 0,0.
6593 QRect newFramePosition = frameGeometry();
6594 QRect newNormalPosition = normalGeometry();
6595 if(d->topData()->wasMaximized && !(windowState() & Qt::WindowMaximized)) {
6596 // Change the starting position
6597 newFramePosition.moveTo(0, 0);
6598 newNormalPosition.moveTo(0, 0);
6602 QDataStream stream(&array, QIODevice::WriteOnly);
6603 stream.setVersion(QDataStream::Qt_4_0);
6604 const quint32 magicNumber = 0x1D9D0CB;
6605 quint16 majorVersion = 1;
6606 quint16 minorVersion = 0;
6607 stream << magicNumber
6612 << newNormalPosition
6614 << qint32(QApplication::desktop()->screenNumber(this))
6615 << quint8(windowState() & Qt::WindowMaximized)
6616 << quint8(windowState() & Qt::WindowFullScreen);
6623 Restores the geometry and state top-level widgets stored in the
6624 byte array \a geometry. Returns true on success; otherwise
6627 If the restored geometry is off-screen, it will be modified to be
6628 inside the available screen geometry.
6630 To restore geometry saved using QSettings, you can use code like
6633 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 12
6635 See the \l{Window Geometry} documentation for an overview of geometry
6636 issues with windows.
6638 Use QMainWindow::restoreState() to restore the geometry and the
6639 state of toolbars and dock widgets.
6641 \sa saveGeometry(), QSettings, QMainWindow::saveState(), QMainWindow::restoreState()
6643 bool QWidget::restoreGeometry(const QByteArray &geometry)
6645 if (geometry.size() < 4)
6647 QDataStream stream(geometry);
6648 stream.setVersion(QDataStream::Qt_4_0);
6650 const quint32 magicNumber = 0x1D9D0CB;
6651 quint32 storedMagicNumber;
6652 stream >> storedMagicNumber;
6653 if (storedMagicNumber != magicNumber)
6656 const quint16 currentMajorVersion = 1;
6657 quint16 majorVersion = 0;
6658 quint16 minorVersion = 0;
6660 stream >> majorVersion >> minorVersion;
6662 if (majorVersion != currentMajorVersion)
6664 // (Allow all minor versions.)
6666 QRect restoredFrameGeometry;
6667 QRect restoredNormalGeometry;
6668 qint32 restoredScreenNumber;
6672 stream >> restoredFrameGeometry
6673 >> restoredNormalGeometry
6674 >> restoredScreenNumber
6678 const int frameHeight = 20;
6679 if (!restoredFrameGeometry.isValid())
6680 restoredFrameGeometry = QRect(QPoint(0,0), sizeHint());
6682 if (!restoredNormalGeometry.isValid())
6683 restoredNormalGeometry = QRect(QPoint(0, frameHeight), sizeHint());
6684 if (!restoredNormalGeometry.isValid()) {
6685 // use the widget's adjustedSize if the sizeHint() doesn't help
6686 restoredNormalGeometry.setSize(restoredNormalGeometry
6688 .expandedTo(d_func()->adjustedSize()));
6691 const QDesktopWidget * const desktop = QApplication::desktop();
6692 if (restoredScreenNumber >= desktop->numScreens())
6693 restoredScreenNumber = desktop->primaryScreen();
6695 const QRect availableGeometry = desktop->availableGeometry(restoredScreenNumber);
6697 // Modify the restored geometry if we are about to restore to coordinates
6698 // that would make the window "lost". This happens if:
6699 // - The restored geometry is completely oustside the available geometry
6700 // - The title bar is outside the available geometry.
6701 // - (Mac only) The window is higher than the available geometry. It must
6702 // be possible to bring the size grip on screen by moving the window.
6704 restoredFrameGeometry.setHeight(qMin(restoredFrameGeometry.height(), availableGeometry.height()));
6705 restoredNormalGeometry.setHeight(qMin(restoredNormalGeometry.height(), availableGeometry.height() - frameHeight));
6708 if (!restoredFrameGeometry.intersects(availableGeometry)) {
6709 restoredFrameGeometry.moveBottom(qMin(restoredFrameGeometry.bottom(), availableGeometry.bottom()));
6710 restoredFrameGeometry.moveLeft(qMax(restoredFrameGeometry.left(), availableGeometry.left()));
6711 restoredFrameGeometry.moveRight(qMin(restoredFrameGeometry.right(), availableGeometry.right()));
6713 restoredFrameGeometry.moveTop(qMax(restoredFrameGeometry.top(), availableGeometry.top()));
6715 if (!restoredNormalGeometry.intersects(availableGeometry)) {
6716 restoredNormalGeometry.moveBottom(qMin(restoredNormalGeometry.bottom(), availableGeometry.bottom()));
6717 restoredNormalGeometry.moveLeft(qMax(restoredNormalGeometry.left(), availableGeometry.left()));
6718 restoredNormalGeometry.moveRight(qMin(restoredNormalGeometry.right(), availableGeometry.right()));
6720 restoredNormalGeometry.moveTop(qMax(restoredNormalGeometry.top(), availableGeometry.top() + frameHeight));
6722 if (maximized || fullScreen) {
6723 // set geomerty before setting the window state to make
6724 // sure the window is maximized to the right screen.
6725 // Skip on windows: the window is restored into a broken
6726 // half-maximized state.
6728 setGeometry(restoredNormalGeometry);
6730 Qt::WindowStates ws = windowState();
6732 ws |= Qt::WindowMaximized;
6734 ws |= Qt::WindowFullScreen;
6736 d_func()->topData()->normalGeometry = restoredNormalGeometry;
6741 offset = d_func()->topData()->fullScreenOffset;
6743 setWindowState(windowState() & ~(Qt::WindowMaximized | Qt::WindowFullScreen));
6744 move(restoredFrameGeometry.topLeft() + offset);
6745 resize(restoredNormalGeometry.size());
6750 /*!\fn void QWidget::setGeometry(int x, int y, int w, int h)
6753 This corresponds to setGeometry(QRect(\a x, \a y, \a w, \a h)).
6757 Sets the margins around the contents of the widget to have the sizes
6758 \a left, \a top, \a right, and \a bottom. The margins are used by
6759 the layout system, and may be used by subclasses to specify the area
6760 to draw in (e.g. excluding the frame).
6762 Changing the margins will trigger a resizeEvent().
6764 \sa contentsRect(), getContentsMargins()
6766 void QWidget::setContentsMargins(int left, int top, int right, int bottom)
6769 if (left == d->leftmargin && top == d->topmargin
6770 && right == d->rightmargin && bottom == d->bottommargin)
6772 d->leftmargin = left;
6774 d->rightmargin = right;
6775 d->bottommargin = bottom;
6777 if (QLayout *l=d->layout)
6778 l->update(); //force activate; will do updateGeometry
6782 // ### Qt 5: compat, remove
6785 QResizeEvent e(data->crect.size(), data->crect.size());
6786 QApplication::sendEvent(this, &e);
6788 setAttribute(Qt::WA_PendingResizeEvent, true);
6791 QEvent e(QEvent::ContentsRectChange);
6792 QApplication::sendEvent(this, &e);
6799 \brief The setContentsMargins function sets the margins around the
6802 Sets the margins around the contents of the widget to have the
6803 sizes determined by \a margins. The margins are
6804 used by the layout system, and may be used by subclasses to
6805 specify the area to draw in (e.g. excluding the frame).
6807 Changing the margins will trigger a resizeEvent().
6809 \sa contentsRect(), getContentsMargins()
6811 void QWidget::setContentsMargins(const QMargins &margins)
6813 setContentsMargins(margins.left(), margins.top(),
6814 margins.right(), margins.bottom());
6818 Returns the widget's contents margins for \a left, \a top, \a
6819 right, and \a bottom.
6821 \sa setContentsMargins(), contentsRect()
6823 void QWidget::getContentsMargins(int *left, int *top, int *right, int *bottom) const
6827 *left = d->leftmargin;
6829 *top = d->topmargin;
6831 *right = d->rightmargin;
6833 *bottom = d->bottommargin;
6839 \brief The contentsMargins function returns the widget's contents margins.
6841 \sa getContentsMargins(), setContentsMargins(), contentsRect()
6843 QMargins QWidget::contentsMargins() const
6846 return QMargins(d->leftmargin, d->topmargin, d->rightmargin, d->bottommargin);
6851 Returns the area inside the widget's margins.
6853 \sa setContentsMargins(), getContentsMargins()
6855 QRect QWidget::contentsRect() const
6858 return QRect(QPoint(d->leftmargin, d->topmargin),
6859 QPoint(data->crect.width() - 1 - d->rightmargin,
6860 data->crect.height() - 1 - d->bottommargin));
6867 \fn void QWidget::customContextMenuRequested(const QPoint &pos)
6869 This signal is emitted when the widget's \l contextMenuPolicy is
6870 Qt::CustomContextMenu, and the user has requested a context menu on
6871 the widget. The position \a pos is the position of the context menu
6872 event that the widget receives. Normally this is in widget
6873 coordinates. The exception to this rule is QAbstractScrollArea and
6874 its subclasses that map the context menu event to coordinates of the
6875 \link QAbstractScrollArea::viewport() viewport() \endlink .
6878 \sa mapToGlobal() QMenu contextMenuPolicy
6883 \property QWidget::contextMenuPolicy
6884 \brief how the widget shows a context menu
6886 The default value of this property is Qt::DefaultContextMenu,
6887 which means the contextMenuEvent() handler is called. Other values
6888 are Qt::NoContextMenu, Qt::PreventContextMenu,
6889 Qt::ActionsContextMenu, and Qt::CustomContextMenu. With
6890 Qt::CustomContextMenu, the signal customContextMenuRequested() is
6893 \sa contextMenuEvent(), customContextMenuRequested(), actions()
6896 Qt::ContextMenuPolicy QWidget::contextMenuPolicy() const
6898 return (Qt::ContextMenuPolicy)data->context_menu_policy;
6901 void QWidget::setContextMenuPolicy(Qt::ContextMenuPolicy policy)
6903 data->context_menu_policy = (uint) policy;
6907 \property QWidget::focusPolicy
6908 \brief the way the widget accepts keyboard focus
6910 The policy is Qt::TabFocus if the widget accepts keyboard
6911 focus by tabbing, Qt::ClickFocus if the widget accepts
6912 focus by clicking, Qt::StrongFocus if it accepts both, and
6913 Qt::NoFocus (the default) if it does not accept focus at
6916 You must enable keyboard focus for a widget if it processes
6917 keyboard events. This is normally done from the widget's
6918 constructor. For instance, the QLineEdit constructor calls
6919 setFocusPolicy(Qt::StrongFocus).
6921 If the widget has a focus proxy, then the focus policy will
6922 be propagated to it.
6924 \sa focusInEvent(), focusOutEvent(), keyPressEvent(), keyReleaseEvent(), enabled
6928 Qt::FocusPolicy QWidget::focusPolicy() const
6930 return (Qt::FocusPolicy)data->focus_policy;
6933 void QWidget::setFocusPolicy(Qt::FocusPolicy policy)
6935 data->focus_policy = (uint) policy;
6937 if (d->extra && d->extra->focus_proxy)
6938 d->extra->focus_proxy->setFocusPolicy(policy);
6942 \property QWidget::updatesEnabled
6943 \brief whether updates are enabled
6945 An updates enabled widget receives paint events and has a system
6946 background; a disabled widget does not. This also implies that
6947 calling update() and repaint() has no effect if updates are
6950 By default, this property is true.
6952 setUpdatesEnabled() is normally used to disable updates for a
6953 short period of time, for instance to avoid screen flicker during
6954 large changes. In Qt, widgets normally do not generate screen
6955 flicker, but on X11 the server might erase regions on the screen
6956 when widgets get hidden before they can be replaced by other
6957 widgets. Disabling updates solves this.
6960 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 13
6962 Disabling a widget implicitly disables all its children. Enabling a widget
6963 enables all child widgets \e except top-level widgets or those that
6964 have been explicitly disabled. Re-enabling updates implicitly calls
6965 update() on the widget.
6969 void QWidget::setUpdatesEnabled(bool enable)
6972 setAttribute(Qt::WA_ForceUpdatesDisabled, !enable);
6973 d->setUpdatesEnabled_helper(enable);
6976 /*! \fn void QWidget::show()
6978 Shows the widget and its child widgets. This function is
6979 equivalent to setVisible(true).
6981 \sa raise(), showEvent(), hide(), setVisible(), showMinimized(), showMaximized(),
6982 showNormal(), isVisible()
6988 Makes the widget visible in the isVisible() meaning of the word.
6989 It is only called for toplevels or widgets with visible parents.
6991 void QWidgetPrivate::show_recursive()
6994 // polish if necessary
6996 if (!q->testAttribute(Qt::WA_WState_Created))
6997 createRecursively();
6998 q->ensurePolished();
7000 if (!q->isWindow() && q->parentWidget()->d_func()->layout && !q->parentWidget()->data->in_show)
7001 q->parentWidget()->d_func()->layout->activate();
7002 // activate our layout before we and our children become visible
7009 void QWidgetPrivate::sendPendingMoveAndResizeEvents(bool recursive, bool disableUpdates)
7013 disableUpdates = disableUpdates && q->updatesEnabled();
7015 q->setAttribute(Qt::WA_UpdatesDisabled);
7017 if (q->testAttribute(Qt::WA_PendingMoveEvent)) {
7018 QMoveEvent e(data.crect.topLeft(), data.crect.topLeft());
7019 QApplication::sendEvent(q, &e);
7020 q->setAttribute(Qt::WA_PendingMoveEvent, false);
7023 if (q->testAttribute(Qt::WA_PendingResizeEvent)) {
7024 QResizeEvent e(data.crect.size(), QSize());
7025 QApplication::sendEvent(q, &e);
7026 q->setAttribute(Qt::WA_PendingResizeEvent, false);
7030 q->setAttribute(Qt::WA_UpdatesDisabled, false);
7035 for (int i = 0; i < children.size(); ++i) {
7036 if (QWidget *child = qobject_cast<QWidget *>(children.at(i)))
7037 child->d_func()->sendPendingMoveAndResizeEvents(recursive, disableUpdates);
7041 void QWidgetPrivate::activateChildLayoutsRecursively()
7043 sendPendingMoveAndResizeEvents(false, true);
7045 for (int i = 0; i < children.size(); ++i) {
7046 QWidget *child = qobject_cast<QWidget *>(children.at(i));
7047 if (!child || child->isHidden() || child->isWindow())
7050 child->ensurePolished();
7052 // Activate child's layout
7053 QWidgetPrivate *childPrivate = child->d_func();
7054 if (childPrivate->layout)
7055 childPrivate->layout->activate();
7057 // Pretend we're visible.
7058 const bool wasVisible = child->isVisible();
7060 child->setAttribute(Qt::WA_WState_Visible);
7062 // Do the same for all my children.
7063 childPrivate->activateChildLayoutsRecursively();
7065 // We're not cheating anymore.
7067 child->setAttribute(Qt::WA_WState_Visible, false);
7071 void QWidgetPrivate::show_helper()
7074 data.in_show = true; // qws optimization
7075 // make sure we receive pending move and resize events
7076 sendPendingMoveAndResizeEvents();
7078 // become visible before showing all children
7079 q->setAttribute(Qt::WA_WState_Visible);
7081 // finally show all children recursively
7082 showChildren(false);
7086 // popup handling: new popups and tools need to be raised, and
7087 // existing popups must be closed. Also propagate the current
7088 // windows's KeyboardFocusChange status.
7089 if (q->isWindow()) {
7090 if ((q->windowType() == Qt::Tool) || (q->windowType() == Qt::Popup) || q->windowType() == Qt::ToolTip) {
7092 if (q->parentWidget() && q->parentWidget()->window()->testAttribute(Qt::WA_KeyboardFocusChange))
7093 q->setAttribute(Qt::WA_KeyboardFocusChange);
7095 while (QApplication::activePopupWidget()) {
7096 if (!QApplication::activePopupWidget()->close())
7102 // Automatic embedding of child windows of widgets already embedded into
7103 // QGraphicsProxyWidget when they are shown the first time.
7104 bool isEmbedded = false;
7105 #ifndef QT_NO_GRAPHICSVIEW
7106 if (q->isWindow()) {
7107 isEmbedded = q->graphicsProxyWidget() ? true : false;
7108 if (!isEmbedded && !bypassGraphicsProxyWidget(q)) {
7109 QGraphicsProxyWidget *ancestorProxy = nearestGraphicsProxyWidget(q->parentWidget());
7110 if (ancestorProxy) {
7112 ancestorProxy->d_func()->embedSubWindow(q);
7117 Q_UNUSED(isEmbedded);
7120 // On Windows, show the popup now so that our own focus handling
7121 // stores the correct old focus widget even if it's stolen in the
7123 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
7124 if (!isEmbedded && q->windowType() == Qt::Popup)
7125 qApp->d_func()->openPopup(q);
7128 // send the show event before showing the window
7129 QShowEvent showEvent;
7130 QApplication::sendEvent(q, &showEvent);
7132 if (!isEmbedded && q->isModal() && q->isWindow())
7133 // QApplicationPrivate::enterModal *before* show, otherwise the initial
7134 // stacking might be wrong
7135 QApplicationPrivate::enterModal(q);
7140 #if !defined(Q_WS_WIN) && !defined(Q_WS_MAC) && !defined(Q_OS_SYMBIAN)
7141 if (!isEmbedded && q->windowType() == Qt::Popup)
7142 qApp->d_func()->openPopup(q);
7145 #ifndef QT_NO_ACCESSIBILITY
7146 if (q->windowType() != Qt::ToolTip) // Tooltips are read aloud twice in MS narrator.
7147 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectShow);
7150 if (QApplicationPrivate::hidden_focus_widget == q) {
7151 QApplicationPrivate::hidden_focus_widget = 0;
7152 q->setFocus(Qt::OtherFocusReason);
7155 // Process events when showing a Qt::SplashScreen widget before the event loop
7156 // is spinnning; otherwise it might not show up on particular platforms.
7157 // This makes QSplashScreen behave the same on all platforms.
7158 if (!qApp->d_func()->in_exec && q->windowType() == Qt::SplashScreen)
7159 QApplication::processEvents();
7161 data.in_show = false; // reset qws optimization
7164 /*! \fn void QWidget::hide()
7166 Hides the widget. This function is equivalent to
7170 \note If you are working with QDialog or its subclasses and you invoke
7171 the show() function after this function, the dialog will be displayed in
7172 its original position.
7174 \sa hideEvent(), isHidden(), show(), setVisible(), isVisible(), close()
7179 void QWidgetPrivate::hide_helper()
7183 bool isEmbedded = false;
7184 #if !defined QT_NO_GRAPHICSVIEW
7185 isEmbedded = q->isWindow() && !bypassGraphicsProxyWidget(q) && nearestGraphicsProxyWidget(q->parentWidget()) != 0;
7187 Q_UNUSED(isEmbedded);
7190 if (!isEmbedded && (q->windowType() == Qt::Popup))
7191 qApp->d_func()->closePopup(q);
7193 // Move test modal here. Otherwise, a modal dialog could get
7194 // destroyed and we lose all access to its parent because we haven't
7195 // left modality. (Eg. modal Progress Dialog)
7196 if (!isEmbedded && q->isModal() && q->isWindow())
7197 QApplicationPrivate::leaveModal(q);
7199 #if defined(Q_WS_WIN)
7200 if (q->isWindow() && !(q->windowType() == Qt::Popup) && q->parentWidget()
7201 && !q->parentWidget()->isHidden() && q->isActiveWindow())
7202 q->parentWidget()->activateWindow(); // Activate parent
7205 q->setAttribute(Qt::WA_Mapped, false);
7208 bool wasVisible = q->testAttribute(Qt::WA_WState_Visible);
7211 q->setAttribute(Qt::WA_WState_Visible, false);
7215 QHideEvent hideEvent;
7216 QApplication::sendEvent(q, &hideEvent);
7217 hideChildren(false);
7219 // next bit tries to move the focus if the focus widget is now
7222 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7223 qApp->d_func()->sendSyntheticEnterLeave(q);
7226 QWidget *fw = QApplication::focusWidget();
7227 while (fw && !fw->isWindow()) {
7229 q->focusNextPrevChild(true);
7232 fw = fw->parentWidget();
7236 if (QWidgetBackingStore *bs = maybeBackingStore())
7237 bs->removeDirtyWidget(q);
7239 #ifndef QT_NO_ACCESSIBILITY
7241 QAccessible::updateAccessibility(q, 0, QAccessible::ObjectHide);
7246 \fn bool QWidget::isHidden() const
7248 Returns true if the widget is hidden, otherwise returns false.
7250 A hidden widget will only become visible when show() is called on
7251 it. It will not be automatically shown when the parent is shown.
7253 To check visibility, use !isVisible() instead (notice the exclamation mark).
7255 isHidden() implies !isVisible(), but a widget can be not visible
7256 and not hidden at the same time. This is the case for widgets that are children of
7257 widgets that are not visible.
7260 Widgets are hidden if:
7262 \o they were created as independent windows,
7263 \o they were created as children of visible widgets,
7264 \o hide() or setVisible(false) was called.
7269 void QWidget::setVisible(bool visible)
7271 if (visible) { // show
7272 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && !testAttribute(Qt::WA_WState_Hidden))
7277 // Designer uses a trick to make grabWidget work without showing
7278 if (!isWindow() && parentWidget() && parentWidget()->isVisible()
7279 && !parentWidget()->testAttribute(Qt::WA_WState_Created))
7280 parentWidget()->window()->d_func()->createRecursively();
7282 //we have to at least create toplevels before applyX11SpecificCommandLineArguments
7283 //but not children of non-visible parents
7284 QWidget *pw = parentWidget();
7285 if (!testAttribute(Qt::WA_WState_Created)
7286 && (isWindow() || pw->testAttribute(Qt::WA_WState_Created))) {
7290 #if defined(Q_WS_X11)
7291 if (windowType() == Qt::Window)
7292 QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
7295 bool wasResized = testAttribute(Qt::WA_Resized);
7296 Qt::WindowStates initialWindowState = windowState();
7298 // polish if necessary
7301 // remember that show was called explicitly
7302 setAttribute(Qt::WA_WState_ExplicitShowHide);
7303 // whether we need to inform the parent widget immediately
7304 bool needUpdateGeometry = !isWindow() && testAttribute(Qt::WA_WState_Hidden);
7305 // we are no longer hidden
7306 setAttribute(Qt::WA_WState_Hidden, false);
7308 if (needUpdateGeometry)
7309 d->updateGeometry_helper(true);
7311 // activate our layout before we and our children become visible
7313 d->layout->activate();
7316 QWidget *parent = parentWidget();
7317 while (parent && parent->isVisible() && parent->d_func()->layout && !parent->data->in_show) {
7318 parent->d_func()->layout->activate();
7319 if (parent->isWindow())
7321 parent = parent->parentWidget();
7324 parent->d_func()->setDirtyOpaqueRegion();
7327 // adjust size if necessary
7329 && (isWindow() || !parentWidget()->d_func()->layout)) {
7332 if (windowState() != initialWindowState)
7333 setWindowState(initialWindowState);
7337 setAttribute(Qt::WA_Resized, false);
7340 setAttribute(Qt::WA_KeyboardFocusChange, false);
7342 if (isWindow() || parentWidget()->isVisible()) {
7343 // remove posted quit events when showing a new window
7344 QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
7348 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7349 qApp->d_func()->sendSyntheticEnterLeave(this);
7353 QEvent showToParentEvent(QEvent::ShowToParent);
7354 QApplication::sendEvent(this, &showToParentEvent);
7356 if (testAttribute(Qt::WA_WState_ExplicitShowHide) && testAttribute(Qt::WA_WState_Hidden))
7358 #if defined(Q_WS_WIN)
7359 // reset WS_DISABLED style in a Blocked window
7360 if(isWindow() && testAttribute(Qt::WA_WState_Created)
7361 && QApplicationPrivate::isBlockedByModal(this))
7363 LONG dwStyle = GetWindowLong(winId(), GWL_STYLE);
7364 dwStyle &= ~WS_DISABLED;
7365 SetWindowLong(winId(), GWL_STYLE, dwStyle);
7368 if (QApplicationPrivate::hidden_focus_widget == this)
7369 QApplicationPrivate::hidden_focus_widget = 0;
7373 // hw: The test on getOpaqueRegion() needs to be more intelligent
7374 // currently it doesn't work if the widget is hidden (the region will
7375 // be clipped). The real check should be testing the cached region
7376 // (and dirty flag) directly.
7377 if (!isWindow() && parentWidget()) // && !d->getOpaqueRegion().isEmpty())
7378 parentWidget()->d_func()->setDirtyOpaqueRegion();
7380 setAttribute(Qt::WA_WState_Hidden);
7381 setAttribute(Qt::WA_WState_ExplicitShowHide);
7382 if (testAttribute(Qt::WA_WState_Created))
7385 // invalidate layout similar to updateGeometry()
7386 if (!isWindow() && parentWidget()) {
7387 if (parentWidget()->d_func()->layout)
7388 parentWidget()->d_func()->layout->invalidate();
7389 else if (parentWidget()->isVisible())
7390 QApplication::postEvent(parentWidget(), new QEvent(QEvent::LayoutRequest));
7393 QEvent hideToParentEvent(QEvent::HideToParent);
7394 QApplication::sendEvent(this, &hideToParentEvent);
7398 /*!\fn void QWidget::setHidden(bool hidden)
7400 Convenience function, equivalent to setVisible(!\a hidden).
7404 void QWidgetPrivate::_q_showIfNotHidden()
7407 if ( !(q->isHidden() && q->testAttribute(Qt::WA_WState_ExplicitShowHide)) )
7408 q->setVisible(true);
7411 void QWidgetPrivate::showChildren(bool spontaneous)
7413 QList<QObject*> childList = children;
7414 for (int i = 0; i < childList.size(); ++i) {
7415 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7417 || widget->isWindow()
7418 || widget->testAttribute(Qt::WA_WState_Hidden))
7421 widget->setAttribute(Qt::WA_Mapped);
7422 widget->d_func()->showChildren(true);
7424 QApplication::sendSpontaneousEvent(widget, &e);
7426 if (widget->testAttribute(Qt::WA_WState_ExplicitShowHide))
7427 widget->d_func()->show_recursive();
7434 void QWidgetPrivate::hideChildren(bool spontaneous)
7436 QList<QObject*> childList = children;
7437 for (int i = 0; i < childList.size(); ++i) {
7438 QWidget *widget = qobject_cast<QWidget*>(childList.at(i));
7439 if (!widget || widget->isWindow() || widget->testAttribute(Qt::WA_WState_Hidden))
7442 // Before doing anything we need to make sure that we don't leave anything in a non-consistent state.
7443 // When hiding a widget we need to make sure that no mouse_down events are active, because
7444 // the mouse_up event will never be received by a hidden widget or one of its descendants.
7445 // The solution is simple, before going through with this we check if there are any mouse_down events in
7446 // progress, if so we check if it is related to this widget or not. If so, we just reset the mouse_down and
7447 // then we continue.
7448 // In X11 and Windows we send a mouse_release event, however we don't do that here because we were already
7449 // ignoring that from before. I.e. Carbon did not send the mouse release event, so we will not send the
7450 // mouse release event. There are two ways to interpret this:
7451 // 1. If we don't send the mouse release event, the widget might get into an inconsistent state, i.e. it
7452 // might be waiting for a release event that will never arrive.
7453 // 2. If we send the mouse release event, then the widget might decide to trigger an action that is not
7454 // supposed to trigger because it is not visible.
7455 if(widget == qt_button_down)
7459 widget->setAttribute(Qt::WA_Mapped, false);
7461 widget->setAttribute(Qt::WA_WState_Visible, false);
7462 widget->d_func()->hideChildren(spontaneous);
7465 QApplication::sendSpontaneousEvent(widget, &e);
7467 QApplication::sendEvent(widget, &e);
7468 if (widget->internalWinId()
7469 && widget->testAttribute(Qt::WA_DontCreateNativeAncestors)) {
7470 // hide_sys() on an ancestor won't have any affect on this
7471 // widget, so it needs an explicit hide_sys() of its own
7472 widget->d_func()->hide_sys();
7475 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QPA)
7476 qApp->d_func()->sendSyntheticEnterLeave(widget);
7478 #ifndef QT_NO_ACCESSIBILITY
7480 QAccessible::updateAccessibility(widget, 0, QAccessible::ObjectHide);
7485 bool QWidgetPrivate::close_helper(CloseMode mode)
7487 if (data.is_closing)
7491 data.is_closing = 1;
7493 QPointer<QWidget> that = q;
7494 QPointer<QWidget> parentWidget = q->parentWidget();
7496 bool quitOnClose = q->testAttribute(Qt::WA_QuitOnClose);
7497 if (mode != CloseNoEvent) {
7499 if (mode == CloseWithSpontaneousEvent)
7500 QApplication::sendSpontaneousEvent(q, &e);
7502 QApplication::sendEvent(q, &e);
7503 if (!that.isNull() && !e.isAccepted()) {
7504 data.is_closing = 0;
7509 if (!that.isNull() && !q->isHidden())
7512 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
7513 quitOnClose = quitOnClose && (parentWidget.isNull() || !parentWidget->isVisible());
7516 /* if there is no non-withdrawn primary window left (except
7517 the ones without QuitOnClose), we emit the lastWindowClosed
7519 QWidgetList list = QApplication::topLevelWidgets();
7520 bool lastWindowClosed = true;
7521 for (int i = 0; i < list.size(); ++i) {
7522 QWidget *w = list.at(i);
7523 if (!w->isVisible() || w->parentWidget() || !w->testAttribute(Qt::WA_QuitOnClose))
7525 lastWindowClosed = false;
7528 if (lastWindowClosed)
7529 QApplicationPrivate::emitLastWindowClosed();
7532 if (!that.isNull()) {
7533 data.is_closing = 0;
7534 if (q->testAttribute(Qt::WA_DeleteOnClose)) {
7535 q->setAttribute(Qt::WA_DeleteOnClose, false);
7544 Closes this widget. Returns true if the widget was closed;
7545 otherwise returns false.
7547 First it sends the widget a QCloseEvent. The widget is \link
7548 hide() hidden\endlink if it \link QCloseEvent::accept()
7549 accepts\endlink the close event. If it \link QCloseEvent::ignore()
7550 ignores\endlink the event, nothing happens. The default
7551 implementation of QWidget::closeEvent() accepts the close event.
7553 If the widget has the Qt::WA_DeleteOnClose flag, the widget
7554 is also deleted. A close events is delivered to the widget no
7555 matter if the widget is visible or not.
7557 The \l QApplication::lastWindowClosed() signal is emitted when the
7558 last visible primary window (i.e. window with no parent) with the
7559 Qt::WA_QuitOnClose attribute set is closed. By default this
7560 attribute is set for all widgets except transient windows such as
7561 splash screens, tool windows, and popup menus.
7565 bool QWidget::close()
7567 return d_func()->close_helper(QWidgetPrivate::CloseWithEvent);
7571 \property QWidget::visible
7572 \brief whether the widget is visible
7574 Calling setVisible(true) or show() sets the widget to visible
7575 status if all its parent widgets up to the window are visible. If
7576 an ancestor is not visible, the widget won't become visible until
7577 all its ancestors are shown. If its size or position has changed,
7578 Qt guarantees that a widget gets move and resize events just
7579 before it is shown. If the widget has not been resized yet, Qt
7580 will adjust the widget's size to a useful default using
7583 Calling setVisible(false) or hide() hides a widget explicitly. An
7584 explicitly hidden widget will never become visible, even if all
7585 its ancestors become visible, unless you show it.
7587 A widget receives show and hide events when its visibility status
7588 changes. Between a hide and a show event, there is no need to
7589 waste CPU cycles preparing or displaying information to the user.
7590 A video application, for example, might simply stop generating new
7593 A widget that happens to be obscured by other windows on the
7594 screen is considered to be visible. The same applies to iconified
7595 windows and windows that exist on another virtual
7596 desktop (on platforms that support this concept). A widget
7597 receives spontaneous show and hide events when its mapping status
7598 is changed by the window system, e.g. a spontaneous hide event
7599 when the user minimizes the window, and a spontaneous show event
7600 when the window is restored again.
7602 You almost never have to reimplement the setVisible() function. If
7603 you need to change some settings before a widget is shown, use
7604 showEvent() instead. If you need to do some delayed initialization
7605 use the Polish event delivered to the event() function.
7607 \sa show(), hide(), isHidden(), isVisibleTo(), isMinimized(),
7608 showEvent(), hideEvent()
7613 Returns true if this widget would become visible if \a ancestor is
7614 shown; otherwise returns false.
7616 The true case occurs if neither the widget itself nor any parent
7617 up to but excluding \a ancestor has been explicitly hidden.
7619 This function will still return true if the widget is obscured by
7620 other windows on the screen, but could be physically visible if it
7621 or they were to be moved.
7623 isVisibleTo(0) is identical to isVisible().
7625 \sa show() hide() isVisible()
7628 bool QWidget::isVisibleTo(QWidget* ancestor) const
7632 const QWidget * w = this;
7633 while (!w->isHidden()
7635 && w->parentWidget()
7636 && w->parentWidget() != ancestor)
7637 w = w->parentWidget();
7638 return !w->isHidden();
7643 Returns the unobscured region where paint events can occur.
7645 For visible widgets, this is an approximation of the area not
7646 covered by other widgets; otherwise, this is an empty region.
7648 The repaint() function calls this function if necessary, so in
7649 general you do not need to call it.
7652 QRegion QWidget::visibleRegion() const
7656 QRect clipRect = d->clipRect();
7657 if (clipRect.isEmpty())
7659 QRegion r(clipRect);
7660 d->subtractOpaqueChildren(r, clipRect);
7661 d->subtractOpaqueSiblings(r);
7666 QSize QWidgetPrivate::adjustedSize() const
7670 QSize s = q->sizeHint();
7672 if (q->isWindow()) {
7673 Qt::Orientations exp;
7675 if (layout->hasHeightForWidth())
7676 s.setHeight(layout->totalHeightForWidth(s.width()));
7677 exp = layout->expandingDirections();
7680 if (q->sizePolicy().hasHeightForWidth())
7681 s.setHeight(q->heightForWidth(s.width()));
7682 exp = q->sizePolicy().expandingDirections();
7684 if (exp & Qt::Horizontal)
7685 s.setWidth(qMax(s.width(), 200));
7686 if (exp & Qt::Vertical)
7687 s.setHeight(qMax(s.height(), 100));
7688 #if defined(Q_WS_X11)
7689 QRect screen = QApplication::desktop()->screenGeometry(q->x11Info().screen());
7691 QRect screen = QApplication::desktop()->screenGeometry(q->pos());
7693 #if defined (Q_WS_WINCE) || defined (Q_OS_SYMBIAN)
7694 s.setWidth(qMin(s.width(), screen.width()));
7695 s.setHeight(qMin(s.height(), screen.height()));
7697 s.setWidth(qMin(s.width(), screen.width()*2/3));
7698 s.setHeight(qMin(s.height(), screen.height()*2/3));
7700 if (QTLWExtra *extra = maybeTopData())
7701 extra->sizeAdjusted = true;
7705 QRect r = q->childrenRect(); // get children rectangle
7708 s = r.size() + QSize(2 * r.x(), 2 * r.y());
7715 Adjusts the size of the widget to fit its contents.
7717 This function uses sizeHint() if it is valid, i.e., the size hint's width
7718 and height are \>= 0. Otherwise, it sets the size to the children
7719 rectangle that covers all child widgets (the union of all child widget
7722 For windows, the screen size is also taken into account. If the sizeHint()
7723 is less than (200, 100) and the size policy is \l{QSizePolicy::Expanding}
7724 {expanding}, the window will be at least (200, 100). The maximum size of
7725 a window is 2/3 of the screen's width and height.
7727 \sa sizeHint(), childrenRect()
7730 void QWidget::adjustSize()
7734 QSize s = d->adjustedSize();
7737 d->layout->activate();
7745 \property QWidget::sizeHint
7746 \brief the recommended size for the widget
7748 If the value of this property is an invalid size, no size is
7751 The default implementation of sizeHint() returns an invalid size
7752 if there is no layout for this widget, and returns the layout's
7753 preferred size otherwise.
7755 \sa QSize::isValid(), minimumSizeHint(), sizePolicy(),
7756 setMinimumSize(), updateGeometry()
7759 QSize QWidget::sizeHint() const
7763 return d->layout->totalSizeHint();
7764 return QSize(-1, -1);
7768 \property QWidget::minimumSizeHint
7769 \brief the recommended minimum size for the widget
7771 If the value of this property is an invalid size, no minimum size
7774 The default implementation of minimumSizeHint() returns an invalid
7775 size if there is no layout for this widget, and returns the
7776 layout's minimum size otherwise. Most built-in widgets reimplement
7779 \l QLayout will never resize a widget to a size smaller than the
7780 minimum size hint unless minimumSize() is set or the size policy is
7781 set to QSizePolicy::Ignore. If minimumSize() is set, the minimum
7782 size hint will be ignored.
7784 \sa QSize::isValid(), resize(), setMinimumSize(), sizePolicy()
7786 QSize QWidget::minimumSizeHint() const
7790 return d->layout->totalMinimumSize();
7791 return QSize(-1, -1);
7796 \fn QWidget *QWidget::parentWidget() const
7798 Returns the parent of this widget, or 0 if it does not have any
7804 Returns true if this widget is a parent, (or grandparent and so on
7805 to any level), of the given \a child, and both widgets are within
7806 the same window; otherwise returns false.
7809 bool QWidget::isAncestorOf(const QWidget *child) const
7814 if (child->isWindow())
7816 child = child->parentWidget();
7821 #if defined(Q_WS_WIN)
7822 inline void setDisabledStyle(QWidget *w, bool setStyle)
7824 // set/reset WS_DISABLED style.
7825 if(w && w->isWindow() && w->isVisible() && w->isEnabled()) {
7826 LONG dwStyle = GetWindowLong(w->winId(), GWL_STYLE);
7827 LONG newStyle = dwStyle;
7829 newStyle |= WS_DISABLED;
7831 newStyle &= ~WS_DISABLED;
7832 if (newStyle != dwStyle) {
7833 SetWindowLong(w->winId(), GWL_STYLE, newStyle);
7834 // we might need to repaint in some situations (eg. menu)
7841 /*****************************************************************************
7842 QWidget event handling
7843 *****************************************************************************/
7846 This is the main event handler; it handles event \a event. You can
7847 reimplement this function in a subclass, but we recommend using
7848 one of the specialized event handlers instead.
7850 Key press and release events are treated differently from other
7851 events. event() checks for Tab and Shift+Tab and tries to move the
7852 focus appropriately. If there is no widget to move the focus to
7853 (or the key press is not Tab or Shift+Tab), event() calls
7856 Mouse and tablet event handling is also slightly special: only
7857 when the widget is \l enabled, event() will call the specialized
7858 handlers such as mousePressEvent(); otherwise it will discard the
7861 This function returns true if the event was recognized, otherwise
7862 it returns false. If the recognized event was accepted (see \l
7863 QEvent::accepted), any further processing such as event
7864 propagation to the parent widget stops.
7866 \sa closeEvent(), focusInEvent(), focusOutEvent(), enterEvent(),
7867 keyPressEvent(), keyReleaseEvent(), leaveEvent(),
7868 mouseDoubleClickEvent(), mouseMoveEvent(), mousePressEvent(),
7869 mouseReleaseEvent(), moveEvent(), paintEvent(), resizeEvent(),
7870 QObject::event(), QObject::timerEvent()
7873 bool QWidget::event(QEvent *event)
7877 // ignore mouse events when disabled
7879 switch(event->type()) {
7880 case QEvent::TabletPress:
7881 case QEvent::TabletRelease:
7882 case QEvent::TabletMove:
7883 case QEvent::MouseButtonPress:
7884 case QEvent::MouseButtonRelease:
7885 case QEvent::MouseButtonDblClick:
7886 case QEvent::MouseMove:
7887 case QEvent::TouchBegin:
7888 case QEvent::TouchUpdate:
7889 case QEvent::TouchEnd:
7890 case QEvent::ContextMenu:
7891 #ifndef QT_NO_WHEELEVENT
7899 switch (event->type()) {
7900 case QEvent::MouseMove:
7901 mouseMoveEvent((QMouseEvent*)event);
7904 case QEvent::MouseButtonPress:
7905 mousePressEvent((QMouseEvent*)event);
7908 case QEvent::MouseButtonRelease:
7909 mouseReleaseEvent((QMouseEvent*)event);
7912 case QEvent::MouseButtonDblClick:
7913 mouseDoubleClickEvent((QMouseEvent*)event);
7915 #ifndef QT_NO_WHEELEVENT
7917 wheelEvent((QWheelEvent*)event);
7920 #ifndef QT_NO_TABLETEVENT
7921 case QEvent::TabletMove:
7922 case QEvent::TabletPress:
7923 case QEvent::TabletRelease:
7924 tabletEvent((QTabletEvent*)event);
7927 case QEvent::KeyPress: {
7928 QKeyEvent *k = (QKeyEvent *)event;
7930 if (!(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier))) { //### Add MetaModifier?
7931 if (k->key() == Qt::Key_Backtab
7932 || (k->key() == Qt::Key_Tab && (k->modifiers() & Qt::ShiftModifier)))
7933 res = focusNextPrevChild(false);
7934 else if (k->key() == Qt::Key_Tab)
7935 res = focusNextPrevChild(true);
7940 #ifdef QT_KEYPAD_NAVIGATION
7941 if (!k->isAccepted() && QApplication::keypadNavigationEnabled()
7942 && !(k->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::ShiftModifier))) {
7943 if (QApplication::navigationMode() == Qt::NavigationModeKeypadTabOrder) {
7944 if (k->key() == Qt::Key_Up)
7945 res = focusNextPrevChild(false);
7946 else if (k->key() == Qt::Key_Down)
7947 res = focusNextPrevChild(true);
7948 } else if (QApplication::navigationMode() == Qt::NavigationModeKeypadDirectional) {
7949 if (k->key() == Qt::Key_Up)
7950 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionNorth);
7951 else if (k->key() == Qt::Key_Right)
7952 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionEast);
7953 else if (k->key() == Qt::Key_Down)
7954 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionSouth);
7955 else if (k->key() == Qt::Key_Left)
7956 res = QWidgetPrivate::navigateToDirection(QWidgetPrivate::DirectionWest);
7964 #ifndef QT_NO_WHATSTHIS
7965 if (!k->isAccepted()
7966 && k->modifiers() & Qt::ShiftModifier && k->key() == Qt::Key_F1
7967 && d->whatsThis.size()) {
7968 QWhatsThis::showText(mapToGlobal(inputMethodQuery(Qt::ImCursorRectangle).toRect().center()), d->whatsThis, this);
7975 case QEvent::KeyRelease:
7976 keyReleaseEvent((QKeyEvent*)event);
7978 case QEvent::ShortcutOverride:
7981 case QEvent::InputMethod:
7982 inputMethodEvent((QInputMethodEvent *) event);
7985 case QEvent::InputMethodQuery:
7986 if (testAttribute(Qt::WA_InputMethodEnabled)) {
7987 QInputMethodQueryEvent *query = static_cast<QInputMethodQueryEvent *>(event);
7988 Qt::InputMethodQueries queries = query->queries();
7989 for (uint i = 0; i < 32; ++i) {
7990 Qt::InputMethodQuery q = (Qt::InputMethodQuery)(int)(queries & (1<<i));
7992 QVariant v = inputMethodQuery(q);
7993 query->setValue(q, v);
8000 case QEvent::PolishRequest:
8004 case QEvent::Polish: {
8005 style()->polish(this);
8006 setAttribute(Qt::WA_WState_Polished);
8007 if (!QApplication::font(this).isCopyOf(QApplication::font()))
8009 if (!QApplication::palette(this).isCopyOf(QApplication::palette()))
8010 d->resolvePalette();
8014 case QEvent::ApplicationWindowIconChange:
8015 if (isWindow() && !testAttribute(Qt::WA_SetWindowIcon)) {
8016 d->setWindowIcon_sys();
8017 d->setWindowIcon_helper();
8020 case QEvent::FocusIn:
8021 #ifdef QT_SOFTKEYS_ENABLED
8022 QSoftKeyManager::updateSoftKeys();
8024 focusInEvent((QFocusEvent*)event);
8025 d->updateWidgetTransform();
8028 case QEvent::FocusOut:
8029 focusOutEvent((QFocusEvent*)event);
8033 #ifndef QT_NO_STATUSTIP
8034 if (d->statusTip.size()) {
8035 QStatusTipEvent tip(d->statusTip);
8036 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8043 #ifndef QT_NO_STATUSTIP
8044 if (d->statusTip.size()) {
8046 QStatusTipEvent tip(empty);
8047 QApplication::sendEvent(const_cast<QWidget *>(this), &tip);
8053 case QEvent::HoverEnter:
8054 case QEvent::HoverLeave:
8059 // At this point the event has to be delivered, regardless
8060 // whether the widget isVisible() or not because it
8061 // already went through the filters
8062 paintEvent((QPaintEvent*)event);
8066 moveEvent((QMoveEvent*)event);
8067 d->updateWidgetTransform();
8070 case QEvent::Resize:
8071 resizeEvent((QResizeEvent*)event);
8072 d->updateWidgetTransform();
8076 closeEvent((QCloseEvent *)event);
8079 #ifndef QT_NO_CONTEXTMENU
8080 case QEvent::ContextMenu:
8081 switch (data->context_menu_policy) {
8082 case Qt::PreventContextMenu:
8084 case Qt::DefaultContextMenu:
8085 contextMenuEvent(static_cast<QContextMenuEvent *>(event));
8087 case Qt::CustomContextMenu:
8088 emit customContextMenuRequested(static_cast<QContextMenuEvent *>(event)->pos());
8091 case Qt::ActionsContextMenu:
8092 if (d->actions.count()) {
8093 QMenu::exec(d->actions, static_cast<QContextMenuEvent *>(event)->globalPos(),
8104 #endif // QT_NO_CONTEXTMENU
8106 #ifndef QT_NO_DRAGANDDROP
8108 dropEvent((QDropEvent*) event);
8111 case QEvent::DragEnter:
8112 dragEnterEvent((QDragEnterEvent*) event);
8115 case QEvent::DragMove:
8116 dragMoveEvent((QDragMoveEvent*) event);
8119 case QEvent::DragLeave:
8120 dragLeaveEvent((QDragLeaveEvent*) event);
8125 showEvent((QShowEvent*) event);
8129 hideEvent((QHideEvent*) event);
8132 case QEvent::ShowWindowRequest:
8137 case QEvent::ApplicationFontChange:
8140 case QEvent::ApplicationPaletteChange:
8141 if (!(windowType() == Qt::Desktop))
8142 d->resolvePalette();
8145 case QEvent::ToolBarChange:
8146 case QEvent::ActivationChange:
8147 case QEvent::EnabledChange:
8148 case QEvent::FontChange:
8149 case QEvent::StyleChange:
8150 case QEvent::PaletteChange:
8151 case QEvent::WindowTitleChange:
8152 case QEvent::IconTextChange:
8153 case QEvent::ModifiedChange:
8154 case QEvent::MouseTrackingChange:
8155 case QEvent::ParentChange:
8156 case QEvent::WindowStateChange:
8157 case QEvent::LocaleChange:
8158 case QEvent::MacSizeChange:
8159 case QEvent::ContentsRectChange:
8163 case QEvent::WindowActivate:
8164 case QEvent::WindowDeactivate: {
8165 if (isVisible() && !palette().isEqual(QPalette::Active, QPalette::Inactive))
8167 QList<QObject*> childList = d->children;
8168 for (int i = 0; i < childList.size(); ++i) {
8169 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8170 if (w && w->isVisible() && !w->isWindow())
8171 QApplication::sendEvent(w, event);
8174 #ifdef QT_SOFTKEYS_ENABLED
8176 QSoftKeyManager::updateSoftKeys();
8181 case QEvent::LanguageChange:
8184 QList<QObject*> childList = d->children;
8185 for (int i = 0; i < childList.size(); ++i) {
8186 QObject *o = childList.at(i);
8188 QApplication::sendEvent(o, event);
8194 case QEvent::ApplicationLayoutDirectionChange:
8195 d->resolveLayoutDirection();
8198 case QEvent::LayoutDirectionChange:
8200 d->layout->invalidate();
8204 case QEvent::UpdateRequest:
8205 d->syncBackingStore();
8207 case QEvent::UpdateLater:
8208 update(static_cast<QUpdateLaterEvent*>(event)->region());
8211 case QEvent::WindowBlocked:
8212 case QEvent::WindowUnblocked:
8214 QList<QObject*> childList = d->children;
8215 for (int i = 0; i < childList.size(); ++i) {
8216 QObject *o = childList.at(i);
8217 if (o && o != QApplication::activeModalWidget()) {
8218 if (qobject_cast<QWidget *>(o) && static_cast<QWidget *>(o)->isWindow()) {
8219 // do not forward the event to child windows,
8220 // QApplication does this for us
8223 QApplication::sendEvent(o, event);
8226 #if defined(Q_WS_WIN)
8227 setDisabledStyle(this, (event->type() == QEvent::WindowBlocked));
8231 #ifndef QT_NO_TOOLTIP
8232 case QEvent::ToolTip:
8233 if (!d->toolTip.isEmpty())
8234 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
8239 #ifndef QT_NO_WHATSTHIS
8240 case QEvent::WhatsThis:
8241 if (d->whatsThis.size())
8242 QWhatsThis::showText(static_cast<QHelpEvent *>(event)->globalPos(), d->whatsThis, this);
8246 case QEvent::QueryWhatsThis:
8247 if (d->whatsThis.isEmpty())
8251 #ifndef QT_NO_ACCESSIBILITY
8252 case QEvent::AccessibilityDescription:
8253 case QEvent::AccessibilityHelp: {
8254 QAccessibleEvent *ev = static_cast<QAccessibleEvent *>(event);
8257 switch (ev->type()) {
8258 #ifndef QT_NO_TOOLTIP
8259 case QEvent::AccessibilityDescription:
8260 ev->setValue(d->toolTip);
8263 #ifndef QT_NO_WHATSTHIS
8264 case QEvent::AccessibilityHelp:
8265 ev->setValue(d->whatsThis);
8273 case QEvent::EmbeddingControl:
8274 d->topData()->frameStrut.setCoords(0 ,0, 0, 0);
8275 data->fstrut_dirty = false;
8276 #if defined(Q_WS_WIN) || defined(Q_WS_X11)
8277 d->topData()->embedded = 1;
8280 #ifndef QT_NO_ACTION
8281 case QEvent::ActionAdded:
8282 case QEvent::ActionRemoved:
8283 case QEvent::ActionChanged:
8284 #ifdef QT_SOFTKEYS_ENABLED
8285 QSoftKeyManager::updateSoftKeys();
8287 actionEvent((QActionEvent*)event);
8291 case QEvent::KeyboardLayoutChange:
8295 // inform children of the change
8296 QList<QObject*> childList = d->children;
8297 for (int i = 0; i < childList.size(); ++i) {
8298 QWidget *w = qobject_cast<QWidget *>(childList.at(i));
8299 if (w && w->isVisible() && !w->isWindow())
8300 QApplication::sendEvent(w, event);
8305 case QEvent::MacGLWindowChange:
8306 d->needWindowChange = false;
8309 case QEvent::TouchBegin:
8310 case QEvent::TouchUpdate:
8311 case QEvent::TouchEnd:
8314 QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
8315 const QTouchEvent::TouchPoint &touchPoint = touchEvent->touchPoints().first();
8316 if (touchPoint.isPrimary() || touchEvent->deviceType() == QTouchEvent::TouchPad)
8319 // fake a mouse event!
8320 QEvent::Type eventType = QEvent::None;
8321 switch (touchEvent->type()) {
8322 case QEvent::TouchBegin:
8323 eventType = QEvent::MouseButtonPress;
8325 case QEvent::TouchUpdate:
8326 eventType = QEvent::MouseMove;
8328 case QEvent::TouchEnd:
8329 eventType = QEvent::MouseButtonRelease;
8335 if (eventType == QEvent::None)
8338 QMouseEvent mouseEvent(eventType,
8340 touchPoint.scenePos(),
8341 touchPoint.screenPos(),
8344 touchEvent->modifiers());
8345 (void) QApplication::sendEvent(this, &mouseEvent);
8349 #ifndef QT_NO_GESTURES
8350 case QEvent::Gesture:
8354 #ifndef QT_NO_PROPERTIES
8355 case QEvent::DynamicPropertyChange: {
8356 const QByteArray &propName = static_cast<QDynamicPropertyChangeEvent *>(event)->propertyName();
8357 if (!qstrncmp(propName, "_q_customDpi", 12) && propName.length() == 13) {
8358 uint value = property(propName.constData()).toUInt();
8361 const char axis = propName.at(12);
8363 d->extra->customDpiX = value;
8364 else if (axis == 'Y')
8365 d->extra->customDpiY = value;
8366 d->updateFont(d->data.fnt);
8372 return QObject::event(event);
8378 This event handler can be reimplemented to handle state changes.
8380 The state being changed in this event can be retrieved through the \a event
8383 Change events include: QEvent::ToolBarChange,
8384 QEvent::ActivationChange, QEvent::EnabledChange, QEvent::FontChange,
8385 QEvent::StyleChange, QEvent::PaletteChange,
8386 QEvent::WindowTitleChange, QEvent::IconTextChange,
8387 QEvent::ModifiedChange, QEvent::MouseTrackingChange,
8388 QEvent::ParentChange, QEvent::WindowStateChange,
8389 QEvent::LanguageChange, QEvent::LocaleChange,
8390 QEvent::LayoutDirectionChange.
8393 void QWidget::changeEvent(QEvent * event)
8395 switch(event->type()) {
8396 case QEvent::EnabledChange:
8398 #ifndef QT_NO_ACCESSIBILITY
8399 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
8403 case QEvent::FontChange:
8404 case QEvent::StyleChange: {
8409 d->layout->invalidate();
8413 case QEvent::PaletteChange:
8418 case QEvent::MacSizeChange:
8421 case QEvent::ToolTipChange:
8422 case QEvent::MouseTrackingChange:
8423 qt_mac_update_mouseTracking(this);
8433 This event handler, for event \a event, can be reimplemented in a
8434 subclass to receive mouse move events for the widget.
8436 If mouse tracking is switched off, mouse move events only occur if
8437 a mouse button is pressed while the mouse is being moved. If mouse
8438 tracking is switched on, mouse move events occur even if no mouse
8441 QMouseEvent::pos() reports the position of the mouse cursor,
8442 relative to this widget. For press and release events, the
8443 position is usually the same as the position of the last mouse
8444 move event, but it might be different if the user's hand shakes.
8445 This is a feature of the underlying window system, not Qt.
8447 If you want to show a tooltip immediately, while the mouse is
8448 moving (e.g., to get the mouse coordinates with QMouseEvent::pos()
8449 and show them as a tooltip), you must first enable mouse tracking
8450 as described above. Then, to ensure that the tooltip is updated
8451 immediately, you must call QToolTip::showText() instead of
8452 setToolTip() in your implementation of mouseMoveEvent().
8454 \sa setMouseTracking(), mousePressEvent(), mouseReleaseEvent(),
8455 mouseDoubleClickEvent(), event(), QMouseEvent, {Scribble Example}
8458 void QWidget::mouseMoveEvent(QMouseEvent *event)
8464 This event handler, for event \a event, can be reimplemented in a
8465 subclass to receive mouse press events for the widget.
8467 If you create new widgets in the mousePressEvent() the
8468 mouseReleaseEvent() may not end up where you expect, depending on
8469 the underlying window system (or X11 window manager), the widgets'
8470 location and maybe more.
8472 The default implementation implements the closing of popup widgets
8473 when you click outside the window. For other widget types it does
8476 \sa mouseReleaseEvent(), mouseDoubleClickEvent(),
8477 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8480 void QWidget::mousePressEvent(QMouseEvent *event)
8483 if ((windowType() == Qt::Popup)) {
8486 while ((w = QApplication::activePopupWidget()) && w != this){
8488 if (QApplication::activePopupWidget() == w) // widget does not want to disappear
8489 w->hide(); // hide at least
8491 if (!rect().contains(event->pos())){
8498 This event handler, for event \a event, can be reimplemented in a
8499 subclass to receive mouse release events for the widget.
8501 \sa mousePressEvent(), mouseDoubleClickEvent(),
8502 mouseMoveEvent(), event(), QMouseEvent, {Scribble Example}
8505 void QWidget::mouseReleaseEvent(QMouseEvent *event)
8511 This event handler, for event \a event, can be reimplemented in a
8512 subclass to receive mouse double click events for the widget.
8514 The default implementation generates a normal mouse press event.
8516 \note The widget will also receive mouse press and mouse release
8517 events in addition to the double click event. It is up to the
8518 developer to ensure that the application interprets these events
8521 \sa mousePressEvent(), mouseReleaseEvent() mouseMoveEvent(),
8522 event(), QMouseEvent
8525 void QWidget::mouseDoubleClickEvent(QMouseEvent *event)
8527 mousePressEvent(event); // try mouse press event
8530 #ifndef QT_NO_WHEELEVENT
8532 This event handler, for event \a event, can be reimplemented in a
8533 subclass to receive wheel events for the widget.
8535 If you reimplement this handler, it is very important that you
8536 \link QWheelEvent ignore()\endlink the event if you do not handle
8537 it, so that the widget's parent can interpret it.
8539 The default implementation ignores the event.
8541 \sa QWheelEvent::ignore(), QWheelEvent::accept(), event(),
8545 void QWidget::wheelEvent(QWheelEvent *event)
8549 #endif // QT_NO_WHEELEVENT
8551 #ifndef QT_NO_TABLETEVENT
8553 This event handler, for event \a event, can be reimplemented in a
8554 subclass to receive tablet events for the widget.
8556 If you reimplement this handler, it is very important that you
8557 \link QTabletEvent ignore()\endlink the event if you do not handle
8558 it, so that the widget's parent can interpret it.
8560 The default implementation ignores the event.
8562 \sa QTabletEvent::ignore(), QTabletEvent::accept(), event(),
8566 void QWidget::tabletEvent(QTabletEvent *event)
8570 #endif // QT_NO_TABLETEVENT
8573 This event handler, for event \a event, can be reimplemented in a
8574 subclass to receive key press events for the widget.
8576 A widget must call setFocusPolicy() to accept focus initially and
8577 have focus in order to receive a key press event.
8579 If you reimplement this handler, it is very important that you
8580 call the base class implementation if you do not act upon the key.
8582 The default implementation closes popup widgets if the user
8583 presses Esc. Otherwise the event is ignored, so that the widget's
8584 parent can interpret it.
8586 Note that QKeyEvent starts with isAccepted() == true, so you do not
8587 need to call QKeyEvent::accept() - just do not call the base class
8588 implementation if you act upon the key.
8590 \sa keyReleaseEvent(), setFocusPolicy(),
8591 focusInEvent(), focusOutEvent(), event(), QKeyEvent, {Tetrix Example}
8594 void QWidget::keyPressEvent(QKeyEvent *event)
8596 if ((windowType() == Qt::Popup) && event->key() == Qt::Key_Escape) {
8605 This event handler, for event \a event, can be reimplemented in a
8606 subclass to receive key release events for the widget.
8608 A widget must \link setFocusPolicy() accept focus\endlink
8609 initially and \link hasFocus() have focus\endlink in order to
8610 receive a key release event.
8612 If you reimplement this handler, it is very important that you
8613 call the base class implementation if you do not act upon the key.
8615 The default implementation ignores the event, so that the widget's
8616 parent can interpret it.
8618 Note that QKeyEvent starts with isAccepted() == true, so you do not
8619 need to call QKeyEvent::accept() - just do not call the base class
8620 implementation if you act upon the key.
8622 \sa keyPressEvent(), QKeyEvent::ignore(), setFocusPolicy(),
8623 focusInEvent(), focusOutEvent(), event(), QKeyEvent
8626 void QWidget::keyReleaseEvent(QKeyEvent *event)
8632 \fn void QWidget::focusInEvent(QFocusEvent *event)
8634 This event handler can be reimplemented in a subclass to receive
8635 keyboard focus events (focus received) for the widget. The event
8636 is passed in the \a event parameter
8638 A widget normally must setFocusPolicy() to something other than
8639 Qt::NoFocus in order to receive focus events. (Note that the
8640 application programmer can call setFocus() on any widget, even
8641 those that do not normally accept focus.)
8643 The default implementation updates the widget (except for windows
8644 that do not specify a focusPolicy()).
8646 \sa focusOutEvent(), setFocusPolicy(), keyPressEvent(),
8647 keyReleaseEvent(), event(), QFocusEvent
8650 void QWidget::focusInEvent(QFocusEvent *)
8652 if (focusPolicy() != Qt::NoFocus || !isWindow()) {
8658 \fn void QWidget::focusOutEvent(QFocusEvent *event)
8660 This event handler can be reimplemented in a subclass to receive
8661 keyboard focus events (focus lost) for the widget. The events is
8662 passed in the \a event parameter.
8664 A widget normally must setFocusPolicy() to something other than
8665 Qt::NoFocus in order to receive focus events. (Note that the
8666 application programmer can call setFocus() on any widget, even
8667 those that do not normally accept focus.)
8669 The default implementation updates the widget (except for windows
8670 that do not specify a focusPolicy()).
8672 \sa focusInEvent(), setFocusPolicy(), keyPressEvent(),
8673 keyReleaseEvent(), event(), QFocusEvent
8676 void QWidget::focusOutEvent(QFocusEvent *)
8678 if (focusPolicy() != Qt::NoFocus || !isWindow())
8683 \fn void QWidget::enterEvent(QEvent *event)
8685 This event handler can be reimplemented in a subclass to receive
8686 widget enter events which are passed in the \a event parameter.
8688 An event is sent to the widget when the mouse cursor enters the
8691 \sa leaveEvent(), mouseMoveEvent(), event()
8694 void QWidget::enterEvent(QEvent *)
8699 \fn void QWidget::leaveEvent(QEvent *event)
8701 This event handler can be reimplemented in a subclass to receive
8702 widget leave events which are passed in the \a event parameter.
8704 A leave event is sent to the widget when the mouse cursor leaves
8707 \sa enterEvent(), mouseMoveEvent(), event()
8710 void QWidget::leaveEvent(QEvent *)
8715 \fn void QWidget::paintEvent(QPaintEvent *event)
8717 This event handler can be reimplemented in a subclass to receive paint
8718 events passed in \a event.
8720 A paint event is a request to repaint all or part of a widget. It can
8721 happen for one of the following reasons:
8724 \o repaint() or update() was invoked,
8725 \o the widget was obscured and has now been uncovered, or
8726 \o many other reasons.
8729 Many widgets can simply repaint their entire surface when asked to, but
8730 some slow widgets need to optimize by painting only the requested region:
8731 QPaintEvent::region(). This speed optimization does not change the result,
8732 as painting is clipped to that region during event processing. QListView
8733 and QTableView do this, for example.
8735 Qt also tries to speed up painting by merging multiple paint events into
8736 one. When update() is called several times or the window system sends
8737 several paint events, Qt merges these events into one event with a larger
8738 region (see QRegion::united()). The repaint() function does not permit this
8739 optimization, so we suggest using update() whenever possible.
8741 When the paint event occurs, the update region has normally been erased, so
8742 you are painting on the widget's background.
8744 The background can be set using setBackgroundRole() and setPalette().
8746 Since Qt 4.0, QWidget automatically double-buffers its painting, so there
8747 is no need to write double-buffering code in paintEvent() to avoid flicker.
8749 \bold{Note for the X11 platform}: It is possible to toggle global double
8750 buffering by calling \c qt_x11_set_global_double_buffer(). For example,
8752 \snippet doc/src/snippets/code/src_gui_kernel_qwidget.cpp 14
8754 \note Generally, you should refrain from calling update() or repaint()
8755 \bold{inside} a paintEvent(). For example, calling update() or repaint() on
8756 children inside a paintevent() results in undefined behavior; the child may
8757 or may not get a paint event.
8759 \warning If you are using a custom paint engine without Qt's backingstore,
8760 Qt::WA_PaintOnScreen must be set. Otherwise, QWidget::paintEngine() will
8761 never be called; the backingstore will be used instead.
8763 \sa event(), repaint(), update(), QPainter, QPixmap, QPaintEvent,
8764 {Analog Clock Example}
8767 void QWidget::paintEvent(QPaintEvent *)
8773 \fn void QWidget::moveEvent(QMoveEvent *event)
8775 This event handler can be reimplemented in a subclass to receive
8776 widget move events which are passed in the \a event parameter.
8777 When the widget receives this event, it is already at the new
8780 The old position is accessible through QMoveEvent::oldPos().
8782 \sa resizeEvent(), event(), move(), QMoveEvent
8785 void QWidget::moveEvent(QMoveEvent *)
8791 This event handler can be reimplemented in a subclass to receive
8792 widget resize events which are passed in the \a event parameter.
8793 When resizeEvent() is called, the widget already has its new
8794 geometry. The old size is accessible through
8795 QResizeEvent::oldSize().
8797 The widget will be erased and receive a paint event immediately
8798 after processing the resize event. No drawing need be (or should
8799 be) done inside this handler.
8802 \sa moveEvent(), event(), resize(), QResizeEvent, paintEvent(),
8806 void QWidget::resizeEvent(QResizeEvent * /* event */)
8810 #ifndef QT_NO_ACTION
8812 \fn void QWidget::actionEvent(QActionEvent *event)
8814 This event handler is called with the given \a event whenever the
8815 widget's actions are changed.
8817 \sa addAction(), insertAction(), removeAction(), actions(), QActionEvent
8819 void QWidget::actionEvent(QActionEvent *)
8826 This event handler is called with the given \a event when Qt receives a window
8827 close request for a top-level widget from the window system.
8829 By default, the event is accepted and the widget is closed. You can reimplement
8830 this function to change the way the widget responds to window close requests.
8831 For example, you can prevent the window from closing by calling \l{QEvent::}{ignore()}
8834 Main window applications typically use reimplementations of this function to check
8835 whether the user's work has been saved and ask for permission before closing.
8836 For example, the \l{Application Example} uses a helper function to determine whether
8837 or not to close the window:
8839 \snippet mainwindows/application/mainwindow.cpp 3
8840 \snippet mainwindows/application/mainwindow.cpp 4
8842 \sa event(), hide(), close(), QCloseEvent, {Application Example}
8845 void QWidget::closeEvent(QCloseEvent *event)
8850 #ifndef QT_NO_CONTEXTMENU
8852 This event handler, for event \a event, can be reimplemented in a
8853 subclass to receive widget context menu events.
8855 The handler is called when the widget's \l contextMenuPolicy is
8856 Qt::DefaultContextMenu.
8858 The default implementation ignores the context event.
8859 See the \l QContextMenuEvent documentation for more details.
8861 \sa event(), QContextMenuEvent customContextMenuRequested()
8864 void QWidget::contextMenuEvent(QContextMenuEvent *event)
8868 #endif // QT_NO_CONTEXTMENU
8872 This event handler, for event \a event, can be reimplemented in a
8873 subclass to receive Input Method composition events. This handler
8874 is called when the state of the input method changes.
8876 Note that when creating custom text editing widgets, the
8877 Qt::WA_InputMethodEnabled window attribute must be set explicitly
8878 (using the setAttribute() function) in order to receive input
8881 The default implementation calls event->ignore(), which rejects the
8882 Input Method event. See the \l QInputMethodEvent documentation for more
8885 \sa event(), QInputMethodEvent
8887 void QWidget::inputMethodEvent(QInputMethodEvent *event)
8893 This method is only relevant for input widgets. It is used by the
8894 input method to query a set of properties of the widget to be
8895 able to support complex input method operations as support for
8896 surrounding text and reconversions.
8898 \a query specifies which property is queried.
8900 \sa inputMethodEvent(), QInputMethodEvent, QInputContext, inputMethodHints
8902 QVariant QWidget::inputMethodQuery(Qt::InputMethodQuery query) const
8905 case Qt::ImCursorRectangle:
8906 return QRect(width()/2, 0, 1, height());
8909 case Qt::ImAnchorPosition:
8911 return inputMethodQuery(Qt::ImCursorPosition);
8913 return (int)inputMethodHints();
8920 \property QWidget::inputMethodHints
8921 \brief What input method specific hints the widget has.
8923 This is only relevant for input widgets. It is used by
8924 the input method to retrieve hints as to how the input method
8925 should operate. For example, if the Qt::ImhFormattedNumbersOnly flag
8926 is set, the input method may change its visual components to reflect
8927 that only numbers can be entered.
8929 \note The flags are only hints, so the particular input method
8930 implementation is free to ignore them. If you want to be
8931 sure that a certain type of characters are entered,
8932 you should also set a QValidator on the widget.
8934 The default value is Qt::ImhNone.
8938 \sa inputMethodQuery(), QInputContext
8940 Qt::InputMethodHints QWidget::inputMethodHints() const
8943 const QWidgetPrivate *priv = d_func();
8944 while (priv->inheritsInputMethodHints) {
8945 priv = priv->q_func()->parentWidget()->d_func();
8948 return priv->imHints;
8954 void QWidget::setInputMethodHints(Qt::InputMethodHints hints)
8959 qApp->inputPanel()->update(Qt::ImHints);
8964 #ifndef QT_NO_DRAGANDDROP
8967 \fn void QWidget::dragEnterEvent(QDragEnterEvent *event)
8969 This event handler is called when a drag is in progress and the
8970 mouse enters this widget. The event is passed in the \a event parameter.
8972 If the event is ignored, the widget won't receive any \l{dragMoveEvent()}{drag
8975 See the \link dnd.html Drag-and-drop documentation\endlink for an
8976 overview of how to provide drag-and-drop in your application.
8978 \sa QDrag, QDragEnterEvent
8980 void QWidget::dragEnterEvent(QDragEnterEvent *)
8985 \fn void QWidget::dragMoveEvent(QDragMoveEvent *event)
8987 This event handler is called if a drag is in progress, and when
8988 any of the following conditions occur: the cursor enters this widget,
8989 the cursor moves within this widget, or a modifier key is pressed on
8990 the keyboard while this widget has the focus. The event is passed
8991 in the \a event parameter.
8993 See the \link dnd.html Drag-and-drop documentation\endlink for an
8994 overview of how to provide drag-and-drop in your application.
8996 \sa QDrag, QDragMoveEvent
8998 void QWidget::dragMoveEvent(QDragMoveEvent *)
9003 \fn void QWidget::dragLeaveEvent(QDragLeaveEvent *event)
9005 This event handler is called when a drag is in progress and the
9006 mouse leaves this widget. The event is passed in the \a event
9009 See the \link dnd.html Drag-and-drop documentation\endlink for an
9010 overview of how to provide drag-and-drop in your application.
9012 \sa QDrag, QDragLeaveEvent
9014 void QWidget::dragLeaveEvent(QDragLeaveEvent *)
9019 \fn void QWidget::dropEvent(QDropEvent *event)
9021 This event handler is called when the drag is dropped on this
9022 widget. The event is passed in the \a event parameter.
9024 See the \link dnd.html Drag-and-drop documentation\endlink for an
9025 overview of how to provide drag-and-drop in your application.
9027 \sa QDrag, QDropEvent
9029 void QWidget::dropEvent(QDropEvent *)
9033 #endif // QT_NO_DRAGANDDROP
9036 \fn void QWidget::showEvent(QShowEvent *event)
9038 This event handler can be reimplemented in a subclass to receive
9039 widget show events which are passed in the \a event parameter.
9041 Non-spontaneous show events are sent to widgets immediately
9042 before they are shown. The spontaneous show events of windows are
9043 delivered afterwards.
9045 Note: A widget receives spontaneous show and hide events when its
9046 mapping status is changed by the window system, e.g. a spontaneous
9047 hide event when the user minimizes the window, and a spontaneous
9048 show event when the window is restored again. After receiving a
9049 spontaneous hide event, a widget is still considered visible in
9050 the sense of isVisible().
9052 \sa visible, event(), QShowEvent
9054 void QWidget::showEvent(QShowEvent *)
9059 \fn void QWidget::hideEvent(QHideEvent *event)
9061 This event handler can be reimplemented in a subclass to receive
9062 widget hide events. The event is passed in the \a event parameter.
9064 Hide events are sent to widgets immediately after they have been
9067 Note: A widget receives spontaneous show and hide events when its
9068 mapping status is changed by the window system, e.g. a spontaneous
9069 hide event when the user minimizes the window, and a spontaneous
9070 show event when the window is restored again. After receiving a
9071 spontaneous hide event, a widget is still considered visible in
9072 the sense of isVisible().
9074 \sa visible, event(), QHideEvent
9076 void QWidget::hideEvent(QHideEvent *)
9081 \fn QWidget::x11Event(MSG *)
9083 This special event handler can be reimplemented in a subclass to receive
9086 In your reimplementation of this function, if you want to stop Qt from
9087 handling the event, return true. If you return false, this native event
9088 is passed back to Qt, which translates it into a Qt event and sends it to
9091 \note Events are only delivered to this event handler if the widget is
9094 \warning This function is not portable.
9096 \sa QApplication::x11EventFilter(), QWidget::winId()
9100 #if defined(Q_WS_MAC)
9103 \fn bool QWidget::macEvent(EventHandlerCallRef caller, EventRef event)
9105 This special event handler can be reimplemented in a subclass to
9106 receive native Macintosh events.
9108 The parameters are a bit different depending if Qt is build against Carbon
9109 or Cocoa. In Carbon, \a caller and \a event are the corresponding
9110 EventHandlerCallRef and EventRef that correspond to the Carbon event
9111 handlers that are installed. In Cocoa, \a caller is always 0 and the
9112 EventRef is the EventRef generated from the NSEvent.
9114 In your reimplementation of this function, if you want to stop the
9115 event being handled by Qt, return true. If you return false, this
9116 native event is passed back to Qt, which translates the event into
9117 a Qt event and sends it to the widget.
9119 \warning This function is not portable.
9121 \warning This function was not called inside of Qt until Qt 4.4.
9122 If you need compatibility with earlier versions of Qt, consider QApplication::macEventFilter() instead.
9124 \sa QApplication::macEventFilter()
9127 bool QWidget::macEvent(EventHandlerCallRef, EventRef)
9133 #if defined(Q_WS_WIN)
9136 This special event handler can be reimplemented in a subclass to
9137 receive native Windows events which are passed in the \a message
9140 In your reimplementation of this function, if you want to stop the
9141 event being handled by Qt, return true and set \a result to the value
9142 that the window procedure should return. If you return false, this
9143 native event is passed back to Qt, which translates the event into
9144 a Qt event and sends it to the widget.
9146 \warning This function is not portable.
9148 \sa QApplication::winEventFilter()
9150 bool QWidget::winEvent(MSG *message, long *result)
9158 #if defined(Q_WS_X11)
9161 \fn bool QWidget::x11Event(XEvent *event)
9163 This special event handler can be reimplemented in a subclass to receive
9164 native X11 events passed in the \a event parameter.
9166 In your reimplementation of this function, if you want to stop Qt from
9167 handling the event, return true. If you return false, this native event
9168 is passed back to Qt, which translates it into a Qt event and sends it to
9171 \note Events are only delivered to this event handler if the widget is
9174 \warning This function is not portable.
9176 \sa QApplication::x11EventFilter(), QWidget::winId()
9178 bool QWidget::x11Event(XEvent *)
9186 Ensures that the widget has been polished by QStyle (i.e., has a
9187 proper font and palette).
9189 QWidget calls this function after it has been fully constructed
9190 but before it is shown the very first time. You can call this
9191 function if you want to ensure that the widget is polished before
9192 doing an operation, e.g., the correct font size might be needed in
9193 the widget's sizeHint() reimplementation. Note that this function
9194 \e is called from the default implementation of sizeHint().
9196 Polishing is useful for final initialization that must happen after
9197 all constructors (from base classes as well as from subclasses)
9200 If you need to change some settings when a widget is polished,
9201 reimplement event() and handle the QEvent::Polish event type.
9203 \bold{Note:} The function is declared const so that it can be called from
9204 other const functions (e.g., sizeHint()).
9208 void QWidget::ensurePolished() const
9212 const QMetaObject *m = metaObject();
9213 if (m == d->polished)
9217 QEvent e(QEvent::Polish);
9218 QCoreApplication::sendEvent(const_cast<QWidget *>(this), &e);
9220 // polish children after 'this'
9221 QList<QObject*> children = d->children;
9222 for (int i = 0; i < children.size(); ++i) {
9223 QObject *o = children.at(i);
9224 if(!o->isWidgetType())
9226 if (QWidget *w = qobject_cast<QWidget *>(o))
9227 w->ensurePolished();
9230 if (d->parent && d->sendChildEvents) {
9231 QChildEvent e(QEvent::ChildPolished, const_cast<QWidget *>(this));
9232 QCoreApplication::sendEvent(d->parent, &e);
9235 if (d->extra && d->extra->topextra && d->extra->topextra->window
9236 && d->extra->topextra->window->objectName().isEmpty()) {
9237 QString on = objectName();
9239 on = QString::fromUtf8(metaObject()->className());
9240 on += QLatin1String("Class");
9242 on += QLatin1String("Window");
9243 d->extra->topextra->window->setObjectName(on);
9249 Returns the mask currently set on a widget. If no mask is set the
9250 return value will be an empty region.
9252 \sa setMask(), clearMask(), QRegion::isEmpty(), {Shaped Clock Example}
9254 QRegion QWidget::mask() const
9257 return d->extra ? d->extra->mask : QRegion();
9261 Returns the layout manager that is installed on this widget, or 0
9262 if no layout manager is installed.
9264 The layout manager sets the geometry of the widget's children
9265 that have been added to the layout.
9267 \sa setLayout(), sizePolicy(), {Layout Management}
9269 QLayout *QWidget::layout() const
9271 return d_func()->layout;
9276 \fn void QWidget::setLayout(QLayout *layout)
9278 Sets the layout manager for this widget to \a layout.
9280 If there already is a layout manager installed on this widget,
9281 QWidget won't let you install another. You must first delete the
9282 existing layout manager (returned by layout()) before you can
9283 call setLayout() with the new layout.
9285 If \a layout is the layout manger on a different widget, setLayout()
9286 will reparent the layout and make it the layout manager for this widget.
9290 \snippet examples/uitools/textfinder/textfinder.cpp 3b
9292 An alternative to calling this function is to pass this widget to
9293 the layout's constructor.
9295 The QWidget will take ownership of \a layout.
9297 \sa layout(), {Layout Management}
9300 void QWidget::setLayout(QLayout *l)
9303 qWarning("QWidget::setLayout: Cannot set layout to 0");
9308 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", which already has a"
9309 " layout", l->objectName().toLocal8Bit().data(), metaObject()->className(),
9310 objectName().toLocal8Bit().data());
9314 QObject *oldParent = l->parent();
9315 if (oldParent && oldParent != this) {
9316 if (oldParent->isWidgetType()) {
9317 // Steal the layout off a widget parent. Takes effect when
9318 // morphing laid-out container widgets in Designer.
9319 QWidget *oldParentWidget = static_cast<QWidget *>(oldParent);
9320 oldParentWidget->takeLayout();
9322 qWarning("QWidget::setLayout: Attempting to set QLayout \"%s\" on %s \"%s\", when the QLayout already has a parent",
9323 l->objectName().toLocal8Bit().data(), metaObject()->className(),
9324 objectName().toLocal8Bit().data());
9330 l->d_func()->topLevel = true;
9332 if (oldParent != this) {
9334 l->d_func()->reparentChildWidgets(this);
9338 if (isWindow() && d->maybeTopData())
9339 d->topData()->sizeAdjusted = false;
9343 \fn QLayout *QWidget::takeLayout()
9345 Remove the layout from the widget.
9349 QLayout *QWidget::takeLayout()
9352 QLayout *l = layout();
9361 \property QWidget::sizePolicy
9362 \brief the default layout behavior of the widget
9364 If there is a QLayout that manages this widget's children, the
9365 size policy specified by that layout is used. If there is no such
9366 QLayout, the result of this function is used.
9368 The default policy is Preferred/Preferred, which means that the
9369 widget can be freely resized, but prefers to be the size
9370 sizeHint() returns. Button-like widgets set the size policy to
9371 specify that they may stretch horizontally, but are fixed
9372 vertically. The same applies to lineedit controls (such as
9373 QLineEdit, QSpinBox or an editable QComboBox) and other
9374 horizontally orientated widgets (such as QProgressBar).
9375 QToolButton's are normally square, so they allow growth in both
9376 directions. Widgets that support different directions (such as
9377 QSlider, QScrollBar or QHeader) specify stretching in the
9378 respective direction only. Widgets that can provide scroll bars
9379 (usually subclasses of QScrollArea) tend to specify that they can
9380 use additional space, and that they can make do with less than
9383 \sa sizeHint() QLayout QSizePolicy updateGeometry()
9385 QSizePolicy QWidget::sizePolicy() const
9388 return d->size_policy;
9391 void QWidget::setSizePolicy(QSizePolicy policy)
9394 setAttribute(Qt::WA_WState_OwnSizePolicy);
9395 if (policy == d->size_policy)
9397 d->size_policy = policy;
9399 #ifndef QT_NO_GRAPHICSVIEW
9400 if (QWExtra *extra = d->extra) {
9401 if (extra->proxyWidget)
9402 extra->proxyWidget->setSizePolicy(policy);
9408 if (isWindow() && d->maybeTopData())
9409 d->topData()->sizeAdjusted = false;
9413 \fn void QWidget::setSizePolicy(QSizePolicy::Policy horizontal, QSizePolicy::Policy vertical)
9416 Sets the size policy of the widget to \a horizontal and \a
9417 vertical, with standard stretch and no height-for-width.
9419 \sa QSizePolicy::QSizePolicy()
9423 Returns the preferred height for this widget, given the width \a w.
9425 If this widget has a layout, the default implementation returns
9426 the layout's preferred height. if there is no layout, the default
9427 implementation returns -1 indicating that the preferred height
9428 does not depend on the width.
9431 int QWidget::heightForWidth(int w) const
9433 if (layout() && layout()->hasHeightForWidth())
9434 return layout()->totalHeightForWidth(w);
9444 This is a bit hackish, but ideally we would have created a virtual function
9445 in the public API (however, too late...) so that subclasses could reimplement
9447 Instead we add a virtual function to QWidgetPrivate.
9448 ### Qt5: move to public class and make virtual
9450 bool QWidgetPrivate::hasHeightForWidth() const
9452 return layout ? layout->hasHeightForWidth() : size_policy.hasHeightForWidth();
9456 \fn QWidget *QWidget::childAt(int x, int y) const
9458 Returns the visible child widget at the position (\a{x}, \a{y})
9459 in the widget's coordinate system. If there is no visible child
9460 widget at the specified position, the function returns 0.
9466 Returns the visible child widget at point \a p in the widget's own
9470 QWidget *QWidget::childAt(const QPoint &p) const
9472 return d_func()->childAt_helper(p, false);
9475 QWidget *QWidgetPrivate::childAt_helper(const QPoint &p, bool ignoreChildrenInDestructor) const
9477 if (children.isEmpty())
9482 // Unified tool bars on the Mac require special handling since they live outside
9483 // QMainWindow's geometry(). See commit: 35667fd45ada49269a5987c235fdedfc43e92bb8
9484 bool includeFrame = q->isWindow() && qobject_cast<const QMainWindow *>(q)
9485 && static_cast<const QMainWindow *>(q)->unifiedTitleAndToolBarOnMac();
9487 return childAtRecursiveHelper(p, ignoreChildrenInDestructor, includeFrame);
9490 if (!pointInsideRectAndMask(p))
9492 return childAtRecursiveHelper(p, ignoreChildrenInDestructor);
9495 QWidget *QWidgetPrivate::childAtRecursiveHelper(const QPoint &p, bool ignoreChildrenInDestructor, bool includeFrame) const
9498 Q_UNUSED(includeFrame);
9500 for (int i = children.size() - 1; i >= 0; --i) {
9501 QWidget *child = qobject_cast<QWidget *>(children.at(i));
9502 if (!child || child->isWindow() || child->isHidden() || child->testAttribute(Qt::WA_TransparentForMouseEvents)
9503 || (ignoreChildrenInDestructor && child->data->in_destructor)) {
9507 // Map the point 'p' from parent coordinates to child coordinates.
9508 QPoint childPoint = p;
9510 // 'includeFrame' is true if the child's parent is a top-level QMainWindow with an unified tool bar.
9511 // An unified tool bar on the Mac lives outside QMainWindow's geometry(), so a normal
9512 // QWidget::mapFromParent won't do the trick.
9513 if (includeFrame && qobject_cast<QToolBar *>(child))
9514 childPoint = qt_mac_nativeMapFromParent(child, p);
9517 childPoint -= child->data->crect.topLeft();
9519 // Check if the point hits the child.
9520 if (!child->d_func()->pointInsideRectAndMask(childPoint))
9523 // Do the same for the child's descendants.
9524 if (QWidget *w = child->d_func()->childAtRecursiveHelper(childPoint, ignoreChildrenInDestructor))
9527 // We have found our target; namely the child at position 'p'.
9533 void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
9537 widgetItem->invalidateSizeCache();
9539 if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
9540 if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
9541 if (parent->d_func()->layout)
9542 parent->d_func()->layout->invalidate();
9543 else if (parent->isVisible())
9544 QApplication::postEvent(parent, new QEvent(QEvent::LayoutRequest));
9550 Notifies the layout system that this widget has changed and may
9551 need to change geometry.
9553 Call this function if the sizeHint() or sizePolicy() have changed.
9555 For explicitly hidden widgets, updateGeometry() is a no-op. The
9556 layout system will be notified as soon as the widget is shown.
9559 void QWidget::updateGeometry()
9562 d->updateGeometry_helper(false);
9565 /*! \property QWidget::windowFlags
9567 Window flags are a combination of a type (e.g. Qt::Dialog) and
9568 zero or more hints to the window system (e.g.
9569 Qt::FramelessWindowHint).
9571 If the widget had type Qt::Widget or Qt::SubWindow and becomes a
9572 window (Qt::Window, Qt::Dialog, etc.), it is put at position (0,
9573 0) on the desktop. If the widget is a window and becomes a
9574 Qt::Widget or Qt::SubWindow, it is put at position (0, 0)
9575 relative to its parent widget.
9577 \note This function calls setParent() when changing the flags for
9578 a window, causing the widget to be hidden. You must call show() to make
9579 the widget visible again..
9581 \sa windowType(), {Window Flags Example}
9583 void QWidget::setWindowFlags(Qt::WindowFlags flags)
9585 if (data->window_flags == flags)
9590 if ((data->window_flags | flags) & Qt::Window) {
9591 // the old type was a window and/or the new type is a window
9592 QPoint oldPos = pos();
9593 bool visible = isVisible();
9594 setParent(parentWidget(), flags);
9596 // if both types are windows or neither of them are, we restore
9598 if (!((data->window_flags ^ flags) & Qt::Window)
9599 && (visible || testAttribute(Qt::WA_Moved))) {
9602 // for backward-compatibility we change Qt::WA_QuitOnClose attribute value only when the window was recreated.
9603 d->adjustQuitOnCloseAttribute();
9605 data->window_flags = flags;
9610 Sets the window flags for the widget to \a flags,
9611 \e without telling the window system.
9613 \warning Do not call this function unless you really know what
9616 \sa setWindowFlags()
9618 void QWidget::overrideWindowFlags(Qt::WindowFlags flags)
9620 data->window_flags = flags;
9624 \fn Qt::WindowType QWidget::windowType() const
9626 Returns the window type of this widget. This is identical to
9627 windowFlags() & Qt::WindowType_Mask.
9633 Sets the parent of the widget to \a parent, and resets the window
9634 flags. The widget is moved to position (0, 0) in its new parent.
9636 If the new parent widget is in a different window, the
9637 reparented widget and its children are appended to the end of the
9638 \l{setFocusPolicy()}{tab chain} of the new parent
9639 widget, in the same internal order as before. If one of the moved
9640 widgets had keyboard focus, setParent() calls clearFocus() for that
9643 If the new parent widget is in the same window as the
9644 old parent, setting the parent doesn't change the tab order or
9647 If the "new" parent widget is the old parent widget, this function
9650 \note The widget becomes invisible as part of changing its parent,
9651 even if it was previously visible. You must call show() to make the
9652 widget visible again.
9654 \warning It is very unlikely that you will ever need this
9655 function. If you have a widget that changes its content
9656 dynamically, it is far easier to use \l QStackedWidget.
9658 \sa setWindowFlags()
9660 void QWidget::setParent(QWidget *parent)
9662 if (parent == parentWidget())
9664 setParent((QWidget*)parent, windowFlags() & ~Qt::WindowType_Mask);
9670 This function also takes widget flags, \a f as an argument.
9673 void QWidget::setParent(QWidget *parent, Qt::WindowFlags f)
9676 d->inSetParent = true;
9677 bool resized = testAttribute(Qt::WA_Resized);
9678 bool wasCreated = testAttribute(Qt::WA_WState_Created);
9679 QWidget *oldtlw = window();
9681 QWidget *desktopWidget = 0;
9682 if (parent && parent->windowType() == Qt::Desktop)
9683 desktopWidget = parent;
9684 bool newParent = (parent != parentWidget()) || !wasCreated || desktopWidget;
9686 #if defined(Q_WS_X11) || defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
9687 if (newParent && parent && !desktopWidget) {
9688 if (testAttribute(Qt::WA_NativeWindow) && !qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings)
9690 // On Mac, toolbars inside the unified title bar will never overlap with
9691 // siblings in the content view. So we skip enforce native siblings in that case
9692 && !d->isInUnifiedToolbar && parentWidget() && parentWidget()->isWindow()
9695 parent->d_func()->enforceNativeChildren();
9696 else if (parent->d_func()->nativeChildrenForced() || parent->testAttribute(Qt::WA_PaintOnScreen))
9697 setAttribute(Qt::WA_NativeWindow);
9702 if (!testAttribute(Qt::WA_WState_Hidden)) {
9704 setAttribute(Qt::WA_WState_ExplicitShowHide, false);
9707 QEvent e(QEvent::ParentAboutToChange);
9708 QApplication::sendEvent(this, &e);
9711 if (newParent && isAncestorOf(focusWidget()))
9712 focusWidget()->clearFocus();
9714 QTLWExtra *oldTopExtra = window()->d_func()->maybeTopData();
9715 QWidgetBackingStoreTracker *oldBsTracker = oldTopExtra ? &oldTopExtra->backingStoreTracker : 0;
9717 d->setParent_sys(parent, f);
9719 QTLWExtra *topExtra = window()->d_func()->maybeTopData();
9720 QWidgetBackingStoreTracker *bsTracker = topExtra ? &topExtra->backingStoreTracker : 0;
9721 if (oldBsTracker && oldBsTracker != bsTracker)
9722 oldBsTracker->unregisterWidgetSubtree(this);
9727 if (QWidgetBackingStore *oldBs = oldtlw->d_func()->maybeBackingStore()) {
9729 oldBs->removeDirtyWidget(this);
9730 // Move the widget and all its static children from
9731 // the old backing store to the new one.
9732 oldBs->moveStaticWidgets(this);
9735 if ((QApplicationPrivate::app_compile_version < 0x040200
9736 || QApplicationPrivate::testAttribute(Qt::AA_ImmediateWidgetCreation))
9737 && !testAttribute(Qt::WA_WState_Created))
9740 d->reparentFocusWidgets(oldtlw);
9741 setAttribute(Qt::WA_Resized, resized);
9742 if (!testAttribute(Qt::WA_StyleSheet)
9743 && (!parent || !parent->testAttribute(Qt::WA_StyleSheet))) {
9745 d->resolvePalette();
9747 d->resolveLayoutDirection();
9750 // Note: GL widgets under WGL or EGL will always need a ParentChange
9751 // event to handle recreation/rebinding of the GL context, hence the
9752 // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all
9755 #if defined(Q_WS_WIN) || defined(QT_OPENGL_ES)
9756 || (f & Qt::MSWindowsOwnDC)
9759 // propagate enabled updates enabled state to non-windows
9761 if (!testAttribute(Qt::WA_ForceDisabled))
9762 d->setEnabled_helper(parent ? parent->isEnabled() : true);
9763 if (!testAttribute(Qt::WA_ForceUpdatesDisabled))
9764 d->setUpdatesEnabled_helper(parent ? parent->updatesEnabled() : true);
9768 // send and post remaining QObject events
9769 if (parent && d->sendChildEvents) {
9770 QChildEvent e(QEvent::ChildAdded, this);
9771 QApplication::sendEvent(parent, &e);
9774 //### already hidden above ---> must probably do something smart on the mac
9776 // extern bool qt_mac_is_macdrawer(const QWidget *); //qwidget_mac.cpp
9777 // if(!qt_mac_is_macdrawer(q)) //special case
9778 // q->setAttribute(Qt::WA_WState_Hidden);
9780 // q->setAttribute(Qt::WA_WState_Hidden);
9783 if (parent && d->sendChildEvents && d->polished) {
9784 QChildEvent e(QEvent::ChildPolished, this);
9785 QCoreApplication::sendEvent(parent, &e);
9788 QEvent e(QEvent::ParentChange);
9789 QApplication::sendEvent(this, &e);
9793 if (isWindow() || parentWidget()->isVisible())
9794 setAttribute(Qt::WA_WState_Hidden, true);
9795 else if (!testAttribute(Qt::WA_WState_ExplicitShowHide))
9796 setAttribute(Qt::WA_WState_Hidden, false);
9799 d->updateIsOpaque();
9801 #ifndef QT_NO_GRAPHICSVIEW
9802 // Embed the widget into a proxy if the parent is embedded.
9803 // ### Doesn't handle reparenting out of an embedded widget.
9804 if (oldtlw->graphicsProxyWidget()) {
9805 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(oldtlw))
9806 ancestorProxy->d_func()->unembedSubWindow(this);
9808 if (isWindow() && parent && !graphicsProxyWidget() && !bypassGraphicsProxyWidget(this)) {
9809 if (QGraphicsProxyWidget *ancestorProxy = d->nearestGraphicsProxyWidget(parent))
9810 ancestorProxy->d_func()->embedSubWindow(this);
9814 d->inSetParent = false;
9818 Scrolls the widget including its children \a dx pixels to the
9819 right and \a dy downward. Both \a dx and \a dy may be negative.
9821 After scrolling, the widgets will receive paint events for
9822 the areas that need to be repainted. For widgets that Qt knows to
9823 be opaque, this is only the newly exposed parts.
9824 For example, if an opaque widget is scrolled 8 pixels to the left,
9825 only an 8-pixel wide stripe at the right edge needs updating.
9827 Since widgets propagate the contents of their parents by default,
9828 you need to set the \l autoFillBackground property, or use
9829 setAttribute() to set the Qt::WA_OpaquePaintEvent attribute, to make
9832 For widgets that use contents propagation, a scroll will cause an
9833 update of the entire scroll area.
9835 \sa {Transparency and Double Buffering}
9838 void QWidget::scroll(int dx, int dy)
9840 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9842 if (dx == 0 && dy == 0)
9845 #ifndef QT_NO_GRAPHICSVIEW
9846 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9847 // Graphics View maintains its own dirty region as a list of rects;
9848 // until we can connect item updates directly to the view, we must
9849 // separately add a translated dirty region.
9850 if (!d->dirty.isEmpty()) {
9851 foreach (const QRect &rect, (d->dirty.translated(dx, dy)).rects())
9852 proxy->update(rect);
9854 proxy->scroll(dx, dy, proxy->subWidgetRect(this));
9858 d->setDirtyOpaqueRegion();
9859 d->scroll_sys(dx, dy);
9865 This version only scrolls \a r and does not move the children of
9868 If \a r is empty or invalid, the result is undefined.
9872 void QWidget::scroll(int dx, int dy, const QRect &r)
9875 if ((!updatesEnabled() && children().size() == 0) || !isVisible())
9877 if (dx == 0 && dy == 0)
9880 #ifndef QT_NO_GRAPHICSVIEW
9881 if (QGraphicsProxyWidget *proxy = QWidgetPrivate::nearestGraphicsProxyWidget(this)) {
9882 // Graphics View maintains its own dirty region as a list of rects;
9883 // until we can connect item updates directly to the view, we must
9884 // separately add a translated dirty region.
9885 if (!d->dirty.isEmpty()) {
9886 foreach (const QRect &rect, (d->dirty.translated(dx, dy) & r).rects())
9887 proxy->update(rect);
9889 proxy->scroll(dx, dy, r.translated(proxy->subWidgetRect(this).topLeft().toPoint()));
9893 d->scroll_sys(dx, dy, r);
9897 Repaints the widget directly by calling paintEvent() immediately,
9898 unless updates are disabled or the widget is hidden.
9900 We suggest only using repaint() if you need an immediate repaint,
9901 for example during animation. In almost all circumstances update()
9902 is better, as it permits Qt to optimize for speed and minimize
9905 \warning If you call repaint() in a function which may itself be
9906 called from paintEvent(), you may get infinite recursion. The
9907 update() function never causes recursion.
9909 \sa update(), paintEvent(), setUpdatesEnabled()
9912 void QWidget::repaint()
9919 This version repaints a rectangle (\a x, \a y, \a w, \a h) inside
9922 If \a w is negative, it is replaced with \c{width() - x}, and if
9923 \a h is negative, it is replaced width \c{height() - y}.
9925 void QWidget::repaint(int x, int y, int w, int h)
9927 if (x > data->crect.width() || y > data->crect.height())
9931 w = data->crect.width() - x;
9933 h = data->crect.height() - y;
9935 repaint(QRect(x, y, w, h));
9940 This version repaints a rectangle \a rect inside the widget.
9942 void QWidget::repaint(const QRect &rect)
9946 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9951 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
9954 if (hasBackingStoreSupport()) {
9956 if (qt_widget_private(this)->isInUnifiedToolbar) {
9957 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9961 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9962 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9963 tlwExtra->inRepaint = true;
9964 tlwExtra->backingStoreTracker->markDirty(rect, this, true);
9965 tlwExtra->inRepaint = false;
9968 d->repaint_sys(rect);
9975 This version repaints a region \a rgn inside the widget.
9977 void QWidget::repaint(const QRegion &rgn)
9981 if (testAttribute(Qt::WA_WState_ConfigPending)) {
9986 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
9989 if (hasBackingStoreSupport()) {
9991 if (qt_widget_private(this)->isInUnifiedToolbar) {
9992 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
9996 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
9997 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore) {
9998 tlwExtra->inRepaint = true;
9999 tlwExtra->backingStoreTracker->markDirty(rgn, this, true);
10000 tlwExtra->inRepaint = false;
10003 d->repaint_sys(rgn);
10008 Updates the widget unless updates are disabled or the widget is
10011 This function does not cause an immediate repaint; instead it
10012 schedules a paint event for processing when Qt returns to the main
10013 event loop. This permits Qt to optimize for more speed and less
10014 flicker than a call to repaint() does.
10016 Calling update() several times normally results in just one
10019 Qt normally erases the widget's area before the paintEvent() call.
10020 If the Qt::WA_OpaquePaintEvent widget attribute is set, the widget is
10021 responsible for painting all its pixels with an opaque color.
10023 \sa repaint() paintEvent(), setUpdatesEnabled(), {Analog Clock Example}
10025 void QWidget::update()
10030 /*! \fn void QWidget::update(int x, int y, int w, int h)
10033 This version updates a rectangle (\a x, \a y, \a w, \a h) inside
10040 This version updates a rectangle \a rect inside the widget.
10042 void QWidget::update(const QRect &rect)
10044 if (!isVisible() || !updatesEnabled() || rect.isEmpty())
10047 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
10048 QApplication::postEvent(this, new QUpdateLaterEvent(rect));
10052 if (hasBackingStoreSupport()) {
10054 if (qt_widget_private(this)->isInUnifiedToolbar) {
10055 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10059 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10060 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
10061 tlwExtra->backingStoreTracker->markDirty(rect, this);
10063 d_func()->repaint_sys(rect);
10070 This version repaints a region \a rgn inside the widget.
10072 void QWidget::update(const QRegion &rgn)
10074 if (!isVisible() || !updatesEnabled() || rgn.isEmpty())
10077 if (testAttribute(Qt::WA_WState_InPaintEvent)) {
10078 QApplication::postEvent(this, new QUpdateLaterEvent(rgn));
10082 if (hasBackingStoreSupport()) {
10084 if (qt_widget_private(this)->isInUnifiedToolbar) {
10085 qt_widget_private(this)->unifiedSurface->renderToolbar(this, true);
10089 QTLWExtra *tlwExtra = window()->d_func()->maybeTopData();
10090 if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
10091 tlwExtra->backingStoreTracker->markDirty(rgn, this);
10093 d_func()->repaint_sys(rgn);
10101 This just sets the corresponding attribute bit to 1 or 0
10103 static void setAttribute_internal(Qt::WidgetAttribute attribute, bool on, QWidgetData *data,
10106 if (attribute < int(8*sizeof(uint))) {
10108 data->widget_attributes |= (1<<attribute);
10110 data->widget_attributes &= ~(1<<attribute);
10112 const int x = attribute - 8*sizeof(uint);
10113 const int int_off = x / (8*sizeof(uint));
10115 d->high_attributes[int_off] |= (1<<(x-(int_off*8*sizeof(uint))));
10117 d->high_attributes[int_off] &= ~(1<<(x-(int_off*8*sizeof(uint))));
10122 Sets the attribute \a attribute on this widget if \a on is true;
10123 otherwise clears the attribute.
10125 \sa testAttribute()
10127 void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
10129 if (testAttribute(attribute) == on)
10133 Q_ASSERT_X(sizeof(d->high_attributes)*8 >= (Qt::WA_AttributeCount - sizeof(uint)*8),
10134 "QWidget::setAttribute(WidgetAttribute, bool)",
10135 "QWidgetPrivate::high_attributes[] too small to contain all attributes in WidgetAttribute");
10137 // ### Don't use PaintOnScreen+paintEngine() to do native painting in 5.0
10138 if (attribute == Qt::WA_PaintOnScreen && on && !inherits("QGLWidget")) {
10139 // see qwidget_win.cpp, ::paintEngine for details
10141 if (d->noPaintOnScreen)
10146 setAttribute_internal(attribute, on, data, d);
10148 switch (attribute) {
10150 #ifndef QT_NO_DRAGANDDROP
10151 case Qt::WA_AcceptDrops: {
10152 if (on && !testAttribute(Qt::WA_DropSiteRegistered))
10153 setAttribute(Qt::WA_DropSiteRegistered, true);
10154 else if (!on && (isWindow() || !parentWidget() || !parentWidget()->testAttribute(Qt::WA_DropSiteRegistered)))
10155 setAttribute(Qt::WA_DropSiteRegistered, false);
10156 QEvent e(QEvent::AcceptDropsChange);
10157 QApplication::sendEvent(this, &e);
10160 case Qt::WA_DropSiteRegistered: {
10161 d->registerDropSite(on);
10162 for (int i = 0; i < d->children.size(); ++i) {
10163 QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
10164 if (w && !w->isWindow() && !w->testAttribute(Qt::WA_AcceptDrops) && w->testAttribute(Qt::WA_DropSiteRegistered) != on)
10165 w->setAttribute(Qt::WA_DropSiteRegistered, on);
10171 case Qt::WA_NoChildEventsForParent:
10172 d->sendChildEvents = !on;
10174 case Qt::WA_NoChildEventsFromChildren:
10175 d->receiveChildEvents = !on;
10177 case Qt::WA_MacBrushedMetal:
10179 d->setStyle_helper(style(), false, true); // Make sure things get unpolished/polished correctly.
10180 // fall through since changing the metal attribute affects the opaque size grip.
10181 case Qt::WA_MacOpaqueSizeGrip:
10182 d->macUpdateOpaqueSizeGrip();
10184 case Qt::WA_MacShowFocusRect:
10191 qt_mac_update_mouseTracking(this);
10194 case Qt::WA_MacAlwaysShowToolWindow:
10196 d->macUpdateHideOnSuspend();
10199 case Qt::WA_MacNormalSize:
10200 case Qt::WA_MacSmallSize:
10201 case Qt::WA_MacMiniSize:
10204 // We can only have one of these set at a time
10205 const Qt::WidgetAttribute MacSizes[] = { Qt::WA_MacNormalSize, Qt::WA_MacSmallSize,
10206 Qt::WA_MacMiniSize };
10207 for (int i = 0; i < 3; ++i) {
10208 if (MacSizes[i] != attribute)
10209 setAttribute_internal(MacSizes[i], false, data, d);
10211 d->macUpdateSizeAttribute();
10215 case Qt::WA_ShowModal:
10218 QApplicationPrivate::leaveModal(this);
10219 // reset modality type to Modeless when clearing WA_ShowModal
10220 data->window_modality = Qt::NonModal;
10221 } else if (data->window_modality == Qt::NonModal) {
10222 // determine the modality type if it hasn't been set prior
10223 // to setting WA_ShowModal. set the default to WindowModal
10224 // if we are the child of a group leader; otherwise use
10225 // ApplicationModal.
10226 QWidget *w = parentWidget();
10229 while (w && !w->testAttribute(Qt::WA_GroupLeader)) {
10230 w = w->parentWidget();
10234 data->window_modality = (w && w->testAttribute(Qt::WA_GroupLeader))
10236 : Qt::ApplicationModal;
10237 // Some window managers does not allow us to enter modal after the
10238 // window is showing. Therefore, to be consistent, we cannot call
10239 // QApplicationPrivate::enterModal(this) here. The window must be
10240 // hidden before changing modality.
10242 if (testAttribute(Qt::WA_WState_Created)) {
10243 // don't call setModal_sys() before create_sys()
10247 case Qt::WA_MouseTracking: {
10248 QEvent e(QEvent::MouseTrackingChange);
10249 QApplication::sendEvent(this, &e);
10251 case Qt::WA_NativeWindow: {
10252 #if defined(Q_WS_QPA)
10253 d->createTLExtra();
10256 QWidget *focusWidget = d->effectiveFocusWidget();
10257 if (on && !internalWinId() && hasFocus()
10258 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10259 qApp->inputPanel()->commit();
10260 qApp->inputPanel()->setInputItem(0);
10262 if (!qApp->testAttribute(Qt::AA_DontCreateNativeWidgetSiblings) && parentWidget()
10264 // On Mac, toolbars inside the unified title bar will never overlap with
10265 // siblings in the content view. So we skip enforce native siblings in that case
10266 && !d->isInUnifiedToolbar && parentWidget()->isWindow()
10269 parentWidget()->d_func()->enforceNativeChildren();
10270 if (on && !internalWinId() && testAttribute(Qt::WA_WState_Created))
10272 if (isEnabled() && focusWidget->isEnabled()
10273 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10274 qApp->inputPanel()->setInputItem(focusWidget);
10279 case Qt::WA_PaintOnScreen:
10280 d->updateIsOpaque();
10281 #if defined(Q_WS_WIN) || defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
10282 // Recreate the widget if it's already created as an alien widget and
10283 // WA_PaintOnScreen is enabled. Paint on screen widgets must have win id.
10284 // So must their children.
10286 setAttribute(Qt::WA_NativeWindow);
10287 d->enforceNativeChildren();
10291 case Qt::WA_OpaquePaintEvent:
10292 d->updateIsOpaque();
10294 case Qt::WA_NoSystemBackground:
10295 d->updateIsOpaque();
10297 case Qt::WA_UpdatesDisabled:
10298 d->updateSystemBackground();
10300 case Qt::WA_TransparentForMouseEvents:
10302 d->macUpdateIgnoreMouseEvents();
10305 case Qt::WA_InputMethodEnabled: {
10307 QWidget *focusWidget = d->effectiveFocusWidget();
10308 if (on && hasFocus() && isEnabled()
10309 && focusWidget->testAttribute(Qt::WA_InputMethodEnabled)) {
10310 qApp->inputPanel()->setInputItem(focusWidget);
10311 } else if (!on && qApp->inputPanel()->inputItem() == focusWidget) {
10312 qApp->inputPanel()->commit();
10313 qApp->inputPanel()->setInputItem(0);
10318 case Qt::WA_WindowPropagation:
10319 d->resolvePalette();
10321 d->resolveLocale();
10324 case Qt::WA_NoX11EventCompression:
10327 d->extra->compress_events = on;
10329 case Qt::WA_X11OpenGLOverlay:
10330 d->updateIsOpaque();
10332 case Qt::WA_X11DoNotAcceptFocus:
10333 if (testAttribute(Qt::WA_WState_Created))
10334 d->updateX11AcceptFocus();
10337 case Qt::WA_DontShowOnScreen: {
10338 if (on && isVisible()) {
10339 // Make sure we keep the current state and only hide the widget
10340 // from the desktop. show_sys will only update platform specific
10341 // attributes at this point.
10349 case Qt::WA_X11NetWmWindowTypeDesktop:
10350 case Qt::WA_X11NetWmWindowTypeDock:
10351 case Qt::WA_X11NetWmWindowTypeToolBar:
10352 case Qt::WA_X11NetWmWindowTypeMenu:
10353 case Qt::WA_X11NetWmWindowTypeUtility:
10354 case Qt::WA_X11NetWmWindowTypeSplash:
10355 case Qt::WA_X11NetWmWindowTypeDialog:
10356 case Qt::WA_X11NetWmWindowTypeDropDownMenu:
10357 case Qt::WA_X11NetWmWindowTypePopupMenu:
10358 case Qt::WA_X11NetWmWindowTypeToolTip:
10359 case Qt::WA_X11NetWmWindowTypeNotification:
10360 case Qt::WA_X11NetWmWindowTypeCombo:
10361 case Qt::WA_X11NetWmWindowTypeDND:
10362 if (testAttribute(Qt::WA_WState_Created))
10363 d->setNetWmWindowTypes();
10367 case Qt::WA_StaticContents:
10368 if (QWidgetBackingStore *bs = d->maybeBackingStore()) {
10370 bs->addStaticWidget(this);
10372 bs->removeStaticWidget(this);
10375 case Qt::WA_TranslucentBackground:
10377 setAttribute(Qt::WA_NoSystemBackground);
10378 d->updateIsTranslucent();
10382 case Qt::WA_AcceptTouchEvents:
10383 #if defined(Q_WS_WIN) || defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
10385 d->registerTouchWindow();
10388 case Qt::WA_LockPortraitOrientation:
10389 case Qt::WA_LockLandscapeOrientation:
10390 case Qt::WA_AutoOrientation: {
10391 const Qt::WidgetAttribute orientations[3] = {
10392 Qt::WA_LockPortraitOrientation,
10393 Qt::WA_LockLandscapeOrientation,
10394 Qt::WA_AutoOrientation
10398 // We can only have one of these set at a time
10399 for (int i = 0; i < 3; ++i) {
10400 if (orientations[i] != attribute)
10401 setAttribute_internal(orientations[i], false, data, d);
10406 CAknAppUiBase* appUi = static_cast<CAknAppUiBase*>(CEikonEnv::Static()->EikAppUi());
10407 const CAknAppUiBase::TAppUiOrientation s60orientations[] = {
10408 CAknAppUiBase::EAppUiOrientationPortrait,
10409 CAknAppUiBase::EAppUiOrientationLandscape,
10410 CAknAppUiBase::EAppUiOrientationAutomatic
10412 CAknAppUiBase::TAppUiOrientation s60orientation = CAknAppUiBase::EAppUiOrientationUnspecified;
10413 for (int i = 0; i < 3; ++i) {
10414 if (testAttribute(orientations[i])) {
10415 s60orientation = s60orientations[i];
10419 QT_TRAP_THROWING(appUi->SetOrientationL(s60orientation));
10420 S60->orientationSet = true;
10421 QSymbianControl *window = static_cast<QSymbianControl *>(internalWinId());
10423 window->ensureFixNativeOrientation();
10432 /*! \fn bool QWidget::testAttribute(Qt::WidgetAttribute attribute) const
10434 Returns true if attribute \a attribute is set on this widget;
10435 otherwise returns false.
10439 bool QWidget::testAttribute_helper(Qt::WidgetAttribute attribute) const
10441 Q_D(const QWidget);
10442 const int x = attribute - 8*sizeof(uint);
10443 const int int_off = x / (8*sizeof(uint));
10444 return (d->high_attributes[int_off] & (1<<(x-(int_off*8*sizeof(uint)))));
10448 \property QWidget::windowOpacity
10450 \brief The level of opacity for the window.
10452 The valid range of opacity is from 1.0 (completely opaque) to
10453 0.0 (completely transparent).
10455 By default the value of this property is 1.0.
10457 This feature is available on Embedded Linux, Mac OS X, Windows,
10458 and X11 platforms that support the Composite extension.
10460 This feature is not available on Windows CE.
10462 Note that under X11 you need to have a composite manager running,
10463 and the X11 specific _NET_WM_WINDOW_OPACITY atom needs to be
10464 supported by the window manager you are using.
10466 \warning Changing this property from opaque to transparent might issue a
10467 paint event that needs to be processed before the window is displayed
10468 correctly. This affects mainly the use of QPixmap::grabWindow(). Also note
10469 that semi-transparent windows update and resize significantly slower than
10474 qreal QWidget::windowOpacity() const
10476 Q_D(const QWidget);
10477 return (isWindow() && d->maybeTopData()) ? d->maybeTopData()->opacity / 255. : 1.0;
10480 void QWidget::setWindowOpacity(qreal opacity)
10486 opacity = qBound(qreal(0.0), opacity, qreal(1.0));
10487 QTLWExtra *extra = d->topData();
10488 extra->opacity = uint(opacity * 255);
10489 setAttribute(Qt::WA_WState_WindowOpacitySet);
10491 if (!testAttribute(Qt::WA_WState_Created))
10494 #ifndef QT_NO_GRAPHICSVIEW
10495 if (QGraphicsProxyWidget *proxy = graphicsProxyWidget()) {
10496 // Avoid invalidating the cache if set.
10497 if (proxy->cacheMode() == QGraphicsItem::NoCache)
10499 else if (QGraphicsScene *scene = proxy->scene())
10500 scene->update(proxy->sceneBoundingRect());
10505 d->setWindowOpacity_sys(opacity);
10509 \property QWidget::windowModified
10510 \brief whether the document shown in the window has unsaved changes
10512 A modified window is a window whose content has changed but has
10513 not been saved to disk. This flag will have different effects
10514 varied by the platform. On Mac OS X the close button will have a
10515 modified look; on other platforms, the window title will have an
10518 The window title must contain a "[*]" placeholder, which
10519 indicates where the '*' should appear. Normally, it should appear
10520 right after the file name (e.g., "document1.txt[*] - Text
10521 Editor"). If the window isn't modified, the placeholder is simply
10524 Note that if a widget is set as modified, all its ancestors will
10525 also be set as modified. However, if you call \c
10526 {setWindowModified(false)} on a widget, this will not propagate to
10527 its parent because other children of the parent might have been
10530 \sa windowTitle, {Application Example}, {SDI Example}, {MDI Example}
10532 bool QWidget::isWindowModified() const
10534 return testAttribute(Qt::WA_WindowModified);
10537 void QWidget::setWindowModified(bool mod)
10540 setAttribute(Qt::WA_WindowModified, mod);
10543 if (!windowTitle().contains(QLatin1String("[*]")) && mod)
10544 qWarning("QWidget::setWindowModified: The window title does not contain a '[*]' placeholder");
10546 d->setWindowTitle_helper(windowTitle());
10547 d->setWindowIconText_helper(windowIconText());
10549 d->setWindowModified_sys(mod);
10552 QEvent e(QEvent::ModifiedChange);
10553 QApplication::sendEvent(this, &e);
10556 #ifndef QT_NO_TOOLTIP
10558 \property QWidget::toolTip
10560 \brief the widget's tooltip
10562 Note that by default tooltips are only shown for widgets that are
10563 children of the active window. You can change this behavior by
10564 setting the attribute Qt::WA_AlwaysShowToolTips on the \e window,
10565 not on the widget with the tooltip.
10567 If you want to control a tooltip's behavior, you can intercept the
10568 event() function and catch the QEvent::ToolTip event (e.g., if you
10569 want to customize the area for which the tooltip should be shown).
10571 By default, this property contains an empty string.
10573 \sa QToolTip statusTip whatsThis
10575 void QWidget::setToolTip(const QString &s)
10580 QEvent event(QEvent::ToolTipChange);
10581 QApplication::sendEvent(this, &event);
10584 QString QWidget::toolTip() const
10586 Q_D(const QWidget);
10589 #endif // QT_NO_TOOLTIP
10592 #ifndef QT_NO_STATUSTIP
10594 \property QWidget::statusTip
10595 \brief the widget's status tip
10597 By default, this property contains an empty string.
10599 \sa toolTip whatsThis
10601 void QWidget::setStatusTip(const QString &s)
10607 QString QWidget::statusTip() const
10609 Q_D(const QWidget);
10610 return d->statusTip;
10612 #endif // QT_NO_STATUSTIP
10614 #ifndef QT_NO_WHATSTHIS
10616 \property QWidget::whatsThis
10618 \brief the widget's What's This help text.
10620 By default, this property contains an empty string.
10622 \sa QWhatsThis QWidget::toolTip QWidget::statusTip
10624 void QWidget::setWhatsThis(const QString &s)
10630 QString QWidget::whatsThis() const
10632 Q_D(const QWidget);
10633 return d->whatsThis;
10635 #endif // QT_NO_WHATSTHIS
10637 #ifndef QT_NO_ACCESSIBILITY
10639 \property QWidget::accessibleName
10641 \brief the widget's name as seen by assistive technologies
10643 This property is used by accessible clients to identify, find, or announce
10644 the widget for accessible clients.
10646 By default, this property contains an empty string.
10648 \sa QAccessibleInterface::text()
10650 void QWidget::setAccessibleName(const QString &name)
10653 d->accessibleName = name;
10654 QAccessible::updateAccessibility(this, 0, QAccessible::NameChanged);
10657 QString QWidget::accessibleName() const
10659 Q_D(const QWidget);
10660 return d->accessibleName;
10664 \property QWidget::accessibleDescription
10666 \brief the widget's description as seen by assistive technologies
10668 By default, this property contains an empty string.
10670 \sa QAccessibleInterface::text()
10672 void QWidget::setAccessibleDescription(const QString &description)
10675 d->accessibleDescription = description;
10676 QAccessible::updateAccessibility(this, 0, QAccessible::DescriptionChanged);
10679 QString QWidget::accessibleDescription() const
10681 Q_D(const QWidget);
10682 return d->accessibleDescription;
10684 #endif // QT_NO_ACCESSIBILITY
10686 #ifndef QT_NO_SHORTCUT
10688 Adds a shortcut to Qt's shortcut system that watches for the given
10689 \a key sequence in the given \a context. If the \a context is
10690 Qt::ApplicationShortcut, the shortcut applies to the application as a
10691 whole. Otherwise, it is either local to this widget, Qt::WidgetShortcut,
10692 or to the window itself, Qt::WindowShortcut.
10694 If the same \a key sequence has been grabbed by several widgets,
10695 when the \a key sequence occurs a QEvent::Shortcut event is sent
10696 to all the widgets to which it applies in a non-deterministic
10697 order, but with the ``ambiguous'' flag set to true.
10699 \warning You should not normally need to use this function;
10700 instead create \l{QAction}s with the shortcut key sequences you
10701 require (if you also want equivalent menu options and toolbar
10702 buttons), or create \l{QShortcut}s if you just need key sequences.
10703 Both QAction and QShortcut handle all the event filtering for you,
10704 and provide signals which are triggered when the user triggers the
10705 key sequence, so are much easier to use than this low-level
10708 \sa releaseShortcut() setShortcutEnabled()
10710 int QWidget::grabShortcut(const QKeySequence &key, Qt::ShortcutContext context)
10715 setAttribute(Qt::WA_GrabbedShortcut);
10716 return qApp->d_func()->shortcutMap.addShortcut(this, key, context, qWidgetShortcutContextMatcher);
10720 Removes the shortcut with the given \a id from Qt's shortcut
10721 system. The widget will no longer receive QEvent::Shortcut events
10722 for the shortcut's key sequence (unless it has other shortcuts
10723 with the same key sequence).
10725 \warning You should not normally need to use this function since
10726 Qt's shortcut system removes shortcuts automatically when their
10727 parent widget is destroyed. It is best to use QAction or
10728 QShortcut to handle shortcuts, since they are easier to use than
10729 this low-level function. Note also that this is an expensive
10732 \sa grabShortcut() setShortcutEnabled()
10734 void QWidget::releaseShortcut(int id)
10738 qApp->d_func()->shortcutMap.removeShortcut(id, this, 0);
10742 If \a enable is true, the shortcut with the given \a id is
10743 enabled; otherwise the shortcut is disabled.
10745 \warning You should not normally need to use this function since
10746 Qt's shortcut system enables/disables shortcuts automatically as
10747 widgets become hidden/visible and gain or lose focus. It is best
10748 to use QAction or QShortcut to handle shortcuts, since they are
10749 easier to use than this low-level function.
10751 \sa grabShortcut() releaseShortcut()
10753 void QWidget::setShortcutEnabled(int id, bool enable)
10757 qApp->d_func()->shortcutMap.setShortcutEnabled(enable, id, this, 0);
10763 If \a enable is true, auto repeat of the shortcut with the
10764 given \a id is enabled; otherwise it is disabled.
10766 \sa grabShortcut() releaseShortcut()
10768 void QWidget::setShortcutAutoRepeat(int id, bool enable)
10772 qApp->d_func()->shortcutMap.setShortcutAutoRepeat(enable, id, this, 0);
10774 #endif // QT_NO_SHORTCUT
10777 Updates the widget's micro focus.
10781 void QWidget::updateMicroFocus()
10783 // updating everything since this is currently called for any kind of state change
10784 qApp->inputPanel()->update(Qt::ImQueryAll);
10786 #ifndef QT_NO_ACCESSIBILITY
10788 // ##### is this correct
10789 QAccessible::updateAccessibility(this, 0, QAccessible::StateChanged);
10795 #if defined (Q_WS_WIN)
10797 Returns the window system handle of the widget, for low-level
10798 access. Using this function is not portable.
10800 An HDC acquired with getDC() has to be released with releaseDC().
10802 \warning Using this function is not portable.
10804 HDC QWidget::getDC() const
10806 Q_D(const QWidget);
10808 return (HDC) d->hd;
10809 return GetDC(winId());
10813 Releases the HDC \a hdc acquired by a previous call to getDC().
10815 \warning Using this function is not portable.
10817 void QWidget::releaseDC(HDC hdc) const
10819 Q_D(const QWidget);
10820 // If its the widgets own dc, it will be released elsewhere. If
10821 // its a different HDC we release it and issue a warning if it
10823 if (hdc != d->hd && !ReleaseDC(winId(), hdc))
10824 qErrnoWarning("QWidget::releaseDC(): failed to release HDC");
10828 Returns the window system handle of the widget, for low-level
10829 access. Using this function is not portable.
10831 The HANDLE type varies with platform; see \c qwindowdefs.h for
10834 Qt::HANDLE QWidget::handle() const
10836 Q_D(const QWidget);
10837 if (!internalWinId() && testAttribute(Qt::WA_WState_Created))
10838 (void)winId(); // enforce native window
10845 Raises this widget to the top of the parent widget's stack.
10847 After this call the widget will be visually in front of any
10848 overlapping sibling widgets.
10850 \note When using activateWindow(), you can call this function to
10851 ensure that the window is stacked on top.
10853 \sa lower(), stackUnder()
10856 void QWidget::raise()
10860 QWidget *p = parentWidget();
10861 const int parentChildCount = p->d_func()->children.size();
10862 if (parentChildCount < 2)
10864 const int from = p->d_func()->children.indexOf(this);
10865 Q_ASSERT(from >= 0);
10866 // Do nothing if the widget is already in correct stacking order _and_ created.
10867 if (from != parentChildCount -1)
10868 p->d_func()->children.move(from, parentChildCount - 1);
10869 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10871 else if (from == parentChildCount - 1)
10874 QRegion region(rect());
10875 d->subtractOpaqueSiblings(region);
10876 d->invalidateBuffer(region);
10878 if (testAttribute(Qt::WA_WState_Created))
10881 QEvent e(QEvent::ZOrderChange);
10882 QApplication::sendEvent(this, &e);
10886 Lowers the widget to the bottom of the parent widget's stack.
10888 After this call the widget will be visually behind (and therefore
10889 obscured by) any overlapping sibling widgets.
10891 \sa raise(), stackUnder()
10894 void QWidget::lower()
10898 QWidget *p = parentWidget();
10899 const int parentChildCount = p->d_func()->children.size();
10900 if (parentChildCount < 2)
10902 const int from = p->d_func()->children.indexOf(this);
10903 Q_ASSERT(from >= 0);
10904 // Do nothing if the widget is already in correct stacking order _and_ created.
10906 p->d_func()->children.move(from, 0);
10907 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10909 else if (from == 0)
10912 if (testAttribute(Qt::WA_WState_Created))
10915 QEvent e(QEvent::ZOrderChange);
10916 QApplication::sendEvent(this, &e);
10921 Places the widget under \a w in the parent widget's stack.
10923 To make this work, the widget itself and \a w must be siblings.
10925 \sa raise(), lower()
10927 void QWidget::stackUnder(QWidget* w)
10930 QWidget *p = parentWidget();
10931 if (!w || isWindow() || p != w->parentWidget() || this == w)
10934 int from = p->d_func()->children.indexOf(this);
10935 int to = p->d_func()->children.indexOf(w);
10936 Q_ASSERT(from >= 0);
10940 // Do nothing if the widget is already in correct stacking order _and_ created.
10942 p->d_func()->children.move(from, to);
10943 if (!testAttribute(Qt::WA_WState_Created) && p->testAttribute(Qt::WA_WState_Created))
10945 else if (from == to)
10948 if (testAttribute(Qt::WA_WState_Created))
10949 d->stackUnder_sys(w);
10951 QEvent e(QEvent::ZOrderChange);
10952 QApplication::sendEvent(this, &e);
10956 \enum QWidget::BackgroundOrigin
10960 \value WidgetOrigin
10961 \value ParentOrigin
10962 \value WindowOrigin
10963 \value AncestorOrigin
10968 \fn bool QWidget::isVisibleToTLW() const
10970 Use isVisible() instead.
10974 \fn void QWidget::iconify()
10976 Use showMinimized() instead.
10980 \fn void QWidget::constPolish() const
10982 Use ensurePolished() instead.
10986 \fn void QWidget::reparent(QWidget *parent, Qt::WindowFlags f, const QPoint &p, bool showIt)
10988 Use setParent() to change the parent or the widget's widget flags;
10989 use move() to move the widget, and use show() to show the widget.
10993 \fn void QWidget::reparent(QWidget *parent, const QPoint &p, bool showIt)
10995 Use setParent() to change the parent; use move() to move the
10996 widget, and use show() to show the widget.
11000 \fn void QWidget::recreate(QWidget *parent, Qt::WindowFlags f, const QPoint & p, bool showIt)
11002 Use setParent() to change the parent or the widget's widget flags;
11003 use move() to move the widget, and use show() to show the widget.
11007 \fn bool QWidget::hasMouse() const
11009 Use testAttribute(Qt::WA_UnderMouse) instead.
11013 \fn bool QWidget::ownCursor() const
11015 Use testAttribute(Qt::WA_SetCursor) instead.
11019 \fn bool QWidget::ownFont() const
11021 Use testAttribute(Qt::WA_SetFont) instead.
11025 \fn void QWidget::unsetFont()
11027 Use setFont(QFont()) instead.
11031 \fn bool QWidget::ownPalette() const
11033 Use testAttribute(Qt::WA_SetPalette) instead.
11037 \fn void QWidget::unsetPalette()
11039 Use setPalette(QPalette()) instead.
11043 \fn void QWidget::setEraseColor(const QColor &color)
11045 Use the palette instead.
11048 widget->setEraseColor(color);
11051 palette.setColor(widget->backgroundRole(), color);
11052 widget->setPalette(palette);
11057 \fn void QWidget::setErasePixmap(const QPixmap &pixmap)
11059 Use the palette instead.
11062 widget->setErasePixmap(pixmap);
11065 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11066 widget->setPalette(palette);
11071 \fn void QWidget::setPaletteForegroundColor(const QColor &color)
11073 Use the palette directly.
11076 widget->setPaletteForegroundColor(color);
11079 palette.setColor(widget->foregroundRole(), color);
11080 widget->setPalette(palette);
11085 \fn void QWidget::setPaletteBackgroundColor(const QColor &color)
11087 Use the palette directly.
11090 widget->setPaletteBackgroundColor(color);
11093 palette.setColor(widget->backgroundRole(), color);
11094 widget->setPalette(palette);
11099 \fn void QWidget::setPaletteBackgroundPixmap(const QPixmap &pixmap)
11101 Use the palette directly.
11104 widget->setPaletteBackgroundPixmap(pixmap);
11107 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11108 widget->setPalette(palette);
11113 \fn void QWidget::setBackgroundPixmap(const QPixmap &pixmap)
11115 Use the palette instead.
11118 widget->setBackgroundPixmap(pixmap);
11121 palette.setBrush(widget->backgroundRole(), QBrush(pixmap));
11122 widget->setPalette(palette);
11127 \fn void QWidget::setBackgroundColor(const QColor &color)
11129 Use the palette instead.
11132 widget->setBackgroundColor(color);
11135 palette.setColor(widget->backgroundRole(), color);
11136 widget->setPalette(palette);
11142 \fn QWidget *QWidget::parentWidget(bool sameWindow) const
11144 Use the no-argument overload instead.
11148 \fn void QWidget::setKeyCompression(bool b)
11150 Use setAttribute(Qt::WA_KeyCompression, b) instead.
11154 \fn void QWidget::setFont(const QFont &f, bool b)
11156 Use the single-argument overload instead.
11160 \fn void QWidget::setPalette(const QPalette &p, bool b)
11162 Use the single-argument overload instead.
11166 \fn void QWidget::setBackgroundOrigin(BackgroundOrigin background)
11172 \fn BackgroundOrigin QWidget::backgroundOrigin() const
11176 Always returns \c WindowOrigin.
11180 \fn QPoint QWidget::backgroundOffset() const
11184 Always returns QPoint().
11188 \fn void QWidget::repaint(bool b)
11190 The boolean parameter \a b is ignored. Use the no-argument overload instead.
11194 \fn void QWidget::repaint(int x, int y, int w, int h, bool b)
11196 The boolean parameter \a b is ignored. Use the four-argument overload instead.
11200 \fn void QWidget::repaint(const QRect &r, bool b)
11202 The boolean parameter \a b is ignored. Use the single rect-argument overload instead.
11206 \fn void QWidget::repaint(const QRegion &rgn, bool b)
11208 The boolean parameter \a b is ignored. Use the single region-argument overload instead.
11212 \fn void QWidget::erase()
11214 Drawing may only take place in a QPaintEvent. Overload
11215 paintEvent() to do your erasing and call update() to schedule a
11216 replaint whenever necessary. See also QPainter.
11220 \fn void QWidget::erase(int x, int y, int w, int h)
11222 Drawing may only take place in a QPaintEvent. Overload
11223 paintEvent() to do your erasing and call update() to schedule a
11224 replaint whenever necessary. See also QPainter.
11228 \fn void QWidget::erase(const QRect &rect)
11230 Drawing may only take place in a QPaintEvent. Overload
11231 paintEvent() to do your erasing and call update() to schedule a
11232 replaint whenever necessary. See also QPainter.
11236 \fn void QWidget::drawText(const QPoint &p, const QString &s)
11238 Drawing may only take place in a QPaintEvent. Overload
11239 paintEvent() to do your drawing and call update() to schedule a
11240 replaint whenever necessary. See also QPainter.
11244 \fn void QWidget::drawText(int x, int y, const QString &s)
11246 Drawing may only take place in a QPaintEvent. Overload
11247 paintEvent() to do your drawing and call update() to schedule a
11248 replaint whenever necessary. See also QPainter.
11252 \fn QWidget *QWidget::childAt(const QPoint &p, bool includeThis) const
11254 Use the single point argument overload instead.
11258 \fn void QWidget::setCaption(const QString &c)
11260 Use setWindowTitle() instead.
11264 \fn void QWidget::setIcon(const QPixmap &i)
11266 Use setWindowIcon() instead.
11270 \fn void QWidget::setIconText(const QString &it)
11272 Use setWindowIconText() instead.
11276 \fn QString QWidget::caption() const
11278 Use windowTitle() instead.
11282 \fn QString QWidget::iconText() const
11284 Use windowIconText() instead.
11288 \fn bool QWidget::isTopLevel() const
11291 Use isWindow() instead.
11295 \fn bool QWidget::isRightToLeft() const
11300 \fn bool QWidget::isLeftToRight() const
11305 \fn void QWidget::setInputMethodEnabled(bool enabled)
11307 Use setAttribute(Qt::WA_InputMethodEnabled, \a enabled) instead.
11311 \fn bool QWidget::isInputMethodEnabled() const
11313 Use testAttribute(Qt::WA_InputMethodEnabled) instead.
11317 \fn void QWidget::setActiveWindow()
11319 Use activateWindow() instead.
11323 \fn bool QWidget::isShown() const
11325 Use !isHidden() instead (notice the exclamation mark), or use isVisible() to check whether the widget is visible.
11329 \fn bool QWidget::isDialog() const
11331 Use windowType() == Qt::Dialog instead.
11335 \fn bool QWidget::isPopup() const
11337 Use windowType() == Qt::Popup instead.
11341 \fn bool QWidget::isDesktop() const
11343 Use windowType() == Qt::Desktop instead.
11347 \fn void QWidget::polish()
11349 Use ensurePolished() instead.
11353 \fn QWidget *QWidget::childAt(int x, int y, bool includeThis) const
11355 Use the childAt() overload that doesn't have an \a includeThis parameter.
11358 return widget->childAt(x, y, true);
11360 QWidget *child = widget->childAt(x, y, true);
11363 if (widget->rect().contains(x, y))
11369 \fn void QWidget::setSizePolicy(QSizePolicy::Policy hor, QSizePolicy::Policy ver, bool hfw)
11372 Use the \l sizePolicy property and heightForWidth() function instead.
11376 \fn bool QWidget::isUpdatesEnabled() const
11379 Use the \l updatesEnabled property instead.
11383 \macro QWIDGETSIZE_MAX
11386 Defines the maximum size for a QWidget object.
11388 The largest allowed size for a widget is QSize(QWIDGETSIZE_MAX,
11389 QWIDGETSIZE_MAX), i.e. QSize (16777215,16777215).
11391 \sa QWidget::setMaximumSize()
11395 \fn QWidget::setupUi(QWidget *widget)
11397 Sets up the user interface for the specified \a widget.
11399 \note This function is available with widgets that derive from user
11400 interface descriptions created using \l{uic}.
11402 \sa {Using a Designer UI File in Your Application}
11405 QRect QWidgetPrivate::frameStrut() const
11407 Q_Q(const QWidget);
11408 if (!q->isWindow() || (q->windowType() == Qt::Desktop) || q->testAttribute(Qt::WA_DontShowOnScreen)) {
11409 // x2 = x1 + w - 1, so w/h = 1
11410 return QRect(0, 0, 1, 1);
11413 if (data.fstrut_dirty
11415 // ### Fix properly for 4.3
11418 && q->testAttribute(Qt::WA_WState_Created))
11419 const_cast<QWidgetPrivate *>(this)->updateFrameStrut();
11421 return maybeTopData() ? maybeTopData()->frameStrut : QRect();
11424 #ifdef QT_KEYPAD_NAVIGATION
11428 Changes the focus from the current focusWidget to a widget in
11431 Returns true, if there was a widget in that direction
11433 bool QWidgetPrivate::navigateToDirection(Direction direction)
11435 QWidget *targetWidget = widgetInNavigationDirection(direction);
11437 targetWidget->setFocus();
11438 return (targetWidget != 0);
11444 Searches for a widget that is positioned in the \a direction, starting
11445 from the current focusWidget.
11447 Returns the pointer to a found widget or 0, if there was no widget in
11450 QWidget *QWidgetPrivate::widgetInNavigationDirection(Direction direction)
11452 const QWidget *sourceWidget = QApplication::focusWidget();
11455 const QRect sourceRect = sourceWidget->rect().translated(sourceWidget->mapToGlobal(QPoint()));
11456 const int sourceX =
11457 (direction == DirectionNorth || direction == DirectionSouth) ?
11458 (sourceRect.left() + (sourceRect.right() - sourceRect.left()) / 2)
11459 :(direction == DirectionEast ? sourceRect.right() : sourceRect.left());
11460 const int sourceY =
11461 (direction == DirectionEast || direction == DirectionWest) ?
11462 (sourceRect.top() + (sourceRect.bottom() - sourceRect.top()) / 2)
11463 :(direction == DirectionSouth ? sourceRect.bottom() : sourceRect.top());
11464 const QPoint sourcePoint(sourceX, sourceY);
11465 const QPoint sourceCenter = sourceRect.center();
11466 const QWidget *sourceWindow = sourceWidget->window();
11468 QWidget *targetWidget = 0;
11469 int shortestDistance = INT_MAX;
11470 foreach(QWidget *targetCandidate, QApplication::allWidgets()) {
11472 const QRect targetCandidateRect = targetCandidate->rect().translated(targetCandidate->mapToGlobal(QPoint()));
11474 // For focus proxies, the child widget handling the focus can have keypad navigation focus,
11475 // but the owner of the proxy cannot.
11476 // Additionally, empty widgets should be ignored.
11477 if (targetCandidate->focusProxy() || targetCandidateRect.isEmpty())
11480 // Only navigate to a target widget that...
11481 if ( targetCandidate != sourceWidget
11482 // ...takes the focus,
11483 && targetCandidate->focusPolicy() & Qt::TabFocus
11484 // ...is above if DirectionNorth,
11485 && !(direction == DirectionNorth && targetCandidateRect.bottom() > sourceRect.top())
11486 // ...is on the right if DirectionEast,
11487 && !(direction == DirectionEast && targetCandidateRect.left() < sourceRect.right())
11488 // ...is below if DirectionSouth,
11489 && !(direction == DirectionSouth && targetCandidateRect.top() < sourceRect.bottom())
11490 // ...is on the left if DirectionWest,
11491 && !(direction == DirectionWest && targetCandidateRect.right() > sourceRect.left())
11493 && targetCandidate->isEnabled()
11495 && targetCandidate->isVisible()
11496 // ...is in the same window,
11497 && targetCandidate->window() == sourceWindow) {
11498 const int targetCandidateDistance = pointToRect(sourcePoint, targetCandidateRect);
11499 if (targetCandidateDistance < shortestDistance) {
11500 shortestDistance = targetCandidateDistance;
11501 targetWidget = targetCandidate;
11505 return targetWidget;
11511 Tells us if it there is currently a reachable widget by keypad navigation in
11512 a certain \a orientation.
11513 If no navigation is possible, occurring key events in that \a orientation may
11514 be used to interact with the value in the focused widget, even though it
11515 currently has not the editFocus.
11517 \sa QWidgetPrivate::widgetInNavigationDirection(), QWidget::hasEditFocus()
11519 bool QWidgetPrivate::canKeypadNavigate(Qt::Orientation orientation)
11521 return orientation == Qt::Horizontal?
11522 (QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionEast)
11523 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionWest))
11524 :(QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionNorth)
11525 || QWidgetPrivate::widgetInNavigationDirection(QWidgetPrivate::DirectionSouth));
11530 Checks, if the \a widget is inside a QTabWidget. If is is inside
11531 one, left/right key events will be used to switch between tabs in keypad
11532 navigation. If there is no QTabWidget, the horizontal key events can be used
11534 interact with the value in the focused widget, even though it currently has
11537 \sa QWidget::hasEditFocus()
11539 bool QWidgetPrivate::inTabWidget(QWidget *widget)
11541 for (QWidget *tabWidget = widget; tabWidget; tabWidget = tabWidget->parentWidget())
11542 if (qobject_cast<const QTabWidget*>(tabWidget))
11552 Sets the backing store to be the \a store specified.
11553 The QWidget will take ownership of the \a store.
11555 void QWidget::setBackingStore(QBackingStore *store)
11557 // ### createWinId() ??
11564 QTLWExtra *topData = d->topData();
11565 if (topData->backingStore == store)
11568 QBackingStore *oldStore = topData->backingStore;
11569 delete topData->backingStore;
11570 topData->backingStore = store;
11572 QWidgetBackingStore *bs = d->maybeBackingStore();
11576 if (isTopLevel()) {
11577 if (bs->store != oldStore && bs->store != store)
11586 Returns the QBackingStore this widget will be drawn into.
11588 QBackingStore *QWidget::backingStore() const
11590 Q_D(const QWidget);
11591 QTLWExtra *extra = d->maybeTopData();
11592 if (extra && extra->backingStore)
11593 return extra->backingStore;
11595 QWidgetBackingStore *bs = d->maybeBackingStore();
11597 return bs ? bs->store : 0;
11600 void QWidgetPrivate::getLayoutItemMargins(int *left, int *top, int *right, int *bottom) const
11603 *left = (int)leftLayoutItemMargin;
11605 *top = (int)topLayoutItemMargin;
11607 *right = (int)rightLayoutItemMargin;
11609 *bottom = (int)bottomLayoutItemMargin;
11612 void QWidgetPrivate::setLayoutItemMargins(int left, int top, int right, int bottom)
11614 if (leftLayoutItemMargin == left
11615 && topLayoutItemMargin == top
11616 && rightLayoutItemMargin == right
11617 && bottomLayoutItemMargin == bottom)
11621 leftLayoutItemMargin = (signed char)left;
11622 topLayoutItemMargin = (signed char)top;
11623 rightLayoutItemMargin = (signed char)right;
11624 bottomLayoutItemMargin = (signed char)bottom;
11625 q->updateGeometry();
11628 void QWidgetPrivate::setLayoutItemMargins(QStyle::SubElement element, const QStyleOption *opt)
11631 QStyleOption myOpt;
11634 myOpt.rect.setRect(0, 0, 32768, 32768); // arbitrary
11638 QRect liRect = q->style()->subElementRect(element, opt, q);
11639 if (liRect.isValid()) {
11640 leftLayoutItemMargin = (signed char)(opt->rect.left() - liRect.left());
11641 topLayoutItemMargin = (signed char)(opt->rect.top() - liRect.top());
11642 rightLayoutItemMargin = (signed char)(liRect.right() - opt->rect.right());
11643 bottomLayoutItemMargin = (signed char)(liRect.bottom() - opt->rect.bottom());
11645 leftLayoutItemMargin = 0;
11646 topLayoutItemMargin = 0;
11647 rightLayoutItemMargin = 0;
11648 bottomLayoutItemMargin = 0;
11651 // resets the Qt::WA_QuitOnClose attribute to the default value for transient widgets.
11652 void QWidgetPrivate::adjustQuitOnCloseAttribute()
11656 if (!q->parentWidget()) {
11657 Qt::WindowType type = q->windowType();
11658 if (type == Qt::Widget || type == Qt::SubWindow)
11660 if (type != Qt::Widget && type != Qt::Window && type != Qt::Dialog)
11661 q->setAttribute(Qt::WA_QuitOnClose, false);
11667 Q_WIDGETS_EXPORT QWidgetData *qt_qwidget_data(QWidget *widget)
11669 return widget->data;
11672 Q_WIDGETS_EXPORT QWidgetPrivate *qt_widget_private(QWidget *widget)
11674 return widget->d_func();
11678 #ifndef QT_NO_GRAPHICSVIEW
11682 Returns the proxy widget for the corresponding embedded widget in a graphics
11683 view; otherwise returns 0.
11685 \sa QGraphicsProxyWidget::createProxyForChildWidget(),
11686 QGraphicsScene::addWidget()
11688 QGraphicsProxyWidget *QWidget::graphicsProxyWidget() const
11690 Q_D(const QWidget);
11692 return d->extra->proxyWidget;
11700 \typedef QWidgetList
11703 Synonym for QList<QWidget *>.
11706 #ifndef QT_NO_GESTURES
11708 Subscribes the widget to a given \a gesture with specific \a flags.
11710 \sa ungrabGesture(), QGestureEvent
11713 void QWidget::grabGesture(Qt::GestureType gesture, Qt::GestureFlags flags)
11716 d->gestureContext.insert(gesture, flags);
11717 (void)QGestureManager::instance(); // create a gesture manager
11721 Unsubscribes the widget from a given \a gesture type
11723 \sa grabGesture(), QGestureEvent
11726 void QWidget::ungrabGesture(Qt::GestureType gesture)
11729 if (d->gestureContext.remove(gesture)) {
11730 if (QGestureManager *manager = QGestureManager::instance())
11731 manager->cleanupCachedGestures(this, gesture);
11734 #endif // QT_NO_GESTURES
11740 Platform dependent window identifier.
11744 \fn void QWidget::destroy(bool destroyWindow, bool destroySubWindows)
11746 Frees up window system resources. Destroys the widget window if \a
11747 destroyWindow is true.
11749 destroy() calls itself recursively for all the child widgets,
11750 passing \a destroySubWindows for the \a destroyWindow parameter.
11751 To have more control over destruction of subwidgets, destroy
11752 subwidgets selectively first.
11754 This function is usually called from the QWidget destructor.
11758 \fn QPaintEngine *QWidget::paintEngine() const
11760 Returns the widget's paint engine.
11762 Note that this function should not be called explicitly by the
11763 user, since it's meant for reimplementation purposes only. The
11764 function is called by Qt internally, and the default
11765 implementation may not always return a valid pointer.
11769 \fn QPoint QWidget::mapToGlobal(const QPoint &pos) const
11771 Translates the widget coordinate \a pos to global screen
11772 coordinates. For example, \c{mapToGlobal(QPoint(0,0))} would give
11773 the global coordinates of the top-left pixel of the widget.
11775 \sa mapFromGlobal() mapTo() mapToParent()
11779 \fn QPoint QWidget::mapFromGlobal(const QPoint &pos) const
11781 Translates the global screen coordinate \a pos to widget
11784 \sa mapToGlobal() mapFrom() mapFromParent()
11788 \fn void QWidget::grabMouse()
11790 Grabs the mouse input.
11792 This widget receives all mouse events until releaseMouse() is
11793 called; other widgets get no mouse events at all. Keyboard
11794 events are not affected. Use grabKeyboard() if you want to grab
11797 \warning Bugs in mouse-grabbing applications very often lock the
11798 terminal. Use this function with extreme caution, and consider
11799 using the \c -nograb command line option while debugging.
11801 It is almost never necessary to grab the mouse when using Qt, as
11802 Qt grabs and releases it sensibly. In particular, Qt grabs the
11803 mouse when a mouse button is pressed and keeps it until the last
11804 button is released.
11806 \note Only visible widgets can grab mouse input. If isVisible()
11807 returns false for a widget, that widget cannot call grabMouse().
11809 \note \bold{(Mac OS X developers)} For \e Cocoa, calling
11810 grabMouse() on a widget only works when the mouse is inside the
11811 frame of that widget. For \e Carbon, it works outside the widget's
11812 frame as well, like for Windows and X11.
11814 \sa releaseMouse() grabKeyboard() releaseKeyboard()
11818 \fn void QWidget::grabMouse(const QCursor &cursor)
11819 \overload grabMouse()
11821 Grabs the mouse input and changes the cursor shape.
11823 The cursor will assume shape \a cursor (for as long as the mouse
11824 focus is grabbed) and this widget will be the only one to receive
11825 mouse events until releaseMouse() is called().
11827 \warning Grabbing the mouse might lock the terminal.
11829 \note \bold{(Mac OS X developers)} See the note in QWidget::grabMouse().
11831 \sa releaseMouse(), grabKeyboard(), releaseKeyboard(), setCursor()
11835 \fn void QWidget::releaseMouse()
11837 Releases the mouse grab.
11839 \sa grabMouse(), grabKeyboard(), releaseKeyboard()
11843 \fn void QWidget::grabKeyboard()
11845 Grabs the keyboard input.
11847 This widget receives all keyboard events until releaseKeyboard()
11848 is called; other widgets get no keyboard events at all. Mouse
11849 events are not affected. Use grabMouse() if you want to grab that.
11851 The focus widget is not affected, except that it doesn't receive
11852 any keyboard events. setFocus() moves the focus as usual, but the
11853 new focus widget receives keyboard events only after
11854 releaseKeyboard() is called.
11856 If a different widget is currently grabbing keyboard input, that
11857 widget's grab is released first.
11859 \sa releaseKeyboard() grabMouse() releaseMouse() focusWidget()
11863 \fn void QWidget::releaseKeyboard()
11865 Releases the keyboard grab.
11867 \sa grabKeyboard(), grabMouse(), releaseMouse()
11871 \fn QWidget *QWidget::mouseGrabber()
11873 Returns the widget that is currently grabbing the mouse input.
11875 If no widget in this application is currently grabbing the mouse,
11878 \sa grabMouse(), keyboardGrabber()
11882 \fn QWidget *QWidget::keyboardGrabber()
11884 Returns the widget that is currently grabbing the keyboard input.
11886 If no widget in this application is currently grabbing the
11887 keyboard, 0 is returned.
11889 \sa grabMouse(), mouseGrabber()
11893 \fn void QWidget::activateWindow()
11895 Sets the top-level widget containing this widget to be the active
11898 An active window is a visible top-level window that has the
11899 keyboard input focus.
11901 This function performs the same operation as clicking the mouse on
11902 the title bar of a top-level window. On X11, the result depends on
11903 the Window Manager. If you want to ensure that the window is
11904 stacked on top as well you should also call raise(). Note that the
11905 window must be visible, otherwise activateWindow() has no effect.
11907 On Windows, if you are calling this when the application is not
11908 currently the active one then it will not make it the active
11909 window. It will change the color of the taskbar entry to indicate
11910 that the window has changed in some way. This is because Microsoft
11911 does not allow an application to interrupt what the user is currently
11912 doing in another application.
11914 \sa isActiveWindow(), window(), show()
11918 \fn int QWidget::metric(PaintDeviceMetric m) const
11920 Internal implementation of the virtual QPaintDevice::metric()
11923 \a m is the metric to get.
11926 void QWidget::init(QPainter *painter) const
11928 const QPalette &pal = palette();
11929 painter->d_func()->state->pen = QPen(pal.brush(foregroundRole()), 0);
11930 painter->d_func()->state->bgBrush = pal.brush(backgroundRole());
11931 QFont f(font(), const_cast<QWidget *>(this));
11932 painter->d_func()->state->deviceFont = f;
11933 painter->d_func()->state->font = f;
11936 QPaintDevice *QWidget::redirected(QPoint *offset) const
11938 return d_func()->redirected(offset);
11941 QPainter *QWidget::sharedPainter() const
11943 // Someone sent a paint event directly to the widget
11944 if (!d_func()->redirectDev)
11947 QPainter *sp = d_func()->sharedPainter();
11948 if (!sp || !sp->isActive())
11951 if (sp->paintEngine()->paintDevice() != d_func()->redirectDev)
11958 \fn void QWidget::setMask(const QRegion ®ion)
11961 Causes only the parts of the widget which overlap \a region to be
11962 visible. If the region includes pixels outside the rect() of the
11963 widget, window system controls in that area may or may not be
11964 visible, depending on the platform.
11966 Note that this effect can be slow if the region is particularly
11971 void QWidget::setMask(const QRegion &newMask)
11976 if (newMask == d->extra->mask)
11979 #ifndef QT_NO_BACKINGSTORE
11980 const QRegion oldMask(d->extra->mask);
11983 d->extra->mask = newMask;
11984 d->extra->hasMask = !newMask.isEmpty();
11987 if (!testAttribute(Qt::WA_WState_Created))
11991 d->setMask_sys(newMask);
11993 #ifndef QT_NO_BACKINGSTORE
11997 if (!d->extra->hasMask) {
11998 // Mask was cleared; update newly exposed area.
11999 QRegion expose(rect());
12001 if (!expose.isEmpty()) {
12002 d->setDirtyOpaqueRegion();
12009 // Update newly exposed area on the parent widget.
12010 QRegion parentExpose(rect());
12011 parentExpose -= newMask;
12012 if (!parentExpose.isEmpty()) {
12013 d->setDirtyOpaqueRegion();
12014 parentExpose.translate(data->crect.topLeft());
12015 parentWidget()->update(parentExpose);
12018 // Update newly exposed area on this widget
12019 if (!oldMask.isEmpty())
12020 update(newMask - oldMask);
12026 \fn void QWidget::setMask(const QBitmap &bitmap)
12028 Causes only the pixels of the widget for which \a bitmap has a
12029 corresponding 1 bit to be visible. If the region includes pixels
12030 outside the rect() of the widget, window system controls in that
12031 area may or may not be visible, depending on the platform.
12033 Note that this effect can be slow if the region is particularly
12036 The following code shows how an image with an alpha channel can be
12037 used to generate a mask for a widget:
12039 \snippet doc/src/snippets/widget-mask/main.cpp 0
12041 The label shown by this code is masked using the image it contains,
12042 giving the appearance that an irregularly-shaped image is being drawn
12043 directly onto the screen.
12045 Masked widgets receive mouse events only on their visible
12048 \sa clearMask(), windowOpacity(), {Shaped Clock Example}
12050 void QWidget::setMask(const QBitmap &bitmap)
12052 setMask(QRegion(bitmap));
12056 \fn void QWidget::clearMask()
12058 Removes any mask set by setMask().
12062 void QWidget::clearMask()
12064 setMask(QRegion());
12067 /*! \fn const QX11Info &QWidget::x11Info() const
12068 Returns information about the configuration of the X display used to display
12071 \warning This function is only available on X11.
12074 /*! \fn Qt::HANDLE QWidget::x11PictureHandle() const
12075 Returns the X11 Picture handle of the widget for XRender
12076 support. Use of this function is not portable. This function will
12077 return 0 if XRender support is not compiled into Qt, if the
12078 XRender extension is not supported on the X11 display, or if the
12079 handle could not be created.
12082 #ifdef Q_OS_SYMBIAN
12083 void QWidgetPrivate::_q_delayedDestroy(WId winId)
12090 void QWidgetPrivate::syncUnifiedMode() {
12091 // The whole purpose of this method is to keep the unifiedToolbar in sync.
12092 // That means making sure we either exchange the drawing methods or we let
12093 // the toolbar know that it does not require to draw the baseline.
12095 // This function makes sense only if this is a top level
12098 OSWindowRef window = qt_mac_window_for(q);
12099 if(changeMethods) {
12100 // Ok, we are in documentMode.
12101 if(originalDrawMethod)
12102 qt_mac_replaceDrawRect(window, this);
12104 if(!originalDrawMethod)
12105 qt_mac_replaceDrawRectOriginal(window, this);
12113 #include "moc_qwidget.cpp"