-
Notifications
You must be signed in to change notification settings - Fork 181
/
qquickwidget.cpp
1924 lines (1640 loc) · 64.8 KB
/
qquickwidget.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) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qquickwidget.h"
#include "qquickwidget_p.h"
#include "qaccessiblequickwidgetfactory_p.h"
#include <QtWidgets/private/qwidgetrepaintmanager_p.h>
#include "private/qquickwindow_p.h"
#include "private/qquickitem_p.h"
#include "private/qquickitemchangelistener_p.h"
#include "private/qquickrendercontrol_p.h"
#include "private/qsgrhisupport_p.h"
#include "private/qsgsoftwarerenderer_p.h"
#include <private/qqmldebugconnector_p.h>
#include <private/qquickprofiler_p.h>
#include <private/qqmldebugserviceinterfaces_p.h>
#include <QtQml/qqmlengine.h>
#include <private/qqmlengine_p.h>
#include <QtCore/qbasictimer.h>
#include <QtGui/QOffscreenSurface>
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/qpa/qplatformintegration.h>
#include <QtGui/QPainter>
#include <QtQuick/QSGRendererInterface>
#ifdef Q_OS_WIN
#if QT_CONFIG(messagebox)
# include <QtWidgets/QMessageBox>
#endif
# include <QtCore/QLibraryInfo>
# include <QtCore/qt_windows.h>
#endif
#include <QtQuick/qquickgraphicsdevice.h>
#include <QtQuick/qquickrendertarget.h>
#include "private/qwidget_p.h"
#if QT_CONFIG(graphicsview)
#include <QtWidgets/qgraphicsscene.h>
#include <QtWidgets/qgraphicsview.h>
#endif
QT_BEGIN_NAMESPACE
QQuickWidgetOffscreenWindow::QQuickWidgetOffscreenWindow(QQuickWindowPrivate &dd, QQuickRenderControl *control)
:QQuickWindow(dd, control)
{
setTitle(QString::fromLatin1("Offscreen"));
setObjectName(QString::fromLatin1("QQuickWidgetOffscreenWindow"));
}
// override setVisble to prevent accidental offscreen window being created
// by base class.
class QQuickWidgetOffscreenWindowPrivate: public QQuickWindowPrivate {
public:
void setVisible(bool visible) override {
Q_Q(QWindow);
// this stays always invisible
visibility = visible ? QWindow::Windowed : QWindow::Hidden;
q->visibilityChanged(visibility); // workaround for QTBUG-49054
}
};
class QQuickWidgetRenderControlPrivate;
class QQuickWidgetRenderControl : public QQuickRenderControl
{
Q_DECLARE_PRIVATE(QQuickWidgetRenderControl)
public:
QQuickWidgetRenderControl(QQuickWidget *quickwidget);
QWindow *renderWindow(QPoint *offset) override;
};
class QQuickWidgetRenderControlPrivate : public QQuickRenderControlPrivate
{
public:
Q_DECLARE_PUBLIC(QQuickWidgetRenderControl)
QQuickWidgetRenderControlPrivate(QQuickWidgetRenderControl *renderControl, QQuickWidget *qqw)
: QQuickRenderControlPrivate(renderControl)
, m_quickWidget(qqw)
{
}
bool isRenderWindow(const QWindow *w) override {
#if QT_CONFIG(graphicsview)
QWidgetPrivate *widgetd = QWidgetPrivate::get(m_quickWidget);
auto *proxy = (widgetd && widgetd->extra) ? widgetd->extra->proxyWidget : nullptr;
auto *scene = proxy ? proxy->scene() : nullptr;
if (scene) {
for (const auto &view : scene->views()) {
if (view->window()->windowHandle() == w)
return true;
}
}
return m_quickWidget->window()->windowHandle() == w;
#endif
}
QQuickWidget *m_quickWidget;
};
QQuickWidgetRenderControl::QQuickWidgetRenderControl(QQuickWidget *quickWidget)
: QQuickRenderControl(*(new QQuickWidgetRenderControlPrivate(this, quickWidget)), nullptr)
{
}
QWindow *QQuickWidgetRenderControl::renderWindow(QPoint *offset)
{
Q_D(QQuickWidgetRenderControl);
if (offset)
*offset = d->m_quickWidget->mapTo(d->m_quickWidget->window(), QPoint());
QWindow *result = nullptr;
#if QT_CONFIG(graphicsview)
QWidgetPrivate *widgetd = QWidgetPrivate::get(d->m_quickWidget);
if (widgetd->extra) {
if (auto proxy = widgetd->extra->proxyWidget) {
auto scene = proxy->scene();
if (scene) {
const auto views = scene->views();
if (!views.isEmpty()) {
// Get the first QGV containing the proxy. Not ideal, but the callers
// of this function aren't prepared to handle more than one render window.
auto candidateView = views.first();
result = candidateView->window()->windowHandle();
}
}
}
}
#endif
if (!result)
result = d->m_quickWidget->window()->windowHandle();
return result;
}
void QQuickWidgetPrivate::initOffscreenWindow()
{
Q_Q(QQuickWidget);
ensureBackingScene();
offscreenWindow->setScreen(q->screen());
// Do not call create() on offscreenWindow.
QWidget::connect(offscreenWindow, SIGNAL(sceneGraphInitialized()), q, SLOT(createFramebufferObject()));
QWidget::connect(offscreenWindow, SIGNAL(sceneGraphInvalidated()), q, SLOT(destroyFramebufferObject()));
QWidget::connect(offscreenWindow, &QQuickWindow::focusObjectChanged, q, &QQuickWidget::propagateFocusObjectChanged);
#if QT_CONFIG(accessibility)
QAccessible::installFactory(&qAccessibleQuickWidgetFactory);
#endif
}
void QQuickWidgetPrivate::ensureBackingScene()
{
// This should initialize, if not already done, the absolute minimum set of
// mandatory backing resources, meaning the QQuickWindow and its
// QQuickRenderControl. This function may be called very early on upon
// construction, including before init() even.
Q_Q(QQuickWidget);
if (!renderControl)
renderControl = new QQuickWidgetRenderControl(q);
if (!offscreenWindow)
offscreenWindow = new QQuickWidgetOffscreenWindow(*new QQuickWidgetOffscreenWindowPrivate(), renderControl);
// Check if the Software Adaptation is being used
auto sgRendererInterface = offscreenWindow->rendererInterface();
if (sgRendererInterface && sgRendererInterface->graphicsApi() == QSGRendererInterface::Software)
useSoftwareRenderer = true;
}
void QQuickWidgetPrivate::init(QQmlEngine* e)
{
Q_Q(QQuickWidget);
initOffscreenWindow();
if (!useSoftwareRenderer) {
if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RhiBasedRendering))
setRenderToTexture();
else
qWarning("QQuickWidget is not supported on this platform.");
}
engine = e;
if (!engine.isNull() && !engine.data()->incubationController())
engine.data()->setIncubationController(offscreenWindow->incubationController());
#if QT_CONFIG(quick_draganddrop)
q->setAcceptDrops(true);
#endif
QObject::connect(renderControl, SIGNAL(renderRequested()), q, SLOT(triggerUpdate()));
QObject::connect(renderControl, SIGNAL(sceneChanged()), q, SLOT(triggerUpdate()));
}
void QQuickWidgetPrivate::ensureEngine() const
{
Q_Q(const QQuickWidget);
if (!engine.isNull())
return;
engine = new QQmlEngine(const_cast<QQuickWidget*>(q));
engine.data()->setIncubationController(offscreenWindow->incubationController());
}
void QQuickWidgetPrivate::invalidateRenderControl()
{
if (!useSoftwareRenderer && rhi) {
// For the user's own OpenGL code connected to some QQuickWindow signals.
rhi->makeThreadLocalNativeContextCurrent();
}
renderControl->invalidate();
}
void QQuickWidgetPrivate::handleWindowChange()
{
Q_Q(QQuickWidget);
if (offscreenWindow->isPersistentSceneGraph()
&& qGuiApp->testAttribute(Qt::AA_ShareOpenGLContexts)
&& rhiConfig().api() == QPlatformBackingStoreRhiConfig::OpenGL)
{
return;
}
// In case of !isPersistentSceneGraph or when we need a new context due to
// the need to share resources with the new window's context, we must both
// invalidate the scenegraph and destroy the context. QQuickRenderControl
// must be recreated because its RHI will contain a dangling pointer to
// the context.
QScopedPointer<QQuickWindow> oldOffScreenWindow(offscreenWindow); // Do not delete before reparenting sgItem
offscreenWindow = nullptr;
delete renderControl;
renderControl = new QQuickWidgetRenderControl(q);
initOffscreenWindow();
QObject::connect(renderControl, SIGNAL(renderRequested()), q, SLOT(triggerUpdate()));
QObject::connect(renderControl, SIGNAL(sceneChanged()), q, SLOT(triggerUpdate()));
if (!source.isEmpty())
execute();
else if (QQuickItem *sgItem = qobject_cast<QQuickItem *>(root))
sgItem->setParentItem(offscreenWindow->contentItem());
}
QQuickWidgetPrivate::QQuickWidgetPrivate()
: root(nullptr)
, component(nullptr)
, offscreenWindow(nullptr)
, renderControl(nullptr)
, rhi(nullptr)
, outputTexture(nullptr)
, depthStencil(nullptr)
, msaaBuffer(nullptr)
, rt(nullptr)
, rtRp(nullptr)
, resizeMode(QQuickWidget::SizeViewToRootObject)
, initialSize(0,0)
, eventPending(false)
, updatePending(false)
, fakeHidden(false)
, requestedSamples(0)
, useSoftwareRenderer(false)
, forceFullUpdate(false)
, deviceLost(false)
{
}
void QQuickWidgetPrivate::destroy()
{
Q_Q(QQuickWidget);
invalidateRenderControl();
q->destroyFramebufferObject();
delete offscreenWindow;
delete renderControl;
offscreenRenderer.reset();
}
void QQuickWidgetPrivate::execute()
{
Q_Q(QQuickWidget);
ensureEngine();
if (root) {
delete root;
root = nullptr;
}
if (component) {
delete component;
component = nullptr;
}
if (!source.isEmpty()) {
component = new QQmlComponent(engine.data(), source, q);
if (!component->isLoading()) {
q->continueExecute();
} else {
QObject::connect(component, SIGNAL(statusChanged(QQmlComponent::Status)),
q, SLOT(continueExecute()));
}
}
}
void QQuickWidgetPrivate::itemGeometryChanged(QQuickItem *resizeItem, QQuickGeometryChange change,
const QRectF &oldGeometry)
{
Q_Q(QQuickWidget);
if (resizeItem == root && resizeMode == QQuickWidget::SizeViewToRootObject) {
// wait for both width and height to be changed
resizetimer.start(0,q);
}
QQuickItemChangeListener::itemGeometryChanged(resizeItem, change, oldGeometry);
}
void QQuickWidgetPrivate::render(bool needsSync)
{
Q_Q(QQuickWidget);
if (!useSoftwareRenderer) {
if (deviceLost) {
deviceLost = false;
initializeWithRhi();
q->createFramebufferObject();
}
if (!rhi) {
qWarning("QQuickWidget: Attempted to render scene with no rhi");
return;
}
// createFramebufferObject() bails out when the size is empty. In this case
// we cannot render either.
if (!outputTexture)
return;
renderControl->beginFrame();
QQuickRenderControlPrivate::FrameStatus frameStatus = QQuickRenderControlPrivate::get(renderControl)->frameStatus;
if (frameStatus == QQuickRenderControlPrivate::DeviceLostInBeginFrame) {
// graphics resources controlled by us must be released
invalidateRenderControl();
// skip this round and hope that the tlw's repaint manager will manage to reinitialize
deviceLost = true;
return;
}
if (frameStatus != QQuickRenderControlPrivate::RecordingFrame) {
qWarning("QQuickWidget: Failed to begin recording a frame");
return;
}
if (needsSync) {
renderControl->polishItems();
renderControl->sync();
}
renderControl->render();
renderControl->endFrame();
} else {
//Software Renderer
if (needsSync) {
renderControl->polishItems();
renderControl->sync();
}
if (!offscreenWindow)
return;
QQuickWindowPrivate *cd = QQuickWindowPrivate::get(offscreenWindow);
auto softwareRenderer = static_cast<QSGSoftwareRenderer*>(cd->renderer);
if (softwareRenderer && !softwareImage.isNull()) {
softwareRenderer->setCurrentPaintDevice(&softwareImage);
if (forceFullUpdate) {
softwareRenderer->markDirty();
forceFullUpdate = false;
}
renderControl->render();
updateRegion += softwareRenderer->flushRegion();
}
}
}
void QQuickWidgetPrivate::renderSceneGraph()
{
Q_Q(QQuickWidget);
updatePending = false;
if (!q->isVisible() || fakeHidden)
return;
render(true);
#if QT_CONFIG(graphicsview)
if (q->window()->graphicsProxyWidget())
QWidgetPrivate::nearestGraphicsProxyWidget(q)->update();
else
#endif
{
if (!useSoftwareRenderer)
q->update(); // schedule composition
else if (!updateRegion.isEmpty())
q->update(updateRegion);
}
}
QImage QQuickWidgetPrivate::grabFramebuffer()
{
if (!useSoftwareRenderer && !rhi)
return QImage();
// grabWindow() does not work for the rhi case, we are in control of the
// render target, and so it is up to us to read it back. When the software
// renderer is in use, just call grabWindow().
if (outputTexture) {
render(true);
QRhiCommandBuffer *cb = nullptr;
rhi->beginOffscreenFrame(&cb);
QRhiResourceUpdateBatch *resUpd = rhi->nextResourceUpdateBatch();
QRhiReadbackResult readResult;
resUpd->readBackTexture(QRhiReadbackDescription(outputTexture), &readResult);
cb->resourceUpdate(resUpd);
rhi->endOffscreenFrame();
if (!readResult.data.isEmpty()) {
QImage wrapperImage(reinterpret_cast<const uchar *>(readResult.data.constData()),
readResult.pixelSize.width(), readResult.pixelSize.height(),
QImage::Format_RGBA8888_Premultiplied);
if (rhi->isYUpInFramebuffer())
return wrapperImage.mirrored();
else
return wrapperImage.copy();
}
return QImage();
}
return offscreenWindow->grabWindow();
}
// Intentionally not overriding the QQuickWindow's focusObject.
// Key events should go to our key event handlers, and then to the
// QQuickWindow, not any in-scene item.
/*!
\module QtQuickWidgets
\title Qt Quick Widgets C++ Classes
\ingroup modules
\brief The C++ API provided by the Qt Quick Widgets module.
\qtcmakepackage QuickWidgets
\qtvariable quickwidgets
To link against the module, add this line to your \l qmake
\c .pro file:
\code
QT += quickwidgets
\endcode
For more information, see the QQuickWidget class documentation.
*/
/*!
\class QQuickWidget
\since 5.3
\brief The QQuickWidget class provides a widget for displaying a Qt Quick user interface.
\inmodule QtQuickWidgets
This is a convenience wrapper for QQuickWindow which will automatically load and display a QML
scene when given the URL of the main source file. Alternatively, you can instantiate your own
objects using QQmlComponent and place them in a manually set up QQuickWidget.
Typical usage:
\code
QQuickWidget *view = new QQuickWidget;
view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
view->show();
\endcode
To receive errors related to loading and executing QML with QQuickWidget,
you can connect to the statusChanged() signal and monitor for QQuickWidget::Error.
The errors are available via QQuickWidget::errors().
QQuickWidget also manages sizing of the view and root object. By default, the \l resizeMode
is SizeViewToRootObject, which will load the component and resize it to the
size of the view. Alternatively the resizeMode may be set to SizeRootObjectToView which
will resize the view to the size of the root object.
\section1 Performance Considerations
QQuickWidget is an alternative to using QQuickView and QWidget::createWindowContainer().
The restrictions on stacking order do not apply, making QQuickWidget the more flexible
alternative, behaving more like an ordinary widget.
However, the above mentioned advantages come at the expense of performance:
\list
\li Unlike QQuickWindow and QQuickView, QQuickWidget involves at least one
additional render pass targeting an offscreen color buffer, typically a 2D
texture, followed by drawing a texture quad. This means increased load
especially for the fragment processing of the GPU.
\li Using QQuickWidget disables the \l{threaded_render_loop}{threaded render loop} on all
platforms. This means that some of the benefits of threaded rendering, for example
\l Animator classes and vsync driven animations, will not be available.
\endlist
\note Avoid calling winId() on a QQuickWidget. This function triggers the creation of
a native window, resulting in reduced performance and possibly rendering glitches. The
entire purpose of QQuickWidget is to render Quick scenes without a separate native
window, hence making it a native widget should always be avoided.
\section1 Graphics API Support
QQuickWidget is functional with all the 3D graphics APIs supported by Qt
Quick, as well as the \c software backend. Other backends, for example
OpenVG, are not compatible however and attempting to construct a
QQuickWidget will lead to problems.
Overriding the platform's default graphics API is done the same way as with
QQuickWindow and QQuickView: either by calling
QQuickWindow::setGraphicsApi() early on before constructing the first
QQuickWidget, or by setting the \c{QSG_RHI_BACKEND} environment variable.
\note One top-level window can only use one single graphics API for
rendering. For example, attempting to place a QQuickWidget using Vulkan and
a QOpenGLWidget in the widget hierarchy of the same top-level window,
problems will occur and one of the widgets will not be rendering as
expected.
\section1 Scene Graph and Context Persistency
QQuickWidget honors QQuickWindow::isPersistentSceneGraph(), meaning that
applications can decide - by calling
QQuickWindow::setPersistentSceneGraph() on the window returned from the
quickWindow() function - to let scenegraph nodes and other Qt Quick scene
related resources be released whenever the widget becomes hidden. By default
persistency is enabled, just like with QQuickWindow.
When running with the OpenGL, QQuickWindow offers the possibility to
disable persistent OpenGL contexts as well. This setting is currently
ignored by QQuickWidget and the context is always persistent. The OpenGL
context is thus not destroyed when hiding the widget. The context is
destroyed only when the widget is destroyed or when the widget gets
reparented into another top-level widget's child hierarchy. However, some
applications, in particular those that have their own graphics resources
due to performing custom OpenGL rendering in the Qt Quick scene, may wish
to disable the latter since they may not be prepared to handle the loss of
the context when moving a QQuickWidget into another window. Such
applications can set the QCoreApplication::AA_ShareOpenGLContexts
attribute. For a discussion on the details of resource initialization and
cleanup, refer to the QOpenGLWidget documentation.
\note QQuickWidget offers less fine-grained control over its internal
OpenGL context than QOpenGLWidget, and there are subtle differences, most
notably that disabling the persistent scene graph will lead to destroying
the context on a window change regardless of the presence of
QCoreApplication::AA_ShareOpenGLContexts.
\section1 Limitations
Putting other widgets underneath and making the QQuickWidget transparent will not lead
to the expected results: the widgets underneath will not be visible. This is because
in practice the QQuickWidget is drawn before all other regular, non-OpenGL widgets,
and so see-through types of solutions are not feasible. Other type of layouts, like
having widgets on top of the QQuickWidget, will function as expected.
When absolutely necessary, this limitation can be overcome by setting the
Qt::WA_AlwaysStackOnTop attribute on the QQuickWidget. Be aware, however that this
breaks stacking order. For example it will not be possible to have other widgets on
top of the QQuickWidget, so it should only be used in situations where a
semi-transparent QQuickWidget with other widgets visible underneath is required.
This limitation only applies when there are other widgets underneath the QQuickWidget
inside the same window. Making the window semi-transparent, with other applications
and the desktop visible in the background, is done in the traditional way: Set
Qt::WA_TranslucentBackground on the top-level window, request an alpha channel, and
change the Qt Quick Scenegraph's clear color to Qt::transparent via setClearColor().
\section1 Tab Key Handling
On press of the \c[TAB] key, the item inside the QQuickWidget gets focus. If
this item can handle \c[TAB] key press, focus will change accordingly within
the item, otherwise the next widget in the focus chain gets focus.
\sa {Exposing Attributes of C++ Types to QML}, {Qt Quick Widgets Example}, QQuickView
*/
/*!
\fn void QQuickWidget::statusChanged(QQuickWidget::Status status)
This signal is emitted when the component's current \a status changes.
*/
/*!
Constructs a QQuickWidget with the given \a parent.
The default value of \a parent is 0.
*/
QQuickWidget::QQuickWidget(QWidget *parent)
: QWidget(*(new QQuickWidgetPrivate), parent, {})
{
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
setAttribute(Qt::WA_AcceptTouchEvents);
d_func()->init();
}
/*!
Constructs a QQuickWidget with the given QML \a source and \a parent.
The default value of \a parent is 0.
*/
QQuickWidget::QQuickWidget(const QUrl &source, QWidget *parent)
: QQuickWidget(parent)
{
setSource(source);
}
/*!
Constructs a QQuickWidget with the given QML \a engine and \a parent.
Note: In this case, the QQuickWidget does not own the given \a engine object;
it is the caller's responsibility to destroy the engine. If the \a engine is deleted
before the view, status() will return QQuickWidget::Error.
\sa Status, status(), errors()
*/
QQuickWidget::QQuickWidget(QQmlEngine* engine, QWidget *parent)
: QWidget(*(new QQuickWidgetPrivate), parent, {})
{
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
d_func()->init(engine);
}
/*!
Destroys the QQuickWidget.
*/
QQuickWidget::~QQuickWidget()
{
// Ensure that the component is destroyed before the engine; the engine may
// be a child of the QQuickWidgetPrivate, and will be destroyed by its dtor
Q_D(QQuickWidget);
delete d->root;
d->root = nullptr;
// NB! resetting graphics resources must be done from this destructor,
// *not* from the private class' destructor. This is due to how destruction
// works and due to the QWidget dtor (for toplevels) destroying the repaint
// manager and rhi before the (QObject) private gets destroyed. Hence must
// do it here early on.
d->destroy();
}
/*!
\property QQuickWidget::source
\brief The URL of the source of the QML component.
Ensure that the URL provided is full and correct, in particular, use
\l QUrl::fromLocalFile() when loading a file from the local filesystem.
\note Setting a source URL will result in the QML component being
instantiated, even if the URL is unchanged from the current value.
*/
/*!
Sets the source to the \a url, loads the QML component and instantiates it.
Ensure that the URL provided is full and correct, in particular, use
\l QUrl::fromLocalFile() when loading a file from the local filesystem.
Calling this method multiple times with the same URL will result
in the QML component being reinstantiated.
*/
void QQuickWidget::setSource(const QUrl& url)
{
Q_D(QQuickWidget);
d->source = url;
d->execute();
}
/*!
\internal
Sets the source \a url, \a component and content \a item (root of the QML object hierarchy) directly.
*/
void QQuickWidget::setContent(const QUrl& url, QQmlComponent *component, QObject* item)
{
Q_D(QQuickWidget);
d->source = url;
d->component = component;
if (d->component && d->component->isError()) {
const QList<QQmlError> errorList = d->component->errors();
for (const QQmlError &error : errorList) {
QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), nullptr).warning()
<< error;
}
emit statusChanged(status());
return;
}
d->setRootObject(item);
emit statusChanged(status());
}
/*!
Returns the source URL, if set.
\sa setSource()
*/
QUrl QQuickWidget::source() const
{
Q_D(const QQuickWidget);
return d->source;
}
/*!
Returns a pointer to the QQmlEngine used for instantiating
QML Components.
*/
QQmlEngine* QQuickWidget::engine() const
{
Q_D(const QQuickWidget);
d->ensureEngine();
return const_cast<QQmlEngine *>(d->engine.data());
}
/*!
This function returns the root of the context hierarchy. Each QML
component is instantiated in a QQmlContext. QQmlContext's are
essential for passing data to QML components. In QML, contexts are
arranged hierarchically and this hierarchy is managed by the
QQmlEngine.
*/
QQmlContext* QQuickWidget::rootContext() const
{
Q_D(const QQuickWidget);
d->ensureEngine();
return d->engine.data()->rootContext();
}
/*!
\enum QQuickWidget::Status
Specifies the loading status of the QQuickWidget.
\value Null This QQuickWidget has no source set.
\value Ready This QQuickWidget has loaded and created the QML component.
\value Loading This QQuickWidget is loading network data.
\value Error One or more errors occurred. Call errors() to retrieve a list
of errors.
*/
/*! \enum QQuickWidget::ResizeMode
This enum specifies how to resize the view.
\value SizeViewToRootObject The view resizes with the root item in the QML.
\value SizeRootObjectToView The view will automatically resize the root item to the size of the view.
*/
/*!
\fn void QQuickWidget::sceneGraphError(QQuickWindow::SceneGraphError error, const QString &message)
This signal is emitted when an \a error occurred during scene graph initialization.
Applications should connect to this signal if they wish to handle errors,
like OpenGL context creation failures, in a custom way. When no slot is
connected to the signal, the behavior will be different: Quick will print
the \a message, or show a message box, and terminate the application.
This signal will be emitted from the GUI thread.
\sa QQuickWindow::sceneGraphError()
*/
/*!
\property QQuickWidget::status
The component's current \l{QQuickWidget::Status} {status}.
*/
QQuickWidget::Status QQuickWidget::status() const
{
Q_D(const QQuickWidget);
if (!d->engine && !d->source.isEmpty())
return QQuickWidget::Error;
if (!d->component)
return QQuickWidget::Null;
if (d->component->status() == QQmlComponent::Ready && !d->root)
return QQuickWidget::Error;
return QQuickWidget::Status(d->component->status());
}
/*!
Return the list of errors that occurred during the last compile or create
operation. When the status is not \l Error, an empty list is returned.
\sa status
*/
QList<QQmlError> QQuickWidget::errors() const
{
Q_D(const QQuickWidget);
QList<QQmlError> errs;
if (d->component)
errs = d->component->errors();
if (!d->engine && !d->source.isEmpty()) {
QQmlError error;
error.setDescription(QLatin1String("QQuickWidget: invalid qml engine."));
errs << error;
}
if (d->component && d->component->status() == QQmlComponent::Ready && !d->root) {
QQmlError error;
error.setDescription(QLatin1String("QQuickWidget: invalid root object."));
errs << error;
}
return errs;
}
/*!
\property QQuickWidget::resizeMode
\brief Determines whether the view should resize the window contents.
If this property is set to SizeViewToRootObject (the default), the view
resizes to the size of the root item in the QML.
If this property is set to SizeRootObjectToView, the view will
automatically resize the root item to the size of the view.
Regardless of this property, the sizeHint of the view
is the initial size of the root item. Note though that
since QML may load dynamically, that size may change.
\sa initialSize()
*/
void QQuickWidget::setResizeMode(ResizeMode mode)
{
Q_D(QQuickWidget);
if (d->resizeMode == mode)
return;
if (d->root) {
if (d->resizeMode == SizeViewToRootObject) {
QQuickItemPrivate *p = QQuickItemPrivate::get(d->root);
p->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
}
}
d->resizeMode = mode;
if (d->root) {
d->initResize();
}
}
void QQuickWidgetPrivate::initResize()
{
if (root) {
if (resizeMode == QQuickWidget::SizeViewToRootObject) {
QQuickItemPrivate *p = QQuickItemPrivate::get(root);
p->addItemChangeListener(this, QQuickItemPrivate::Geometry);
}
}
updateSize();
}
void QQuickWidgetPrivate::updateSize()
{
Q_Q(QQuickWidget);
if (!root)
return;
if (resizeMode == QQuickWidget::SizeViewToRootObject) {
QSize newSize = QSize(root->width(), root->height());
if (newSize.isValid()) {
if (newSize != q->size()) {
q->resize(newSize);
q->updateGeometry();
} else if (offscreenWindow->size().isEmpty()) {
// QQuickDeliveryAgentPrivate::deliverHoverEvent() ignores events that
// occur outside of QQuickRootItem's geometry, so we need it to match root's size.
offscreenWindow->contentItem()->setSize(newSize);
}
}
} else if (resizeMode == QQuickWidget::SizeRootObjectToView) {
const bool needToUpdateWidth = !qFuzzyCompare(q->width(), root->width());
const bool needToUpdateHeight = !qFuzzyCompare(q->height(), root->height());
if (needToUpdateWidth && needToUpdateHeight) {
// Make sure that we have realistic sizing behavior by following
// what on-screen windows would do and resize everything, not just
// the root item. We do this because other types may be relying on
// us to behave correctly.
const QSizeF newSize(q->width(), q->height());
offscreenWindow->resize(newSize.toSize());
offscreenWindow->contentItem()->setSize(newSize);
root->setSize(newSize);
} else if (needToUpdateWidth) {
const int newWidth = q->width();
offscreenWindow->setWidth(newWidth);
offscreenWindow->contentItem()->setWidth(newWidth);
root->setWidth(newWidth);
} else if (needToUpdateHeight) {
const int newHeight = q->height();
offscreenWindow->setHeight(newHeight);
offscreenWindow->contentItem()->setHeight(newHeight);
root->setHeight(newHeight);
}
}
}
/*!
\internal
Update the position of the offscreen window, so it matches the position of the QQuickWidget.
*/
void QQuickWidgetPrivate::updatePosition()
{
Q_Q(QQuickWidget);
if (offscreenWindow == nullptr)
return;
const QPoint &pos = q->mapToGlobal(QPoint(0, 0));
if (offscreenWindow->position() != pos)
offscreenWindow->setPosition(pos);
}
QSize QQuickWidgetPrivate::rootObjectSize() const
{
QSize rootObjectSize(0,0);
int widthCandidate = -1;
int heightCandidate = -1;
if (root) {
widthCandidate = root->width();
heightCandidate = root->height();
}
if (widthCandidate > 0) {
rootObjectSize.setWidth(widthCandidate);
}
if (heightCandidate > 0) {
rootObjectSize.setHeight(heightCandidate);
}
return rootObjectSize;
}
void QQuickWidgetPrivate::handleContextCreationFailure(const QSurfaceFormat &)
{
Q_Q(QQuickWidget);
QString translatedMessage;
QString untranslatedMessage;
QQuickWindowPrivate::rhiCreationFailureMessage(QLatin1String("QRhi"), &translatedMessage, &untranslatedMessage);
static const QMetaMethod errorSignal = QMetaMethod::fromSignal(&QQuickWidget::sceneGraphError);
const bool signalConnected = q->isSignalConnected(errorSignal);
if (signalConnected)
emit q->sceneGraphError(QQuickWindow::ContextNotAvailable, translatedMessage);
#if defined(Q_OS_WIN) && QT_CONFIG(messagebox)
if (!signalConnected && !QLibraryInfo::isDebugBuild() && !GetConsoleWindow())
QMessageBox::critical(q, QCoreApplication::applicationName(), translatedMessage);
#endif // Q_OS_WIN
if (!signalConnected)
qFatal("%s", qPrintable(untranslatedMessage));
}
static inline QPlatformBackingStoreRhiConfig::Api graphicsApiToBackingStoreRhiApi(QSGRendererInterface::GraphicsApi api)
{
switch (api) {
case QSGRendererInterface::OpenGL:
return QPlatformBackingStoreRhiConfig::OpenGL;
case QSGRendererInterface::Vulkan:
return QPlatformBackingStoreRhiConfig::Vulkan;
case QSGRendererInterface::Direct3D11:
return QPlatformBackingStoreRhiConfig::D3D11;
case QSGRendererInterface::Direct3D12:
return QPlatformBackingStoreRhiConfig::D3D12;
case QSGRendererInterface::Metal:
return QPlatformBackingStoreRhiConfig::Metal;
default:
return QPlatformBackingStoreRhiConfig::Null;
}
}