-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathqwidget.cpp
13245 lines (10973 loc) · 428 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) 2017 The Qt Company Ltd.
// Copyright (C) 2016 Intel Corporation.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qapplication.h"
#include "qapplication_p.h"
#include "qbrush.h"
#include "qcursor.h"
#include "qevent.h"
#include "qlayout.h"
#if QT_CONFIG(menu)
#include "qmenu.h"
#endif
#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"
#include "qstylehints.h"
#if QT_CONFIG(accessibility)
# include "qaccessible.h"
#endif
#include <qpa/qplatformwindow.h>
#include <qpa/qplatformwindow_p.h>
#include "private/qwidgetwindow_p.h"
#include "qpainter.h"
#if QT_CONFIG(tooltip)
#include "qtooltip.h"
#endif
#if QT_CONFIG(whatsthis)
#include "qwhatsthis.h"
#endif
#include "qdebug.h"
#include "private/qstylesheetstyle_p.h"
#include "private/qstyle_p.h"
#include "qfileinfo.h"
#include "qscopeguard.h"
#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qinputmethod.h>
#if QT_CONFIG(graphicseffect)
#include <private/qgraphicseffect_p.h>
#endif
#include <qbackingstore.h>
#include <private/qwidgetrepaintmanager_p.h>
#include <private/qpaintengine_raster_p.h>
#include "qwidget_p.h"
#include <QtGui/private/qwindow_p.h>
#if QT_CONFIG(action)
# include "QtGui/private/qaction_p.h"
#endif
#include "qlayout_p.h"
#if QT_CONFIG(graphicsview)
#include "QtWidgets/qgraphicsproxywidget.h"
#include "QtWidgets/qgraphicsscene.h"
#include "private/qgraphicsproxywidget_p.h"
#endif
#include "QtWidgets/qabstractscrollarea.h"
#include "private/qabstractscrollarea_p.h"
#include "private/qevent_p.h"
#include "private/qgesturemanager_p.h"
#ifdef QT_KEYPAD_NAVIGATION
#if QT_CONFIG(tabwidget)
#include "qtabwidget.h" // Needed in inTabWidget()
#endif
#endif // QT_KEYPAD_NAVIGATION
#include "qwindowcontainer_p.h"
#include <sstream>
QT_BEGIN_NAMESPACE
using namespace QNativeInterface::Private;
using namespace Qt::StringLiterals;
Q_LOGGING_CATEGORY(lcWidgetPainting, "qt.widgets.painting", QtWarningMsg);
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()));
}
extern bool qt_sendSpontaneousEvent(QObject*, QEvent*); // qapplication.cpp
QWidgetPrivate::QWidgetPrivate(int version)
: QObjectPrivate(version)
, focus_next(nullptr)
, focus_prev(nullptr)
, focus_child(nullptr)
, layout(nullptr)
, needsFlush(nullptr)
, redirectDev(nullptr)
, widgetItem(nullptr)
, extraPaintEngine(nullptr)
, polished(nullptr)
, graphicsEffect(nullptr)
#if !defined(QT_NO_IM)
, imHints(Qt::ImhNone)
#endif
#if QT_CONFIG(tooltip)
, toolTipDuration(-1)
#endif
, directFontResolveMask(0)
, inheritedFontResolveMask(0)
, directPaletteResolveMask(0)
, inheritedPaletteResolveMask(0)
, leftmargin(0)
, topmargin(0)
, rightmargin(0)
, bottommargin(0)
, leftLayoutItemMargin(0)
, topLayoutItemMargin(0)
, rightLayoutItemMargin(0)
, bottomLayoutItemMargin(0)
, hd(nullptr)
, size_policy(QSizePolicy::Preferred, QSizePolicy::Preferred)
, fg_role(QPalette::NoRole)
, bg_role(QPalette::NoRole)
, dirtyOpaqueChildren(1)
, isOpaque(0)
, retainSizeWhenHiddenChanged(0)
, inDirtyList(0)
, isScrolled(0)
, isMoved(0)
, usesDoubleBufferedGLContext(0)
, mustHaveWindowHandle(0)
, renderToTexture(0)
, textureChildSeen(0)
#ifndef QT_NO_IM
, inheritsInputMethodHints(0)
#endif
, renderToTextureReallyDirty(1)
, usesRhiFlush(0)
, childrenHiddenByWState(0)
, childrenShownByExpose(0)
#if defined(Q_OS_WIN)
, noPaintOnScreen(0)
#endif
{
if (Q_UNLIKELY(!qApp)) {
qFatal("QWidget: Must construct a QApplication before a QWidget");
return;
}
#ifdef QT_BUILD_INTERNAL
// Don't check the version parameter in internal builds.
// This allows incompatible versions to be loaded, possibly for testing.
Q_UNUSED(version);
#else
if (Q_UNLIKELY(version != QObjectPrivateVersion))
qFatal("Cannot mix incompatible Qt library (version 0x%x) with this library (version 0x%x)",
version, QObjectPrivateVersion);
#endif
willBeWidget = true; // used in QObject's ctor
memset(high_attributes, 0, sizeof(high_attributes));
#ifdef QWIDGET_EXTRA_DEBUG
static int count = 0;
qDebug() << "widgets" << ++count;
#endif
}
QWidgetPrivate::~QWidgetPrivate()
{
if (widgetItem)
widgetItem->wid = nullptr;
if (extra)
deleteExtra();
}
/*!
\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;
if (w->testAttribute(Qt::WA_WState_Created))
w->d_func()->setWSGeometry();
w->d_func()->setDirtyOpaqueRegion();
QMoveEvent e(r.topLeft(), oldp);
QCoreApplication::sendEvent(w, &e);
}
}
}
}
void QWidgetPrivate::setWSGeometry()
{
Q_Q(QWidget);
if (QWindow *window = q->windowHandle())
window->setGeometry(data.crect);
}
void QWidgetPrivate::updateWidgetTransform(QEvent *event)
{
Q_Q(QWidget);
if (q == QGuiApplication::focusObject() || event->type() == QEvent::FocusIn) {
QTransform t;
QPoint p = q->mapTo(q->topLevelWidget(), QPoint(0,0));
t.translate(p.x(), p.y());
QGuiApplication::inputMethod()->setInputItemTransform(t);
QGuiApplication::inputMethod()->setInputItemRectangle(q->rect());
QGuiApplication::inputMethod()->update(Qt::ImInputItemClipRectangle);
}
}
#ifdef QT_KEYPAD_NAVIGATION
QPointer<QWidget> QWidgetPrivate::editingWidget;
/*!
Returns \c true if this widget currently has edit focus; otherwise false.
This feature is only available in Qt for Embedded Linux.
\sa setEditFocus(), QApplication::navigationMode()
*/
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.
\sa hasEditFocus(), QApplication::navigationMode()
*/
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);
QCoreApplication::sendEvent(f, &event);
QCoreApplication::sendEvent(f->style(), &event);
} else if (on) {
QWidgetPrivate::editingWidget = f;
QEvent event(QEvent::EnterEditFocus);
QCoreApplication::sendEvent(f, &event);
QCoreApplication::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 \c 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
\inmodule QtWidgets
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
\li \c{QWidget *parent = nullptr} is the parent of the new widget.
If it is \nullptr (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).
\li \c{Qt::WindowFlags f = { }} (where available) sets the window flags;
the default is suitable for most 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 that 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.
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 Widgets Examples}
{examples provided with Qt} use this approach, and it is also covered in
the Qt \l{Widgets Tutorial}.
\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
because 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 that 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 don't 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
\li 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().
\li resizeEvent() is called when the widget has been resized.
\li 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().
\li 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.
\li 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, (a mouse click event,) a second
mouse press, this event and finally a second mouse release 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
\li 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
\uicontrol Tab and \uicontrol 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().
\li 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.
\li 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
\li 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 in Qt}{Drag and Drop} guide.)
\li 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 \uicontrol Tab and \uicontrol 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().
\li wheelEvent() is called whenever the user turns the mouse wheel
while the widget has the focus.
\li enterEvent() is called when the mouse enters the widget's screen
space. (This excludes screen space owned by any of the widget's
children.)
\li 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().
\li moveEvent() is called when the widget has been moved relative to
its parent.
\li 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 \uicontrol Tab and \uicontrol 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 \li Context \li Functions and Properties
\row \li Window functions \li
show(),
hide(),
raise(),
lower(),
close().
\row \li Top-level windows \li
\l windowModified, \l windowTitle, \l windowIcon,
\l isActiveWindow, activateWindow(), \l minimized, showMinimized(),
\l maximized, showMaximized(), \l fullScreen, showFullScreen(),
showNormal().
\row \li Window contents \li
update(),
repaint(),
scroll().
\row \li Geometry \li
\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 \li Mode \li
\l visible, isVisibleTo(),
\l enabled, isEnabledTo(),
\l modal,
isWindow(),
\l mouseTracking,
\l updatesEnabled,
visibleRegion().
\row \li Look and feel \li
style(),
setStyle(),
\l styleSheet,
\l cursor,
\l font,
\l palette,
backgroundRole(), setBackgroundRole(),
fontInfo(), fontMetrics().
\row \li Keyboard focus functions \li
\l focus, \l focusPolicy,
setFocus(), clearFocus(), setTabOrder(), setFocusProxy(),
focusNextChild(), focusPreviousChild().
\row \li Mouse and keyboard grabbing \li
grabMouse(), releaseMouse(),
grabKeyboard(), releaseKeyboard(),
mouseGrabber(), keyboardGrabber().
\row \li Event handlers \li
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 \li System functions \li
parentWidget(), window(), setParent(), winId(),
find(), metric().
\row \li Context menu \li
contextMenuPolicy, contextMenuEvent(),
customContextMenuRequested(), actions()
\row \li Interactive help \li
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
QWidget automatically double-buffers its painting, so there
is no need to write double-buffering code in paintEvent() to avoid
flicker.
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
\li The left widget has no additional properties or widget attributes
set. This default state suits most custom widgets that have
transparency, are irregularly-shaped, or do not paint over their
entire area with an opaque brush.
\li 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.
\li 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.
\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, for example, 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.
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.
\image propagation-standard.png
The scope for customizing the painting behavior of standard Qt widgets,
without resorting to subclassing, is slightly less than that possible for
custom widgets. Usually, the desired appearance of a standard widget can be
achieved by setting its \l autoFillBackground property.
\section1 Creating Translucent Windows
You can create windows with translucent regions on window systems that
support compositing.
To enable this feature in a top-level widget, set its Qt::WA_TranslucentBackground
attribute with setAttribute() and ensure that its background is painted with
non-opaque colors in the regions you want to be partially transparent.
Platform notes:
\list
\li X11: This feature relies on the use of an X server that supports ARGB visuals
and a compositing window manager.
\li Windows: The widget needs to have the Qt::FramelessWindowHint window flag set
for the translucency to work.
\li \macos: The widget needs to have the Qt::FramelessWindowHint window flag set
for the translucency to work.
\endlist
\section1 Native Widgets vs Alien Widgets
Alien widgets are widgets unknown to the windowing system. They do not have
a native window handle associated with them. This feature significantly
speeds up widget painting, resizing, and removes flicker.
Should you require the old behavior with native windows, choose one of the
following options:
\list 1
\li Use the \c{QT_USE_NATIVE_WINDOWS=1} in your environment.
\li Set the Qt::AA_NativeWindows attribute on your application. All
widgets will be native widgets.
\li Set the Qt::WA_NativeWindow attribute on widgets: The widget itself
and all its ancestors will become native (unless
Qt::WA_DontCreateNativeAncestors is set).
\li Call QWidget::winId to enforce a native window (this implies 3).
\li Set the Qt::WA_PaintOnScreen attribute to enforce a native window
(this implies 3).
\endlist
\sa QEvent, QPainter, QGridLayout, QBoxLayout
*/
QWidgetMapper *QWidgetPrivate::mapper = nullptr; // widget with wid
QWidgetSet *QWidgetPrivate::allWidgets = nullptr; // widgets with no wid
/*****************************************************************************
QWidget member functions
*****************************************************************************/
/*
Widget state flags:
\list
\li Qt::WA_WState_Created The widget has a valid winId().
\li Qt::WA_WState_Visible The widget is currently visible.
\li Qt::WA_WState_Hidden The widget is hidden, i.e. it won't
become visible unless you call show() on it. Qt::WA_WState_Hidden
implies !Qt::WA_WState_Visible.
\li Qt::WA_WState_CompressKeys Compress keyboard events.
\li Qt::WA_WState_BlockUpdates Repaints and updates are disabled.
\li Qt::WA_WState_InPaintEvent Currently processing a paint event.
\li Qt::WA_WState_Reparented The widget has been reparented.
\li Qt::WA_WState_ConfigPending A configuration (resize/move) event is pending.
\endlist
*/
struct QWidgetExceptionCleaner
{
/* this cleans up when the constructor throws an exception */
static inline void cleanup(QWidget *that, QWidgetPrivate *d)
{
#ifdef QT_NO_EXCEPTIONS
Q_UNUSED(that);
Q_UNUSED(d);
#else
QWidgetPrivate::allWidgets->remove(that);
if (d->focus_next != that) {
if (d->focus_next)
d->focus_next->d_func()->focus_prev = d->focus_prev;
if (d->focus_prev)
d->focus_prev->d_func()->focus_next = d->focus_next;
}
#endif
}
};
/*!
Constructs a widget which is a child of \a parent, with widget
flags set to \a f.
If \a parent is \nullptr, the new widget becomes a window. If
\a parent is another widget, this widget becomes a child window
inside \a parent. The new widget is deleted when its \a parent is
deleted.
The widget flags argument, \a f, is normally 0, but it can be set
to customize the frame of a window (i.e. \a parent must be
\nullptr). To customize the frame, use a value composed
from the bitwise OR of any of the \l{Qt::WindowFlags}{window flags}.
If you add a child widget to an already visible widget you must
explicitly show the child to make it visible.
Note that the X11 version of Qt may not be able to deliver all
combinations of style flags on all systems. This is because on
X11, Qt can only ask the window manager, and the window manager
can override the application's settings. On Windows, Qt can set
whatever flags you want.
\sa windowFlags
*/
QWidget::QWidget(QWidget *parent, Qt::WindowFlags f)
: QObject(*new QWidgetPrivate, nullptr), QPaintDevice()
{
QT_TRY {
d_func()->init(parent, f);
} QT_CATCH(...) {
QWidgetExceptionCleaner::cleanup(this, d_func());
QT_RETHROW;
}
}
/*! \internal
*/
QWidget::QWidget(QWidgetPrivate &dd, QWidget* parent, Qt::WindowFlags f)
: QObject(dd, nullptr), QPaintDevice()
{
Q_D(QWidget);
QT_TRY {
d->init(parent, f);
} QT_CATCH(...) {
QWidgetExceptionCleaner::cleanup(this, d_func());
QT_RETHROW;
}
}
/*!
\internal
*/
int QWidget::devType() const
{
return QInternal::Widget;
}
//### w is a "this" ptr, passed as a param because QWorkspace needs special logic
void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w)
{
bool customize = (flags & (Qt::CustomizeWindowHint
| Qt::FramelessWindowHint
| Qt::WindowTitleHint
| Qt::WindowSystemMenuHint
| Qt::WindowMinimizeButtonHint
| Qt::WindowMaximizeButtonHint
| Qt::WindowCloseButtonHint
| Qt::WindowContextHelpButtonHint));
uint type = (flags & Qt::WindowType_Mask);
if ((type == Qt::Widget || type == Qt::SubWindow) && w && !w->parent()) {
type = Qt::Window;
flags |= Qt::Window;
}
if (flags & Qt::CustomizeWindowHint) {
// modify window flags to make them consistent.
// Only enable this on non-Mac platforms. Since the old way of doing this would
// interpret WindowSystemMenuHint as a close button and we can't change that behavior
// we can't just add this in.
if ((flags & (Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowContextHelpButtonHint))
# ifdef Q_OS_WIN
&& type != Qt::Dialog // QTBUG-2027, allow for menu-less dialogs.
# endif
) {
flags |= Qt::WindowSystemMenuHint;
flags |= Qt::WindowTitleHint;
flags &= ~Qt::FramelessWindowHint;
}
} else if (customize && !(flags & Qt::FramelessWindowHint)) {
// if any of the window hints that affect the titlebar are set
// and the window is supposed to have frame, we add a titlebar
// and system menu by default.
flags |= Qt::WindowSystemMenuHint;
flags |= Qt::WindowTitleHint;
}
if (!customize) { // don't modify window flags if the user explicitly set them.
flags |= Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint;
if (type != Qt::Dialog && type != Qt::Sheet && type != Qt::Tool)
flags |= Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint | Qt::WindowFullscreenButtonHint;
}
if (w->testAttribute(Qt::WA_TransparentForMouseEvents))
flags |= Qt::WindowTransparentForInput;
}
void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f)
{
Q_Q(QWidget);
isWidget = true;
wasWidget = true;
Q_ASSERT_X(q != parentWidget, Q_FUNC_INFO, "Cannot parent a QWidget to itself");
if (Q_UNLIKELY(!qobject_cast<QApplication *>(QCoreApplication::instance())))
qFatal("QWidget: Cannot create a QWidget without QApplication");
Q_ASSERT(allWidgets);
if (allWidgets)
allWidgets->insert(q);
q->data = &data;
#if QT_CONFIG(thread)
if (!parent) {
Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget",
"Widgets must be created in the GUI thread.");
}
#endif
data.fstrut_dirty = true;
data.winid = 0;
data.widget_attributes = 0;
data.window_flags = f;
data.window_state = 0;
data.focus_policy = 0;
data.context_menu_policy = Qt::DefaultContextMenu;
data.window_modality = Qt::NonModal;
data.sizehint_forced = 0;
data.is_closing = false;
data.in_show = 0;
data.in_set_window_state = 0;
data.in_destructor = false;
// Widgets with Qt::MSWindowsOwnDC (typically QGLWidget) must have a window handle.
if (f & Qt::MSWindowsOwnDC) {
mustHaveWindowHandle = 1;
q->setAttribute(Qt::WA_NativeWindow);
}
q->setAttribute(Qt::WA_QuitOnClose); // might be cleared in adjustQuitOnCloseAttribute()
adjustQuitOnCloseAttribute();
q->setAttribute(Qt::WA_ContentsMarginsRespectsSafeArea);
q->setAttribute(Qt::WA_WState_Hidden);
//give potential windows a bigger "pre-initial" size; create() will give them a new size later
data.crect = parentWidget ? QRect(0,0,100,30) : QRect(0,0,640,480);
focus_next = focus_prev = q;
if ((f & Qt::WindowType_Mask) == Qt::Desktop)
q->create();
else if (parentWidget)
q->setParent(parentWidget, data.window_flags);
else {
adjustFlags(data.window_flags, q);
resolveLayoutDirection();
// opaque system background?
const QBrush &background = q->palette().brush(QPalette::Window);
setOpaque(q->isWindow() && background.style() != Qt::NoBrush && background.isOpaque());
}
data.fnt = QFont(data.fnt, q);
q->setAttribute(Qt::WA_PendingMoveEvent);