-
Notifications
You must be signed in to change notification settings - Fork 1k
/
qwidget.cpp
12679 lines (10470 loc) · 388 KB
/
qwidget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qapplication.h"
#include "qapplication_p.h"
#include "qbrush.h"
#include "qcursor.h"
#include "qdesktopwidget.h"
#include "qevent.h"
#include "qhash.h"
#include "qlayout.h"
#include "qmenu.h"
#include "qmetaobject.h"
#include "qpixmap.h"
#include "qpointer.h"
#include "qstack.h"
#include "qstyle.h"
#include "qstylefactory.h"
#include "qvariant.h"
#include "qwidget.h"
#include "qstyleoption.h"
#ifndef QT_NO_ACCESSIBILITY
# include "qaccessible.h"
#endif
#if defined(Q_WS_WIN)
# include "qt_windows.h"
#endif
#ifdef Q_WS_MAC
# include "qt_mac_p.h"
# include "qt_cocoa_helpers_mac_p.h"
# include "qmainwindow.h"
# include "qtoolbar.h"
# include <private/qmainwindowlayout_p.h>
#endif
#if defined(Q_WS_QWS)
# include "qwsdisplay_qws.h"
# include "qwsmanager_qws.h"
# include "qpaintengine.h" // for PorterDuff
# include "private/qwindowsurface_qws_p.h"
#endif
#if defined(Q_WS_QPA)
#include "qplatformwindow_qpa.h"
#endif
#include "qpainter.h"
#include "qtooltip.h"
#include "qwhatsthis.h"
#include "qdebug.h"
#include "private/qstylesheetstyle_p.h"
#include "private/qstyle_p.h"
#include "private/qinputcontext_p.h"
#include "qfileinfo.h"
#include "private/qsoftkeymanager_p.h"
#if defined (Q_WS_WIN)
# include <private/qwininputcontext_p.h>
#endif
#if defined(Q_WS_X11)
# include <private/qpaintengine_x11_p.h>
# include "qx11info_x11.h"
#endif
#include <private/qgraphicseffect_p.h>
#include <private/qwindowsurface_p.h>
#include <private/qbackingstore_p.h>
#ifdef Q_WS_MAC
# include <private/qpaintengine_mac_p.h>
#endif
#include <private/qpaintengine_raster_p.h>
#if defined(Q_OS_SYMBIAN)
#include "private/qt_s60_p.h"
#endif
#include "qwidget_p.h"
#include "qaction_p.h"
#include "qlayout_p.h"
#include "QtGui/qgraphicsproxywidget.h"
#include "QtGui/qgraphicsscene.h"
#include "private/qgraphicsproxywidget_p.h"
#include "QtGui/qabstractscrollarea.h"
#include "private/qabstractscrollarea_p.h"
#include "private/qevent_p.h"
#include "private/qgraphicssystem_p.h"
#include "private/qgesturemanager_p.h"
#ifdef QT_KEYPAD_NAVIGATION
#include "qtabwidget.h" // Needed in inTabWidget()
#endif // QT_KEYPAD_NAVIGATION
#ifdef Q_WS_S60
#include <aknappui.h>
#endif
// widget/widget data creation count
//#define QWIDGET_EXTRA_DEBUG
//#define ALIEN_DEBUG
QT_BEGIN_NAMESPACE
#if !defined(Q_WS_QWS)
static bool qt_enable_backingstore = true;
#endif
#ifdef Q_WS_X11
// for compatibility with Qt 4.0
Q_GUI_EXPORT void qt_x11_set_global_double_buffer(bool enable)
{
qt_enable_backingstore = enable;
}
#endif
#if defined(QT_MAC_USE_COCOA)
bool qt_mac_clearDirtyOnWidgetInsideDrawWidget = false;
#endif
static inline bool qRectIntersects(const QRect &r1, const QRect &r2)
{
return (qMax(r1.left(), r2.left()) <= qMin(r1.right(), r2.right()) &&
qMax(r1.top(), r2.top()) <= qMin(r1.bottom(), r2.bottom()));
}
static inline bool hasBackingStoreSupport()
{
#ifdef Q_WS_MAC
return QApplicationPrivate::graphicsSystem() != 0;
#else
return true;
#endif
}
#ifdef Q_WS_MAC
# define QT_NO_PAINT_DEBUG
#endif
extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
extern QDesktopWidget *qt_desktopWidget; // qapplication.cpp
/*!
\internal
\class QWidgetBackingStoreTracker
\brief Class which allows tracking of which widgets are using a given backing store
QWidgetBackingStoreTracker is a thin wrapper around a QWidgetBackingStore pointer,
which maintains a list of the QWidgets which are currently using the backing
store. This list is modified via the registerWidget and unregisterWidget functions.
*/
QWidgetBackingStoreTracker::QWidgetBackingStoreTracker()
: m_ptr(0)
{
}
QWidgetBackingStoreTracker::~QWidgetBackingStoreTracker()
{
delete m_ptr;
}
/*!
\internal
Destroy the contained QWidgetBackingStore, if not null, and clear the list of
widgets using the backing store, then create a new QWidgetBackingStore, providing
the QWidget.
*/
void QWidgetBackingStoreTracker::create(QWidget *widget)
{
destroy();
m_ptr = new QWidgetBackingStore(widget);
}
/*!
\internal
Destroy the contained QWidgetBackingStore, if not null, and clear the list of
widgets using the backing store.
*/
void QWidgetBackingStoreTracker::destroy()
{
delete m_ptr;
m_ptr = 0;
m_widgets.clear();
}
/*!
\internal
Add the widget to the list of widgets currently using the backing store.
If the widget was already in the list, this function is a no-op.
*/
void QWidgetBackingStoreTracker::registerWidget(QWidget *w)
{
Q_ASSERT(m_ptr);
Q_ASSERT(w->internalWinId());
Q_ASSERT(qt_widget_private(w)->maybeBackingStore() == m_ptr);
m_widgets.insert(w);
}
/*!
\internal
Remove the widget from the list of widgets currently using the backing store.
If the widget was in the list, and removing it causes the list to be empty,
the backing store is deleted.
If the widget was not in the list, this function is a no-op.
*/
void QWidgetBackingStoreTracker::unregisterWidget(QWidget *w)
{
if (m_widgets.remove(w) && m_widgets.isEmpty()) {
delete m_ptr;
m_ptr = 0;
}
}
/*!
\internal
Recursively remove widget and all of its descendents.
*/
void QWidgetBackingStoreTracker::unregisterWidgetSubtree(QWidget *widget)
{
unregisterWidget(widget);
foreach (QObject *child, widget->children())
if (QWidget *childWidget = qobject_cast<QWidget *>(child))
unregisterWidgetSubtree(childWidget);
}
QWidgetPrivate::QWidgetPrivate(int version)
: QObjectPrivate(version)
, extra(0)
, focus_next(0)
, focus_prev(0)
, focus_child(0)
, layout(0)
, needsFlush(0)
, redirectDev(0)
, widgetItem(0)
, extraPaintEngine(0)
, polished(0)
, graphicsEffect(0)
#if !defined(QT_NO_IM)
, imHints(Qt::ImhNone)
#endif
, inheritedFontResolveMask(0)
, inheritedPaletteResolveMask(0)
, leftmargin(0)
, topmargin(0)
, rightmargin(0)
, bottommargin(0)
, leftLayoutItemMargin(0)
, topLayoutItemMargin(0)
, rightLayoutItemMargin(0)
, bottomLayoutItemMargin(0)
, hd(0)
, size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
, fg_role(QPalette::NoRole)
, bg_role(QPalette::NoRole)
, dirtyOpaqueChildren(1)
, isOpaque(0)
, inDirtyList(0)
, isScrolled(0)
, isMoved(0)
, isGLWidget(0)
, usesDoubleBufferedGLContext(0)
#ifndef QT_NO_IM
, inheritsInputMethodHints(0)
#endif
#if defined(Q_WS_X11)
, picture(0)
#elif defined(Q_WS_WIN)
, noPaintOnScreen(0)
#ifndef QT_NO_GESTURES
, nativeGesturePanEnabled(0)
#endif
#elif defined(Q_WS_MAC)
, needWindowChange(0)
, window_event(0)
, qd_hd(0)
#elif defined(Q_OS_SYMBIAN)
, symbianScreenNumber(0)
, fixNativeOrientationCalled(false)
#endif
{
if (!qApp) {
qFatal("QWidget: Must construct a QApplication before a QPaintDevice");
return;
}
if (version != QObjectPrivateVersion)
qFatal("Cannot mix incompatible Qt libraries");
isWidget = true;
memset(high_attributes, 0, sizeof(high_attributes));
#if QT_MAC_USE_COCOA
drawRectOriginalAdded = false;
originalDrawMethod = true;
changeMethods = false;
isInUnifiedToolbar = false;
unifiedSurface = 0;
toolbar_ancestor = 0;
flushRequested = false;
touchEventsEnabled = false;
#endif // QT_MAC_USE_COCOA
#ifdef QWIDGET_EXTRA_DEBUG
static int count = 0;
qDebug() << "widgets" << ++count;
#endif
}
QWidgetPrivate::~QWidgetPrivate()
{
if (widgetItem)
widgetItem->wid = 0;
if (extra)
deleteExtra();
#ifndef QT_NO_GRAPHICSEFFECT
delete graphicsEffect;
#endif //QT_NO_GRAPHICSEFFECT
}
class QDummyWindowSurface : public QWindowSurface
{
public:
QDummyWindowSurface(QWidget *window) : QWindowSurface(window) {}
QPaintDevice *paintDevice() { return window(); }
void flush(QWidget *, const QRegion &, const QPoint &) {}
};
QWindowSurface *QWidgetPrivate::createDefaultWindowSurface()
{
Q_Q(QWidget);
QWindowSurface *surface;
#ifndef QT_NO_PROPERTIES
if (q->property("_q_DummyWindowSurface").toBool()) {
surface = new QDummyWindowSurface(q);
} else
#endif
{
if (QApplicationPrivate::graphicsSystem())
surface = QApplicationPrivate::graphicsSystem()->createWindowSurface(q);
else
surface = createDefaultWindowSurface_sys();
}
return surface;
}
/*!
\internal
*/
void QWidgetPrivate::scrollChildren(int dx, int dy)
{
Q_Q(QWidget);
if (q->children().size() > 0) { // scroll children
QPoint pd(dx, dy);
QObjectList childObjects = q->children();
for (int i = 0; i < childObjects.size(); ++i) { // move all children
QWidget *w = qobject_cast<QWidget*>(childObjects.at(i));
if (w && !w->isWindow()) {
QPoint oldp = w->pos();
QRect r(w->pos() + pd, w->size());
w->data->crect = r;
#ifndef Q_WS_QWS
if (w->testAttribute(Qt::WA_WState_Created))
w->d_func()->setWSGeometry();
#endif
w->d_func()->setDirtyOpaqueRegion();
QMoveEvent e(r.topLeft(), oldp);
QApplication::sendEvent(w, &e);
}
}
}
}
QInputContext *QWidgetPrivate::assignedInputContext() const
{
#ifndef QT_NO_IM
const QWidget *widget = q_func();
while (widget) {
if (QInputContext *qic = widget->d_func()->ic)
return qic;
widget = widget->parentWidget();
}
#endif
return 0;
}
QInputContext *QWidgetPrivate::inputContext() const
{
#ifndef QT_NO_IM
if (QInputContext *qic = assignedInputContext())
return qic;
return qApp->inputContext();
#else
return 0;
#endif
}
/*!
This function returns the QInputContext for this widget. By
default the input context is inherited from the widgets
parent. For toplevels it is inherited from QApplication.
You can override this and set a special input context for this
widget by using the setInputContext() method.
\sa setInputContext()
*/
QInputContext *QWidget::inputContext()
{
Q_D(QWidget);
if (!testAttribute(Qt::WA_InputMethodEnabled))
return 0;
return d->inputContext();
}
/*!
This function sets the input context \a context
on this widget.
Qt takes ownership of the given input \a context.
\sa inputContext()
*/
void QWidget::setInputContext(QInputContext *context)
{
Q_D(QWidget);
if (!testAttribute(Qt::WA_InputMethodEnabled))
return;
#ifndef QT_NO_IM
if (context == d->ic)
return;
if (d->ic)
delete d->ic;
d->ic = context;
if (d->ic)
d->ic->setParent(this);
#endif
}
/*!
\obsolete
This function can be called on the widget that currently has focus
to reset the input method operating on it.
This function is providing for convenience, instead you should use
\l{QInputContext::}{reset()} on the input context that was
returned by inputContext().
\sa QInputContext, inputContext(), QInputContext::reset()
*/
void QWidget::resetInputContext()
{
if (!hasFocus())
return;
#ifndef QT_NO_IM
QInputContext *qic = this->inputContext();
if(qic)
qic->reset();
#endif // QT_NO_IM
}
#ifdef QT_KEYPAD_NAVIGATION
QPointer<QWidget> QWidgetPrivate::editingWidget;
/*!
Returns true if this widget currently has edit focus; otherwise false.
This feature is only available in Qt for Embedded Linux.
\sa setEditFocus(), QApplication::keypadNavigationEnabled()
*/
bool QWidget::hasEditFocus() const
{
const QWidget* w = this;
while (w->d_func()->extra && w->d_func()->extra->focus_proxy)
w = w->d_func()->extra->focus_proxy;
return QWidgetPrivate::editingWidget == w;
}
/*!
\fn void QWidget::setEditFocus(bool enable)
If \a enable is true, make this widget have edit focus, in which
case Qt::Key_Up and Qt::Key_Down will be delivered to the widget
normally; otherwise, Qt::Key_Up and Qt::Key_Down are used to
change focus.
This feature is only available in Qt for Embedded Linux and Qt
for Symbian.
\sa hasEditFocus(), QApplication::keypadNavigationEnabled()
*/
void QWidget::setEditFocus(bool on)
{
QWidget *f = this;
while (f->d_func()->extra && f->d_func()->extra->focus_proxy)
f = f->d_func()->extra->focus_proxy;
if (QWidgetPrivate::editingWidget && QWidgetPrivate::editingWidget != f)
QWidgetPrivate::editingWidget->setEditFocus(false);
if (on && !f->hasFocus())
f->setFocus();
if ((!on && !QWidgetPrivate::editingWidget)
|| (on && QWidgetPrivate::editingWidget == f)) {
return;
}
if (!on && QWidgetPrivate::editingWidget == f) {
QWidgetPrivate::editingWidget = 0;
QEvent event(QEvent::LeaveEditFocus);
QApplication::sendEvent(f, &event);
QApplication::sendEvent(f->style(), &event);
} else if (on) {
QWidgetPrivate::editingWidget = f;
QEvent event(QEvent::EnterEditFocus);
QApplication::sendEvent(f, &event);
QApplication::sendEvent(f->style(), &event);
}
}
#endif
/*!
\property QWidget::autoFillBackground
\brief whether the widget background is filled automatically
\since 4.1
If enabled, this property will cause Qt to fill the background of the
widget before invoking the paint event. The color used is defined by the
QPalette::Window color role from the widget's \l{QPalette}{palette}.
In addition, Windows are always filled with QPalette::Window, unless the
WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
This property cannot be turned off (i.e., set to false) if a widget's
parent has a static gradient for its background.
\warning Use this property with caution in conjunction with
\l{Qt Style Sheets}. When a widget has a style sheet with a valid
background or a border-image, this property is automatically disabled.
By default, this property is false.
\sa Qt::WA_OpaquePaintEvent, Qt::WA_NoSystemBackground,
{QWidget#Transparency and Double Buffering}{Transparency and Double Buffering}
*/
bool QWidget::autoFillBackground() const
{
Q_D(const QWidget);
return d->extra && d->extra->autoFillBackground;
}
void QWidget::setAutoFillBackground(bool enabled)
{
Q_D(QWidget);
if (!d->extra)
d->createExtra();
if (d->extra->autoFillBackground == enabled)
return;
d->extra->autoFillBackground = enabled;
d->updateIsOpaque();
update();
d->updateIsOpaque();
}
/*!
\class QWidget
\brief The QWidget class is the base class of all user interface objects.
\ingroup basicwidgets
The widget is the atom of the user interface: it receives mouse, keyboard
and other events from the window system, and paints a representation of
itself on the screen. Every widget is rectangular, and they are sorted in a
Z-order. A widget is clipped by its parent and by the widgets in front of
it.
A widget that is not embedded in a parent widget is called a window.
Usually, windows have a frame and a title bar, although it is also possible
to create windows without such decoration using suitable
\l{Qt::WindowFlags}{window flags}). In Qt, QMainWindow and the various
subclasses of QDialog are the most common window types.
Every widget's constructor accepts one or two standard arguments:
\list 1
\i \c{QWidget *parent = 0} is the parent of the new widget. If it is 0
(the default), the new widget will be a window. If not, it will be
a child of \e parent, and be constrained by \e parent's geometry
(unless you specify Qt::Window as window flag).
\i \c{Qt::WindowFlags f = 0} (where available) sets the window flags;
the default is suitable for almost all widgets, but to get, for
example, a window without a window system frame, you must use
special flags.
\endlist
QWidget has many member functions, but some of them have little direct
functionality; for example, QWidget has a font property, but never uses
this itself. There are many subclasses which provide real functionality,
such as QLabel, QPushButton, QListWidget, and QTabWidget.
\section1 Top-Level and Child Widgets
A widget without a parent widget is always an independent window (top-level
widget). For these widgets, setWindowTitle() and setWindowIcon() set the
title bar and icon respectively.
Non-window widgets are child widgets, displayed within their parent
widgets. Most widgets in Qt are mainly useful as child widgets. For
example, it is possible to display a button as a top-level window, but most
people prefer to put their buttons inside other widgets, such as QDialog.
\image parent-child-widgets.png A parent widget containing various child widgets.
The diagram above shows a QGroupBox widget being used to hold various child
widgets in a layout provided by QGridLayout. The QLabel child widgets have
been outlined to indicate their full sizes.
If you want to use a QWidget to hold child widgets you will usually want to
add a layout to the parent QWidget. See \l{Layout Management} for more
information.
\section1 Composite Widgets
When a widget is used as a container to group a number of child widgets, it
is known as a composite widget. These can be created by constructing a
widget with the required visual properties - a QFrame, for example - and
adding child widgets to it, usually managed by a layout. The above diagram
shows such a composite widget that was created using \l{Qt Designer}.
Composite widgets can also be created by subclassing a standard widget,
such as QWidget or QFrame, and adding the necessary layout and child
widgets in the constructor of the subclass. Many of the \l{Qt Examples}
{examples provided with Qt} use this approach, and it is also covered in
the Qt \l{Tutorials}.
\section1 Custom Widgets and Painting
Since QWidget is a subclass of QPaintDevice, subclasses can be used to
display custom content that is composed using a series of painting
operations with an instance of the QPainter class. This approach contrasts
with the canvas-style approach used by the \l{Graphics View}
{Graphics View Framework} where items are added to a scene by the
application and are rendered by the framework itself.
Each widget performs all painting operations from within its paintEvent()
function. This is called whenever the widget needs to be redrawn, either
as a result of some external change or when requested by the application.
The \l{widgets/analogclock}{Analog Clock example} shows how a simple widget
can handle paint events.
\section1 Size Hints and Size Policies
When implementing a new widget, it is almost always useful to reimplement
sizeHint() to provide a reasonable default size for the widget and to set
the correct size policy with setSizePolicy().
By default, composite widgets which do not provide a size hint will be
sized according to the space requirements of their child widgets.
The size policy lets you supply good default behavior for the layout
management system, so that other widgets can contain and manage yours
easily. The default size policy indicates that the size hint represents
the preferred size of the widget, and this is often good enough for many
widgets.
\note The size of top-level widgets are constrained to 2/3 of the desktop's
height and width. You can resize() the widget manually if these bounds are
inadequate.
\section1 Events
Widgets respond to events that are typically caused by user actions. Qt
delivers events to widgets by calling specific event handler functions with
instances of QEvent subclasses containing information about each event.
If your widget only contains child widgets, you probably do not need to
implement any event handlers. If you want to detect a mouse click in a
child widget call the child's underMouse() function inside the widget's
mousePressEvent().
The \l{widgets/scribble}{Scribble example} implements a wider set of
events to handle mouse movement, button presses, and window resizing.
You will need to supply the behavior and content for your own widgets, but
here is a brief overview of the events that are relevant to QWidget,
starting with the most common ones:
\list
\i paintEvent() is called whenever the widget needs to be repainted.
Every widget displaying custom content must implement it. Painting
using a QPainter can only take place in a paintEvent() or a
function called by a paintEvent().
\i resizeEvent() is called when the widget has been resized.
\i mousePressEvent() is called when a mouse button is pressed while
the mouse cursor is inside the widget, or when the widget has
grabbed the mouse using grabMouse(). Pressing the mouse without
releasing it is effectively the same as calling grabMouse().
\i mouseReleaseEvent() is called when a mouse button is released. A
widget receives mouse release events when it has received the
corresponding mouse press event. This means that if the user
presses the mouse inside \e your widget, then drags the mouse
somewhere else before releasing the mouse button, \e your widget
receives the release event. There is one exception: if a popup menu
appears while the mouse button is held down, this popup immediately
steals the mouse events.
\i mouseDoubleClickEvent() is called when the user double-clicks in
the widget. If the user double-clicks, the widget receives a mouse
press event, a mouse release event and finally this event instead
of a second mouse press event. (Some mouse move events may also be
received if the mouse is not held steady during this operation.) It
is \e{not possible} to distinguish a click from a double-click
until the second click arrives. (This is one reason why most GUI
books recommend that double-clicks be an extension of
single-clicks, rather than trigger a different action.)
\endlist
Widgets that accept keyboard input need to reimplement a few more event
handlers:
\list
\i keyPressEvent() is called whenever a key is pressed, and again when
a key has been held down long enough for it to auto-repeat. The
\key Tab and \key Shift+Tab keys are only passed to the widget if
they are not used by the focus-change mechanisms. To force those
keys to be processed by your widget, you must reimplement
QWidget::event().
\i focusInEvent() is called when the widget gains keyboard focus
(assuming you have called setFocusPolicy()). Well-behaved widgets
indicate that they own the keyboard focus in a clear but discreet
way.
\i focusOutEvent() is called when the widget loses keyboard focus.
\endlist
You may be required to also reimplement some of the less common event
handlers:
\list
\i mouseMoveEvent() is called whenever the mouse moves while a mouse
button is held down. This can be useful during drag and drop
operations. If you call \l{setMouseTracking()}{setMouseTracking}(true),
you get mouse move events even when no buttons are held down.
(See also the \l{Drag and Drop} guide.)
\i keyReleaseEvent() is called whenever a key is released and while it
is held down (if the key is auto-repeating). In that case, the
widget will receive a pair of key release and key press event for
every repeat. The \key Tab and \key Shift+Tab keys are only passed
to the widget if they are not used by the focus-change mechanisms.
To force those keys to be processed by your widget, you must
reimplement QWidget::event().
\i wheelEvent() is called whenever the user turns the mouse wheel
while the widget has the focus.
\i enterEvent() is called when the mouse enters the widget's screen
space. (This excludes screen space owned by any of the widget's
children.)
\i leaveEvent() is called when the mouse leaves the widget's screen
space. If the mouse enters a child widget it will not cause a
leaveEvent().
\i moveEvent() is called when the widget has been moved relative to
its parent.
\i closeEvent() is called when the user closes the widget (or when
close() is called).
\endlist
There are also some rather obscure events described in the documentation
for QEvent::Type. To handle these events, you need to reimplement event()
directly.
The default implementation of event() handles \key Tab and \key Shift+Tab
(to move the keyboard focus), and passes on most of the other events to
one of the more specialized handlers above.
Events and the mechanism used to deliver them are covered in
\l{The Event System}.
\section1 Groups of Functions and Properties
\table
\header \i Context \i Functions and Properties
\row \i Window functions \i
show(),
hide(),
raise(),
lower(),
close().
\row \i Top-level windows \i
\l windowModified, \l windowTitle, \l windowIcon, \l windowIconText,
\l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
\l maximized, showMaximized(), \l fullScreen, showFullScreen(),
showNormal().
\row \i Window contents \i
update(),
repaint(),
scroll().
\row \i Geometry \i
\l pos, x(), y(), \l rect, \l size, width(), height(), move(), resize(),
\l sizePolicy, sizeHint(), minimumSizeHint(),
updateGeometry(), layout(),
\l frameGeometry, \l geometry, \l childrenRect, \l childrenRegion,
adjustSize(),
mapFromGlobal(), mapToGlobal(),
mapFromParent(), mapToParent(),
\l maximumSize, \l minimumSize, \l sizeIncrement,
\l baseSize, setFixedSize()
\row \i Mode \i
\l visible, isVisibleTo(),
\l enabled, isEnabledTo(),
\l modal,
isWindow(),
\l mouseTracking,
\l updatesEnabled,
visibleRegion().
\row \i Look and feel \i
style(),
setStyle(),
\l styleSheet,
\l cursor,
\l font,
\l palette,
backgroundRole(), setBackgroundRole(),
fontInfo(), fontMetrics().
\row \i Keyboard focus functions \i
\l focus, \l focusPolicy,
setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
focusNextChild(), focusPreviousChild().
\row \i Mouse and keyboard grabbing \i
grabMouse(), releaseMouse(),
grabKeyboard(), releaseKeyboard(),
mouseGrabber(), keyboardGrabber().
\row \i Event handlers \i
event(),
mousePressEvent(),
mouseReleaseEvent(),
mouseDoubleClickEvent(),
mouseMoveEvent(),
keyPressEvent(),
keyReleaseEvent(),
focusInEvent(),
focusOutEvent(),
wheelEvent(),
enterEvent(),
leaveEvent(),
paintEvent(),
moveEvent(),
resizeEvent(),
closeEvent(),
dragEnterEvent(),
dragMoveEvent(),
dragLeaveEvent(),
dropEvent(),
childEvent(),
showEvent(),
hideEvent(),
customEvent().
changeEvent(),
\row \i System functions \i
parentWidget(), window(), setParent(), winId(),
find(), metric().
\row \i Interactive help \i
setToolTip(), setWhatsThis()
\endtable
\section1 Widget Style Sheets
In addition to the standard widget styles for each platform, widgets can
also be styled according to rules specified in a \l{styleSheet}
{style sheet}. This feature enables you to customize the appearance of
specific widgets to provide visual cues to users about their purpose. For
example, a button could be styled in a particular way to indicate that it
performs a destructive action.
The use of widget style sheets is described in more detail in the
\l{Qt Style Sheets} document.
\section1 Transparency and Double Buffering
Since Qt 4.0, QWidget automatically double-buffers its painting, so there
is no need to write double-buffering code in paintEvent() to avoid
flicker.
Since Qt 4.1, the Qt::WA_ContentsPropagated widget attribute has been
deprecated. Instead, the contents of parent widgets are propagated by
default to each of their children as long as Qt::WA_PaintOnScreen is not
set. Custom widgets can be written to take advantage of this feature by
updating irregular regions (to create non-rectangular child widgets), or
painting with colors that have less than full alpha component. The
following diagram shows how attributes and properties of a custom widget
can be fine-tuned to achieve different effects.
\image propagation-custom.png
In the above diagram, a semi-transparent rectangular child widget with an
area removed is constructed and added to a parent widget (a QLabel showing
a pixmap). Then, different properties and widget attributes are set to
achieve different effects:
\list
\i The left widget has no additional properties or widget attributes
set. This default state suits most custom widgets using
transparency, are irregularly-shaped, or do not paint over their
entire area with an opaque brush.
\i The center widget has the \l autoFillBackground property set. This
property is used with custom widgets that rely on the widget to
supply a default background, and do not paint over their entire
area with an opaque brush.
\i The right widget has the Qt::WA_OpaquePaintEvent widget attribute
set. This indicates that the widget will paint over its entire area
with opaque colors. The widget's area will initially be
\e{uninitialized}, represented in the diagram with a red diagonal
grid pattern that shines through the overpainted area. The
Qt::WA_OpaquePaintArea attribute is useful for widgets that need to
paint their own specialized contents quickly and do not need a
default filled background.
\endlist
To rapidly update custom widgets with simple background colors, such as
real-time plotting or graphing widgets, it is better to define a suitable
background color (using setBackgroundRole() with the
QPalette::Window role), set the \l autoFillBackground property, and only
implement the necessary drawing functionality in the widget's paintEvent().
To rapidly update custom widgets that constantly paint over their entire
areas with opaque content, e.g., video streaming widgets, it is better to
set the widget's Qt::WA_OpaquePaintEvent, avoiding any unnecessary overhead
associated with repainting the widget's background.
If a widget has both the Qt::WA_OpaquePaintEvent widget attribute \e{and}
the \l autoFillBackground property set, the Qt::WA_OpaquePaintEvent
attribute takes precedence. Depending on your requirements, you should
choose either one of them.
Since Qt 4.1, the contents of parent widgets are also propagated to
standard Qt widgets. This can lead to some unexpected results if the
parent widget is decorated in a non-standard way, as shown in the diagram
below.