Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquickwidget.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qquickwidget.h"
7#include <QtWidgets/private/qwidgetrepaintmanager_p.h>
8
9#include "private/qquickwindow_p.h"
10#include "private/qquickitem_p.h"
11#include "private/qquickitemchangelistener_p.h"
12#include "private/qquickrendercontrol_p.h"
13#include "private/qsgrhisupport_p.h"
14
15#include "private/qsgsoftwarerenderer_p.h"
16
17#include <private/qqmldebugconnector_p.h>
18#include <private/qquickprofiler_p.h>
19#include <private/qqmldebugserviceinterfaces_p.h>
20
21#include <QtQml/qqmlengine.h>
22#include <QtQml/qqmlcomponent.h>
23#include <private/qqmlengine_p.h>
24#include <QtCore/qbasictimer.h>
25#include <QtGui/QOffscreenSurface>
26#include <QtGui/private/qguiapplication_p.h>
27#include <QtGui/qpa/qplatformintegration.h>
28
29#include <QtGui/QPainter>
30
31#include <QtQuick/QSGRendererInterface>
32
33#ifdef Q_OS_WIN
34#if QT_CONFIG(messagebox)
35# include <QtWidgets/QMessageBox>
36#endif
37# include <QtCore/QLibraryInfo>
38# include <QtCore/qt_windows.h>
39#endif
40
41#include <QtQuick/qquickgraphicsdevice.h>
42#include <QtQuick/qquickrendertarget.h>
43
44#include "private/qwidget_p.h"
45
46#if QT_CONFIG(graphicsview)
47#include <QtWidgets/qgraphicsscene.h>
48#include <QtWidgets/qgraphicsview.h>
49#endif
50
51#if QT_CONFIG(vulkan)
52#include <QtGui/private/qvulkandefaultinstance_p.h>
53#endif
54
55QT_BEGIN_NAMESPACE
56
57QQuickWidgetOffscreenWindow::QQuickWidgetOffscreenWindow(QQuickWindowPrivate &dd, QQuickRenderControl *control)
58:QQuickWindow(dd, control)
59{
60 setTitle(QString::fromLatin1("Offscreen"));
61 setObjectName(QString::fromLatin1("QQuickWidgetOffscreenWindow"));
62}
63
65{
66public:
67 // override setVisible to prevent accidental offscreen window being created
68 // by base class.
69 void setVisible(bool visible) override
70 {
71 Q_Q(QWindow);
72 // this stays always invisible
73 visibility = visible ? QWindow::Windowed : QWindow::Hidden;
74 q->visibilityChanged(visibility); // workaround for QTBUG-49054
75 }
76};
77
78/*
79 Returns the widget that \a widget's content is composited into.
80
81 The widget layer flushes a widget's content to the backing store of the
82 closest ancestor that has a window, keyed by that ancestor's own window,
83 so that is the widget whose window the content ends up in. It is the top
84 level unless some widget in between has Qt::WA_NativeWindow set.
85
86 See QWidgetRepaintManager::markNeedsFlush().
87*/
88static QWidget *compositingWidgetFor(QWidget *widget)
89{
90 if (widget->windowHandle())
91 return widget;
92 if (QWidget *nativeParent = widget->nativeParentWidget())
93 return nativeParent;
94 return widget->window();
95}
96
98
107
109{
110public:
111 Q_DECLARE_PUBLIC(QQuickWidgetRenderControl)
112 QQuickWidgetRenderControlPrivate(QQuickWidgetRenderControl *renderControl, QQuickWidget *qqw)
113 : QQuickRenderControlPrivate(renderControl)
114 , m_quickWidget(qqw)
115 {
116 }
117
118 bool isRenderWindow(const QWindow *w) override
119 {
120#if QT_CONFIG(graphicsview)
121 QWidgetPrivate *widgetd = QWidgetPrivate::get(m_quickWidget);
122 auto *proxy = (widgetd && widgetd->extra) ? widgetd->extra->proxyWidget : nullptr;
123 auto *scene = proxy ? proxy->scene() : nullptr;
124 if (scene) {
125 for (const auto &view : scene->views()) {
126 if (compositingWidgetFor(view)->windowHandle() == w)
127 return true;
128 }
129 }
130#endif
131 return QQuickRenderControlPrivate::isRenderWindow(w);
132 }
134};
135
136#if QT_CONFIG(accessibility)
137QAccessibleInterface *QQuickWidgetOffscreenWindow::accessibleRoot() const
138{
139 Q_D(const QQuickWidgetOffscreenWindow);
140 if (d->renderControl) {
141 auto *priv = static_cast<QQuickWidgetRenderControlPrivate *>(
142 QQuickRenderControlPrivate::get(d->renderControl)
143 );
144 return QAccessible::queryAccessibleInterface(priv->m_quickWidget);
145 }
146 return nullptr;
147}
148#endif // QT_CONFIG(accessibility)
149
150QQuickWidgetRenderControl::QQuickWidgetRenderControl(QQuickWidget *quickWidget)
151 : QQuickRenderControl(*(new QQuickWidgetRenderControlPrivate(this, quickWidget)), nullptr)
152{
153}
154
156{
157 Q_D(QQuickWidgetRenderControl);
158
159 QQuickWidget *quickWidget = d->m_quickWidget;
160
161#if QT_CONFIG(graphicsview)
162 QWidgetPrivate *widgetd = QWidgetPrivate::get(quickWidget);
163 if (widgetd->extra) {
164 if (auto proxy = widgetd->extra->proxyWidget) {
165 auto scene = proxy->scene();
166 if (scene) {
167 const auto views = scene->views();
168 if (!views.isEmpty()) {
169 // Get the first QGV containing the proxy. Not ideal, but the callers
170 // of this function aren't prepared to handle more than one render window.
171 auto candidateView = views.first();
172 return compositingWidgetFor(candidateView)->windowHandle();
173 }
174 }
175 }
176 }
177#endif
178
179 QWidget *renderWidget = compositingWidgetFor(quickWidget);
180 if (offset)
181 *offset = quickWidget->mapTo(renderWidget, QPoint());
182
183 return renderWidget->windowHandle();
184}
185
187{
188 Q_Q(QQuickWidget);
189
191 offscreenWindow->setScreen(q->screen());
192 // Do not call create() on offscreenWindow.
193
194 QWidget::connect(offscreenWindow, SIGNAL(sceneGraphInitialized()), q, SLOT(createFramebufferObject()));
195 QWidget::connect(offscreenWindow, SIGNAL(sceneGraphInvalidated()), q, SLOT(destroyFramebufferObject()));
196 QWidget::connect(offscreenWindow, &QQuickWindow::focusObjectChanged, q, &QQuickWidget::propagateFocusObjectChanged);
197
198#if QT_CONFIG(accessibility)
199 QAccessible::installFactory(&qAccessibleQuickWidgetFactory);
200#endif
201}
202
204{
205 // This should initialize, if not already done, the absolute minimum set of
206 // mandatory backing resources, meaning the QQuickWindow and its
207 // QQuickRenderControl. This function may be called very early on upon
208 // construction, including before init() even.
209
210 Q_Q(QQuickWidget);
211 if (!renderControl)
212 renderControl = new QQuickWidgetRenderControl(q);
213 if (!offscreenWindow)
214 offscreenWindow = new QQuickWidgetOffscreenWindow(*new QQuickWidgetOffscreenWindowPrivate(), renderControl);
215
216 // Check if the Software Adaptation is being used
217 auto sgRendererInterface = offscreenWindow->rendererInterface();
218 if (sgRendererInterface && sgRendererInterface->graphicsApi() == QSGRendererInterface::Software)
219 useSoftwareRenderer = true;
220}
221
222void QQuickWidgetPrivate::init(QQmlEngine* e)
223{
224 Q_Q(QQuickWidget);
225
227
228 if (!useSoftwareRenderer) {
229 if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RhiBasedRendering))
230 setRenderToTexture();
231 else
232 qWarning("QQuickWidget is not supported on this platform.");
233 }
234
235 engine = e;
236
237 if (!engine.isNull() && !engine.data()->incubationController())
238 engine.data()->setIncubationController(offscreenWindow->incubationController());
239
240 q->setMouseTracking(true);
241 q->setFocusPolicy(Qt::StrongFocus);
242#ifndef Q_OS_MACOS
243 /*
244 Usually, a QTouchEvent comes from a touchscreen, and we want those
245 touch events in Qt Quick. But on macOS, there are no touchscreens, and
246 WA_AcceptTouchEvents has a different meaning: QApplication::notify()
247 calls the native-integration function registertouchwindow() to change
248 NSView::allowedTouchTypes to include NSTouchTypeMaskIndirect when the
249 trackpad cursor enters the window, and removes that mask when the
250 cursor exits. In other words, WA_AcceptTouchEvents enables getting
251 discrete touchpoints from the trackpad. We rather prefer to get mouse,
252 wheel and native gesture events from the trackpad (because those
253 provide more of a "native feel"). The only exception is for
254 MultiPointTouchArea, and it takes care of that for itself. So don't
255 automatically set WA_AcceptTouchEvents on macOS. The user can still do
256 it, but we don't recommend it.
257 */
258 q->setAttribute(Qt::WA_AcceptTouchEvents);
259#endif
260
261#if QT_CONFIG(quick_draganddrop)
262 q->setAcceptDrops(true);
263#endif
264
265 QObject::connect(renderControl, SIGNAL(renderRequested()), q, SLOT(triggerUpdate()));
266 QObject::connect(renderControl, SIGNAL(sceneChanged()), q, SLOT(triggerUpdate()));
267}
268
270{
271 Q_Q(const QQuickWidget);
272 if (!engine.isNull())
273 return;
274
275 engine = new QQmlEngine(const_cast<QQuickWidget*>(q));
276 engine.data()->setIncubationController(offscreenWindow->incubationController());
277}
278
280{
281 if (!useSoftwareRenderer && rhi) {
282 // For the user's own OpenGL code connected to some QQuickWindow signals.
283 rhi->makeThreadLocalNativeContextCurrent();
284 }
285
286 renderControl->invalidate();
287}
288
290{
291 Q_Q(QQuickWidget);
292 if (rhi)
293 rhi->removeCleanupCallback(q);
294
296 deviceLost = true;
297 rhi = nullptr;
298}
299
301{
302 Q_Q(QQuickWidget);
303
304 if (offscreenWindow->isPersistentSceneGraph()
305 && qGuiApp->testAttribute(Qt::AA_ShareOpenGLContexts)
306 && rhiConfig().api() == QPlatformBackingStoreRhiConfig::OpenGL)
307 {
308 return;
309 }
310
311 // In case of !isPersistentSceneGraph or when we need a new context due to
312 // the need to share resources with the new window's context, we must both
313 // invalidate the scenegraph and destroy the context. QQuickRenderControl
314 // must be recreated because its RHI will contain a dangling pointer to
315 // the context.
316
317 QScopedPointer<QQuickWindow> oldOffScreenWindow(offscreenWindow); // Do not delete before reparenting sgItem
318 offscreenWindow = nullptr;
319 delete renderControl;
320
321 renderControl = new QQuickWidgetRenderControl(q);
323
324 if (oldOffScreenWindow)
325 offscreenWindow->setColor(oldOffScreenWindow->color());
326
327 QObject::connect(renderControl, SIGNAL(renderRequested()), q, SLOT(triggerUpdate()));
328 QObject::connect(renderControl, SIGNAL(sceneChanged()), q, SLOT(triggerUpdate()));
329
330 if (QQuickItem *sgItem = qobject_cast<QQuickItem *>(root))
331 sgItem->setParentItem(offscreenWindow->contentItem());
332}
333
334QQuickWidgetPrivate::QQuickWidgetPrivate()
335 : root(nullptr)
336 , component(nullptr)
337 , offscreenWindow(nullptr)
338 , renderControl(nullptr)
339 , rhi(nullptr)
340 , outputTexture(nullptr)
341 , depthStencil(nullptr)
342 , msaaBuffer(nullptr)
343 , rt(nullptr)
344 , rtRp(nullptr)
345 , resizeMode(QQuickWidget::SizeViewToRootObject)
346 , initialSize(0,0)
347 , eventPending(false)
348 , updatePending(false)
349 , fakeHidden(false)
351 , useSoftwareRenderer(false)
352 , forceFullUpdate(false)
353 , deviceLost(false)
354{
355}
356
358{
360
361 if (root) {
362 delete root;
363 root = nullptr;
364 }
365 if (component) {
366 delete component;
367 component = nullptr;
368 }
369}
370
372{
373 Q_Q(QQuickWidget);
375 q->destroyFramebufferObject();
376 delete offscreenWindow;
377 delete renderControl;
378 offscreenRenderer.reset();
379}
380
382{
383 Q_Q(QQuickWidget);
385
386 if (!source.isEmpty()) {
387 component = new QQmlComponent(engine.data(), source, q);
388 if (!component->isLoading()) {
389 q->continueExecute();
390 } else {
391 QObject::connect(component, SIGNAL(statusChanged(QQmlComponent::Status)),
392 q, SLOT(continueExecute()));
393 }
394 }
395}
396
397void QQuickWidgetPrivate::execute(QAnyStringView uri, QAnyStringView typeName)
398{
399 Q_Q(QQuickWidget);
401
402 component = new QQmlComponent(engine.data(), uri, typeName, q);
403 if (!component->isLoading()) {
404 q->continueExecute();
405 } else {
406 QObject::connect(component, SIGNAL(statusChanged(QQmlComponent::Status)),
407 q, SLOT(continueExecute()));
408 }
409}
410
411void QQuickWidgetPrivate::itemGeometryChanged(QQuickItem *resizeItem, QQuickGeometryChange change,
412 const QRectF &oldGeometry)
413{
414 Q_Q(QQuickWidget);
415 if (resizeItem == root && resizeMode == QQuickWidget::SizeViewToRootObject) {
416 // wait for both width and height to be changed
417 resizetimer.start(0,q);
418 }
419 QQuickItemChangeListener::itemGeometryChanged(resizeItem, change, oldGeometry);
420}
421
422void QQuickWidgetPrivate::render(bool needsSync)
423{
424 Q_Q(QQuickWidget);
425 if (!useSoftwareRenderer) {
426 if (deviceLost) {
427 deviceLost = false;
429 q->createFramebufferObject();
430 }
431
432 if (!rhi) {
433 qWarning("QQuickWidget: Attempted to render scene with no rhi");
434 return;
435 }
436
437 // createFramebufferObject() bails out when the size is empty. In this case
438 // we cannot render either.
439 if (!outputTexture)
440 return;
441
442 renderControl->beginFrame();
443 QQuickRenderControlPrivate::FrameStatus frameStatus = QQuickRenderControlPrivate::get(renderControl)->frameStatus;
444 if (frameStatus == QQuickRenderControlPrivate::DeviceLostInBeginFrame) {
445 // graphics resources controlled by us must be released
447 // skip this round and hope that the tlw's repaint manager will manage to reinitialize
448 deviceLost = true;
449 return;
450 }
451 if (frameStatus != QQuickRenderControlPrivate::RecordingFrame) {
452 qWarning("QQuickWidget: Failed to begin recording a frame");
453 return;
454 }
455
456 if (needsSync) {
457 renderControl->polishItems();
458 renderControl->sync();
459 }
460
461 renderControl->render();
462
463 renderControl->endFrame();
464 } else {
465 //Software Renderer
466 if (needsSync) {
467 renderControl->polishItems();
468 renderControl->sync();
469 }
470 if (!offscreenWindow)
471 return;
472 QQuickWindowPrivate *cd = QQuickWindowPrivate::get(offscreenWindow);
473 auto softwareRenderer = static_cast<QSGSoftwareRenderer*>(cd->renderer);
474 if (softwareRenderer && !softwareImage.isNull()) {
475 softwareRenderer->setCurrentPaintDevice(&softwareImage);
476 if (forceFullUpdate) {
477 softwareRenderer->markDirty();
478 forceFullUpdate = false;
479 }
480 renderControl->render();
481
482 updateRegion += softwareRenderer->flushRegion();
483 }
484 }
485}
486
488{
489 Q_Q(QQuickWidget);
490 updatePending = false;
491
492 if (!q->isVisible() || fakeHidden)
493 return;
494
495 render(true);
496
497#if QT_CONFIG(graphicsview)
498 if (q->window()->graphicsProxyWidget())
499 QWidgetPrivate::nearestGraphicsProxyWidget(q)->update();
500 else
501#endif
502 {
503 if (!useSoftwareRenderer)
504 q->update(); // schedule composition
505 else if (!updateRegion.isEmpty())
506 q->update(updateRegion);
507 }
508}
509
511{
512 if (!useSoftwareRenderer && !rhi)
513 return QImage();
514
515 // grabWindow() does not work for the rhi case, we are in control of the
516 // render target, and so it is up to us to read it back. When the software
517 // renderer is in use, just call grabWindow().
518
519 if (outputTexture) {
520 render(true);
521 QRhiCommandBuffer *cb = nullptr;
522 rhi->beginOffscreenFrame(&cb);
523 QRhiResourceUpdateBatch *resUpd = rhi->nextResourceUpdateBatch();
524 QRhiReadbackResult readResult;
525 resUpd->readBackTexture(QRhiReadbackDescription(outputTexture), &readResult);
526 cb->resourceUpdate(resUpd);
527 rhi->endOffscreenFrame();
528 if (!readResult.data.isEmpty()) {
529 QImage wrapperImage(reinterpret_cast<const uchar *>(readResult.data.constData()),
530 readResult.pixelSize.width(), readResult.pixelSize.height(),
531 QImage::Format_RGBA8888_Premultiplied);
532 if (rhi->isYUpInFramebuffer())
533 return wrapperImage.flipped();
534 else
535 return wrapperImage.copy();
536 }
537 return QImage();
538 }
539
540 return offscreenWindow->grabWindow();
541}
542
543// Intentionally not overriding the QQuickWindow's focusObject.
544// Key events should go to our key event handlers, and then to the
545// QQuickWindow, not any in-scene item.
546
547/*!
548 \module QtQuickWidgets
549 \title Qt Quick Widgets C++ Classes
550 \ingroup modules
551 \brief The C++ API provided by the Qt Quick Widgets module.
552 \qtcmakepackage QuickWidgets
553 \qtvariable quickwidgets
554
555 To link against the module, add this line to your \l qmake
556 \c .pro file:
557
558 \code
559 QT += quickwidgets
560 \endcode
561
562 For more information, see the QQuickWidget class documentation.
563*/
564
565/*!
566 \class QQuickWidget
567 \since 5.3
568 \brief The QQuickWidget class provides a widget for displaying a Qt Quick user interface.
569
570 \inmodule QtQuickWidgets
571
572 This is a convenience wrapper for QQuickWindow which will automatically load and display a QML
573 scene when given the URL of the main source file. Alternatively, you can instantiate your own
574 objects using QQmlComponent and place them in a manually set up QQuickWidget.
575
576 Typical usage:
577
578 \code
579 QQuickWidget *view = new QQuickWidget;
580 view->setSource(QUrl::fromLocalFile("myqmlfile.qml"));
581 view->show();
582 \endcode
583
584 To receive errors related to loading and executing QML with QQuickWidget,
585 you can connect to the statusChanged() signal and monitor for QQuickWidget::Error.
586 The errors are available via QQuickWidget::errors().
587
588 QQuickWidget also manages sizing of the view and root object. By default,
589 the \l resizeMode is \l SizeViewToRootObject, which resizes
590 the view to the size of the root object. Alternatively, you can set the
591 \l resizeMode to \l SizeRootObjectToView, which resizes the
592 root object to the size of the view.
593
594 \section1 Performance Considerations
595
596 QQuickWidget is an alternative to using QQuickView and QWidget::createWindowContainer().
597 The restrictions on stacking order do not apply, making QQuickWidget the more flexible
598 alternative, behaving more like an ordinary widget.
599
600 However, the above mentioned advantages come at the expense of performance:
601 \list
602
603 \li Unlike QQuickWindow and QQuickView, QQuickWidget involves at least one
604 additional render pass targeting an offscreen color buffer, typically a 2D
605 texture, followed by drawing a texture quad. This means increased load
606 especially for the fragment processing of the GPU.
607
608 \li Using QQuickWidget disables the \l{threaded_render_loop}{threaded render loop} on all
609 platforms. This means that some of the benefits of threaded rendering, for example
610 \l Animator classes and vsync driven animations, will not be available.
611 \endlist
612
613 \note Avoid calling winId() on a QQuickWidget. This function triggers the creation of
614 a native window, resulting in reduced performance and possibly rendering glitches. The
615 entire purpose of QQuickWidget is to render Quick scenes without a separate native
616 window, hence making it a native widget should always be avoided.
617
618 \section1 Graphics API Support
619
620 QQuickWidget is functional with all the 3D graphics APIs supported by Qt
621 Quick, as well as the \c software backend. Other backends, for example
622 OpenVG, are not compatible however and attempting to construct a
623 QQuickWidget will lead to problems.
624
625 Overriding the platform's default graphics API is done the same way as with
626 QQuickWindow and QQuickView: either by calling
627 QQuickWindow::setGraphicsApi() early on before constructing the first
628 QQuickWidget, or by setting the \c{QSG_RHI_BACKEND} environment variable.
629
630 \note One top-level window can only use one single graphics API for
631 rendering. For example, attempting to place a QQuickWidget using Vulkan and
632 a QOpenGLWidget in the widget hierarchy of the same top-level window,
633 problems will occur and one of the widgets will not be rendering as
634 expected.
635
636 \section1 Scene Graph and Context Persistency
637
638 QQuickWidget honors QQuickWindow::isPersistentSceneGraph(), meaning that
639 applications can decide - by calling
640 QQuickWindow::setPersistentSceneGraph() on the window returned from the
641 quickWindow() function - to let scenegraph nodes and other Qt Quick scene
642 related resources be released whenever the widget becomes hidden. By default
643 persistency is enabled, just like with QQuickWindow.
644
645 When running with the OpenGL, QQuickWindow offers the possibility to
646 disable persistent OpenGL contexts as well. This setting is currently
647 ignored by QQuickWidget and the context is always persistent. The OpenGL
648 context is thus not destroyed when hiding the widget. The context is
649 destroyed only when the widget is destroyed or when the widget gets
650 reparented into another top-level widget's child hierarchy. However, some
651 applications, in particular those that have their own graphics resources
652 due to performing custom OpenGL rendering in the Qt Quick scene, may wish
653 to disable the latter since they may not be prepared to handle the loss of
654 the context when moving a QQuickWidget into another window. Such
655 applications can set the QCoreApplication::AA_ShareOpenGLContexts
656 attribute. For a discussion on the details of resource initialization and
657 cleanup, refer to the QOpenGLWidget documentation.
658
659 \note QQuickWidget offers less fine-grained control over its internal
660 OpenGL context than QOpenGLWidget, and there are subtle differences, most
661 notably that disabling the persistent scene graph will lead to destroying
662 the context on a window change regardless of the presence of
663 QCoreApplication::AA_ShareOpenGLContexts.
664
665 \section1 Limitations
666
667 Putting other widgets underneath and making the QQuickWidget transparent will not lead
668 to the expected results: the widgets underneath will not be visible. This is because
669 in practice the QQuickWidget is drawn before all other regular, non-OpenGL widgets,
670 and so see-through types of solutions are not feasible. Other type of layouts, like
671 having widgets on top of the QQuickWidget, will function as expected.
672
673 When absolutely necessary, this limitation can be overcome by setting the
674 Qt::WA_AlwaysStackOnTop attribute on the QQuickWidget. Be aware, however that this
675 breaks stacking order. For example it will not be possible to have other widgets on
676 top of the QQuickWidget, so it should only be used in situations where a
677 semi-transparent QQuickWidget with other widgets visible underneath is required.
678
679 This limitation only applies when there are other widgets underneath the QQuickWidget
680 inside the same window. Making the window semi-transparent, with other applications
681 and the desktop visible in the background, is done in the traditional way: Set
682 Qt::WA_TranslucentBackground on the top-level window, request an alpha channel, and
683 change the Qt Quick Scenegraph's clear color to Qt::transparent via setClearColor().
684
685 \sa {Exposing Attributes of C++ Types to QML}, {Qt Quick Widgets Example}, QQuickView
686*/
687
688
689/*!
690 \fn void QQuickWidget::statusChanged(QQuickWidget::Status status)
691 This signal is emitted when the component's current \a status changes.
692*/
693
694/*!
695 Constructs a QQuickWidget with a default QML engine as a child of \a parent.
696
697 The default value of \a parent is \c nullptr.
698*/
699QQuickWidget::QQuickWidget(QWidget *parent)
700 : QWidget(*(new QQuickWidgetPrivate), parent, {})
701{
702 d_func()->init();
703}
704
705/*!
706 Constructs a QQuickWidget with a default QML engine and the given QML \a source
707 as a child of \a parent.
708
709 The default value of \a parent is \c nullptr.
710 */
711QQuickWidget::QQuickWidget(const QUrl &source, QWidget *parent)
712 : QQuickWidget(parent)
713{
714 setSource(source);
715}
716
717/*!
718 \since 6.9
719 Constructs a QQuickWidget with the element specified by \a uri and \a typeName
720 and parent \a parent.
721 The default value of \a parent is \c{nullptr}.
722 \sa loadFromModule
723 */
724QQuickWidget::QQuickWidget(QAnyStringView uri, QAnyStringView typeName, QWidget *parent)
725 : QQuickWidget(parent)
726{
727 loadFromModule(uri, typeName);
728}
729
730/*!
731 Constructs a QQuickWidget with the given QML \a engine as a child of \a parent.
732
733 \note The QQuickWidget does not take ownership of the given \a engine object;
734 it is the caller's responsibility to destroy the engine. If the \a engine is deleted
735 before the view, \l status() will return \l QQuickWidget::Error.
736*/
737QQuickWidget::QQuickWidget(QQmlEngine* engine, QWidget *parent)
738 : QWidget(*(new QQuickWidgetPrivate), parent, {})
739{
740 d_func()->init(engine);
741}
742
743/*!
744 Destroys the QQuickWidget.
745*/
746QQuickWidget::~QQuickWidget()
747{
748 // Ensure that the component is destroyed before the engine; the engine may
749 // be a child of the QQuickWidgetPrivate, and will be destroyed by its dtor
750 Q_D(QQuickWidget);
751 delete d->root;
752 d->root = nullptr;
753
754 if (d->rhi)
755 d->rhi->removeCleanupCallback(this);
756
757 // NB! resetting graphics resources must be done from this destructor,
758 // *not* from the private class' destructor. This is due to how destruction
759 // works and due to the QWidget dtor (for toplevels) destroying the repaint
760 // manager and rhi before the (QObject) private gets destroyed. Hence must
761 // do it here early on.
762 d->destroy();
763}
764
765/*!
766 \property QQuickWidget::source
767 \brief The URL of the source of the QML component.
768
769 Ensure that the URL provided is full and correct, in particular, use
770 \l QUrl::fromLocalFile() when loading a file from the local filesystem.
771
772 \note Setting a source URL will result in the QML component being
773 instantiated, even if the URL is unchanged from the current value.
774*/
775
776/*!
777 Sets the source to the \a url, loads the QML component and instantiates it.
778
779 Ensure that the URL provided is full and correct, in particular, use
780 \l QUrl::fromLocalFile() when loading a file from the local filesystem.
781
782 Calling this method multiple times with the same URL will result
783 in the QML component being reinstantiated.
784 */
785void QQuickWidget::setSource(const QUrl& url)
786{
787 Q_D(QQuickWidget);
788 d->source = url;
789 d->execute();
790}
791
792/*!
793 \internal
794
795 Sets the source \a url, \a component and content \a item (root of the QML object hierarchy) directly.
796 */
797void QQuickWidget::setContent(const QUrl& url, QQmlComponent *component, QObject* item)
798{
799 Q_D(QQuickWidget);
800 d->source = url;
801 d->component = component;
802
803 if (d->component && d->component->isError()) {
804 const QList<QQmlError> errorList = d->component->errors();
805 for (const QQmlError &error : errorList) {
806 QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), nullptr).warning()
807 << error;
808 }
809 emit statusChanged(status());
810 return;
811 }
812
813 d->setRootObject(item);
814 emit statusChanged(status());
815}
816/*!
817 Sets the initial properties \a initialProperties with which the QML
818 component gets initialized after calling \l QQuickWidget::setSource().
819
820 \note You can only use this function to initialize top-level properties.
821 \note This function should always be called before setSource, as it has
822 no effect once the component has become \c Ready.
823
824 \sa QQmlComponent::createWithInitialProperties()
825 \since 6.9
826*/
827void QQuickWidget::setInitialProperties(const QVariantMap &initialProperties)
828{
829 Q_D(QQuickWidget);
830 d->initialProperties = initialProperties;
831}
832
833/*!
834 \since 6.9
835 Loads the QML component identified by \a uri and \a typeName. If the component
836 is backed by a QML file, \l{source} will be set accordingly. For types defined
837 in \c{C++}, \c{source} will be empty.
838
839 If any \l{source} was set before this method was called, it will be cleared.
840
841 Calling this method multiple times with the same \a uri and \a typeName will result
842 in the QML component being reinstantiated.
843
844 \sa setSource, QQmlComponent::loadFromModule, QQmlApplicationEngine::loadFromModule
845 */
846void QQuickWidget::loadFromModule(QAnyStringView uri, QAnyStringView typeName)
847{
848 Q_D(QQuickWidget);
849 d->source = {}; // clear URL
850 d->execute(uri, typeName);
851}
852
853/*!
854 Returns the source URL, if set.
855
856 \sa setSource()
857 */
858QUrl QQuickWidget::source() const
859{
860 Q_D(const QQuickWidget);
861 return d->source;
862}
863
864/*!
865 Returns a pointer to the QQmlEngine used for instantiating
866 QML Components.
867 */
868QQmlEngine* QQuickWidget::engine() const
869{
870 Q_D(const QQuickWidget);
871 d->ensureEngine();
872 return const_cast<QQmlEngine *>(d->engine.data());
873}
874
875/*!
876 This function returns the root of the context hierarchy. Each QML
877 component is instantiated in a QQmlContext. QQmlContext's are
878 essential for passing data to QML components. In QML, contexts are
879 arranged hierarchically and this hierarchy is managed by the
880 QQmlEngine.
881 */
882QQmlContext* QQuickWidget::rootContext() const
883{
884 Q_D(const QQuickWidget);
885 d->ensureEngine();
886 return d->engine.data()->rootContext();
887}
888
889/*!
890 \enum QQuickWidget::Status
891 Specifies the loading status of the QQuickWidget.
892
893 \value Null This QQuickWidget has no source set.
894 \value Ready This QQuickWidget has loaded and created the QML component.
895 \value Loading This QQuickWidget is loading network data.
896 \value Error One or more errors occurred. Call errors() to retrieve a list
897 of errors.
898*/
899
900/*! \enum QQuickWidget::ResizeMode
901
902 This enum specifies how to resize the view.
903
904 \value SizeViewToRootObject The view resizes with the root item in the QML.
905 \value SizeRootObjectToView The view will automatically resize the root item to the size of the view.
906*/
907
908/*!
909 \fn void QQuickWidget::sceneGraphError(QQuickWindow::SceneGraphError error, const QString &message)
910
911 This signal is emitted when an \a error occurred during scene graph initialization.
912
913 Applications should connect to this signal if they wish to handle errors,
914 like OpenGL context creation failures, in a custom way. When no slot is
915 connected to the signal, the behavior will be different: Quick will print
916 the \a message, or show a message box, and terminate the application.
917
918 This signal will be emitted from the GUI thread.
919
920 \sa QQuickWindow::sceneGraphError()
921 */
922
923/*!
924 \property QQuickWidget::status
925 The component's current \l{QQuickWidget::Status} {status}.
926*/
927
928QQuickWidget::Status QQuickWidget::status() const
929{
930 Q_D(const QQuickWidget);
931 if (!d->engine && !d->source.isEmpty())
932 return QQuickWidget::Error;
933
934 if (!d->component)
935 return QQuickWidget::Null;
936
937 if (d->component->status() == QQmlComponent::Ready && !d->root)
938 return QQuickWidget::Error;
939
940 return QQuickWidget::Status(d->component->status());
941}
942
943/*!
944 Return the list of errors that occurred during the last compile or create
945 operation. When the status is not \l Error, an empty list is returned.
946
947 \sa status
948*/
949QList<QQmlError> QQuickWidget::errors() const
950{
951 Q_D(const QQuickWidget);
952 QList<QQmlError> errs;
953
954 if (d->component)
955 errs = d->component->errors();
956
957 if (!d->engine && !d->source.isEmpty()) {
958 QQmlError error;
959 error.setDescription(QLatin1String("QQuickWidget: invalid qml engine."));
960 errs << error;
961 }
962 if (d->component && d->component->status() == QQmlComponent::Ready && !d->root) {
963 QQmlError error;
964 error.setDescription(QLatin1String("QQuickWidget: invalid root object."));
965 errs << error;
966 }
967
968 return errs;
969}
970
971/*!
972 \property QQuickWidget::resizeMode
973 \brief Determines whether the view should resize the window contents.
974
975 If this property is set to SizeViewToRootObject (the default), the view
976 resizes to the size of the root item in the QML.
977
978 If this property is set to SizeRootObjectToView, the view will
979 automatically resize the root item to the size of the view.
980
981 Regardless of this property, the sizeHint of the view
982 is the initial size of the root item. Note though that
983 since QML may load dynamically, that size may change.
984
985 \sa initialSize()
986*/
987
988void QQuickWidget::setResizeMode(ResizeMode mode)
989{
990 Q_D(QQuickWidget);
991 if (d->resizeMode == mode)
992 return;
993
994 if (d->root) {
995 if (d->resizeMode == SizeViewToRootObject) {
996 QQuickItemPrivate *p = QQuickItemPrivate::get(d->root);
997 p->removeItemChangeListener(d, QQuickItemPrivate::Geometry);
998 }
999 }
1000
1001 d->resizeMode = mode;
1002 if (d->root) {
1003 d->initResize();
1004 }
1005}
1006
1008{
1009 if (root) {
1010 if (resizeMode == QQuickWidget::SizeViewToRootObject) {
1011 QQuickItemPrivate *p = QQuickItemPrivate::get(root);
1012 p->addItemChangeListener(this, QQuickItemPrivate::Geometry);
1013 }
1014 }
1016}
1017
1019{
1020 Q_Q(QQuickWidget);
1021 if (!root)
1022 return;
1023
1024 if (resizeMode == QQuickWidget::SizeViewToRootObject) {
1025 QSize newSize = QSize(root->width(), root->height());
1026 if (newSize.isValid()) {
1027 if (newSize != q->size()) {
1028 q->resize(newSize);
1029 q->updateGeometry();
1030 } else if (offscreenWindow->size().isEmpty()) {
1031 // QQuickDeliveryAgentPrivate::deliverHoverEvent() ignores events that
1032 // occur outside of QQuickRootItem's geometry, so we need it to match root's size.
1033 offscreenWindow->resize(newSize);
1034 offscreenWindow->contentItem()->setSize(newSize);
1035 }
1036 }
1037 } else if (resizeMode == QQuickWidget::SizeRootObjectToView) {
1038 const bool needToUpdateWidth = !qFuzzyCompare(q->width(), root->width());
1039 const bool needToUpdateHeight = !qFuzzyCompare(q->height(), root->height());
1040
1041 if (needToUpdateWidth && needToUpdateHeight) {
1042 // Make sure that we have realistic sizing behavior by following
1043 // what on-screen windows would do and resize everything, not just
1044 // the root item. We do this because other types may be relying on
1045 // us to behave correctly.
1046 const QSizeF newSize(q->width(), q->height());
1047 offscreenWindow->resize(newSize.toSize());
1048 offscreenWindow->contentItem()->setSize(newSize);
1049 root->setSize(newSize);
1050 } else if (needToUpdateWidth) {
1051 const int newWidth = q->width();
1052 offscreenWindow->setWidth(newWidth);
1053 offscreenWindow->contentItem()->setWidth(newWidth);
1054 root->setWidth(newWidth);
1055 } else if (needToUpdateHeight) {
1056 const int newHeight = q->height();
1057 offscreenWindow->setHeight(newHeight);
1058 offscreenWindow->contentItem()->setHeight(newHeight);
1059 root->setHeight(newHeight);
1060 }
1061 }
1062}
1063
1064/*!
1065 \internal
1066
1067 Update the position of the offscreen window, so it matches the position of the QQuickWidget.
1068 */
1070{
1071 Q_Q(QQuickWidget);
1072 if (offscreenWindow == nullptr)
1073 return;
1074
1075 const QPoint &pos = q->mapToGlobal(QPoint(0, 0));
1076 if (offscreenWindow->position() != pos)
1077 offscreenWindow->setPosition(pos);
1078}
1079
1081{
1082 QSize rootObjectSize(0,0);
1083 int widthCandidate = -1;
1084 int heightCandidate = -1;
1085 if (root) {
1086 widthCandidate = root->width();
1087 heightCandidate = root->height();
1088 }
1089 if (widthCandidate > 0) {
1090 rootObjectSize.setWidth(widthCandidate);
1091 }
1092 if (heightCandidate > 0) {
1093 rootObjectSize.setHeight(heightCandidate);
1094 }
1095 return rootObjectSize;
1096}
1097
1099{
1100 Q_Q(QQuickWidget);
1101
1102 QString translatedMessage;
1103 QString untranslatedMessage;
1104 QQuickWindowPrivate::rhiCreationFailureMessage(QLatin1String("QRhi"), &translatedMessage, &untranslatedMessage);
1105
1106 static const QMetaMethod errorSignal = QMetaMethod::fromSignal(&QQuickWidget::sceneGraphError);
1107 const bool signalConnected = q->isSignalConnected(errorSignal);
1108 if (signalConnected)
1109 emit q->sceneGraphError(QQuickWindow::ContextNotAvailable, translatedMessage);
1110
1111#if defined(Q_OS_WIN) && QT_CONFIG(messagebox)
1112 if (!signalConnected && !QLibraryInfo::isDebugBuild() && !GetConsoleWindow())
1113 QMessageBox::critical(q, QCoreApplication::applicationName(), translatedMessage);
1114#endif // Q_OS_WIN
1115 if (!signalConnected)
1116 qFatal("%s", qPrintable(untranslatedMessage));
1117}
1118
1119static inline QPlatformBackingStoreRhiConfig::Api graphicsApiToBackingStoreRhiApi(QSGRendererInterface::GraphicsApi api)
1120{
1121 switch (api) {
1122 case QSGRendererInterface::OpenGL:
1123 return QPlatformBackingStoreRhiConfig::OpenGL;
1124 case QSGRendererInterface::Vulkan:
1125 return QPlatformBackingStoreRhiConfig::Vulkan;
1126 case QSGRendererInterface::Direct3D11:
1127 return QPlatformBackingStoreRhiConfig::D3D11;
1128 case QSGRendererInterface::Direct3D12:
1129 return QPlatformBackingStoreRhiConfig::D3D12;
1130 case QSGRendererInterface::Metal:
1131 return QPlatformBackingStoreRhiConfig::Metal;
1132 default:
1133 return QPlatformBackingStoreRhiConfig::Null;
1134 }
1135}
1136
1137// Never called by Software Rendering backend
1139{
1140 Q_Q(QQuickWidget);
1141
1142 // when reparenting, the rhi may suddenly be different
1143 if (rhi) {
1144 QRhi *backingStoreRhi = QWidgetPrivate::rhi();
1145 if (backingStoreRhi && rhi != backingStoreRhi) {
1146 // Can get here not just when reparenting to a new top-level window,
1147 // but also when switching over from the offscreen infrastructure.
1148 // Do the same that the Window[AboutTo]ChangeInternal events would do.
1149 if (rhi == offscreenRenderer.rhi()) {
1152 } else {
1153 rhi = nullptr;
1154 }
1155 }
1156 }
1157
1158 // On hide-show we may invalidate() (when !isPersistentSceneGraph) but our
1159 // context is kept. We may need to initialize() again, though.
1160 const bool onlyNeedsSgInit = rhi && !offscreenWindow->isSceneGraphInitialized();
1161
1162 if (!onlyNeedsSgInit) {
1163 if (rhi)
1164 return;
1165
1166 if (QRhi *backingStoreRhi = QWidgetPrivate::rhi()) {
1167 rhi = backingStoreRhi;
1168 // We don't own the RHI, so make sure we clean up if it goes away
1169 rhi->addCleanupCallback(q, [this](QRhi *rhi) {
1170 if (this->rhi == rhi) {
1172 deviceLost = true;
1173 this->rhi = nullptr;
1174 }
1175 });
1176 }
1177
1178 if (!rhi) {
1179 // The widget (and its parent chain, if any) may not be shown at
1180 // all, yet one may still want to use it for grabs. This is
1181 // ridiculous of course because the rendering infrastructure is
1182 // tied to the top-level widget that initializes upon expose, but
1183 // it has to be supported.
1184 offscreenRenderer.setConfig(rhiConfig());
1185 offscreenRenderer.setFormat(q->format());
1186 // no window passed in, so no swapchain, but we get a functional QRhi which we own
1187 if (offscreenRenderer.create())
1188 rhi = offscreenRenderer.rhi();
1189 }
1190
1191 // Could be that something else already initialized the window with some
1192 // other graphics API for the QRhi, that's not good.
1193 if (rhi && rhi->backend() != QBackingStoreRhiSupport::apiToRhiBackend(graphicsApiToBackingStoreRhiApi(QQuickWindow::graphicsApi()))) {
1194 qWarning("The top-level window is not using the expected graphics API for composition, "
1195 "'%s' is not compatible with this QQuickWidget",
1196 rhi->backendName());
1197 rhi = nullptr;
1198 }
1199 }
1200
1201 if (rhi) {
1202 if (!offscreenWindow->isSceneGraphInitialized()) {
1203 offscreenWindow->setGraphicsDevice(QQuickGraphicsDevice::fromRhi(rhi));
1204#if QT_CONFIG(vulkan)
1205 if (QWindow *w = q->window()->windowHandle())
1206 offscreenWindow->setVulkanInstance(w->vulkanInstance());
1207 else if (rhi == offscreenRenderer.rhi())
1208 offscreenWindow->setVulkanInstance(QVulkanDefaultInstance::instance());
1209#endif
1210 renderControl->initialize();
1211 }
1212 } else {
1213 qWarning("QQuickWidget: Failed to get a QRhi from the top-level widget's window");
1214 }
1215}
1216
1217void QQuickWidget::createFramebufferObject()
1218{
1219 Q_D(QQuickWidget);
1220
1221 // Could come from Show -> initializeWithRhi -> sceneGraphInitialized in which case the size may
1222 // still be invalid on some platforms. Bail out. A resize will come later on.
1223 if (size().isEmpty())
1224 return;
1225
1226 // Even though this is just an offscreen window we should set the position on it, as it might be
1227 // useful for an item to know the actual position of the scene.
1228 // Note: The position will be update when we get a move event (see: updatePosition()).
1229 const QPoint &globalPos = mapToGlobal(QPoint(0, 0));
1230 d->offscreenWindow->setGeometry(globalPos.x(), globalPos.y(), width(), height());
1231 d->offscreenWindow->contentItem()->setSize(QSizeF(width(), height()));
1232
1233 if (d->useSoftwareRenderer) {
1234 const QSize imageSize = size() * devicePixelRatio();
1235 d->softwareImage = QImage(imageSize, QImage::Format_ARGB32_Premultiplied);
1236 d->softwareImage.setDevicePixelRatio(devicePixelRatio());
1237 d->forceFullUpdate = true;
1238 return;
1239 }
1240
1241 if (!d->rhi) {
1242 qWarning("QQuickWidget: Attempted to create output texture with no QRhi");
1243 return;
1244 }
1245
1246 int samples = d->requestedSamples;
1247 if (d->rhi->isFeatureSupported(QRhi::MultisampleRenderBuffer))
1248 samples = QSGRhiSupport::chooseSampleCount(samples, d->rhi);
1249 else
1250 samples = 0;
1251
1252 const int minTexSize = d->rhi->resourceLimit(QRhi::TextureSizeMin);
1253 const int maxTexSize = d->rhi->resourceLimit(QRhi::TextureSizeMax);
1254
1255 QSize fboSize = size() * devicePixelRatio();
1256 if (fboSize.width() > maxTexSize || fboSize.height() > maxTexSize) {
1257 qWarning("QQuickWidget: Requested backing texture size is %dx%d, but the maximum texture size for the 3D API implementation is %dx%d",
1258 fboSize.width(), fboSize.height(),
1259 maxTexSize, maxTexSize);
1260 }
1261 fboSize.setWidth(qMin(maxTexSize, qMax(minTexSize, fboSize.width())));
1262 fboSize.setHeight(qMin(maxTexSize, qMax(minTexSize, fboSize.height())));
1263
1264 // Could be a simple hide - show, in which case the previous texture is just fine.
1265 if (!d->outputTexture) {
1266 d->outputTexture = d->rhi->newTexture(QRhiTexture::RGBA8, fboSize, 1, QRhiTexture::RenderTarget | QRhiTexture::UsedAsTransferSource);
1267 if (!d->outputTexture->create()) {
1268 qWarning("QQuickWidget: failed to create output texture of size %dx%d",
1269 fboSize.width(), fboSize.height());
1270 }
1271 }
1272 if (!d->depthStencil) {
1273 d->depthStencil = d->rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, fboSize, samples,
1274 QSGRhiSupport::depthStencilBufferFlags());
1275 if (!d->depthStencil->create()) {
1276 qWarning("QQuickWidget: failed to create depth/stencil buffer of size %dx%d and sample count %d",
1277 fboSize.width(), fboSize.height(), samples);
1278 }
1279 }
1280 if (samples > 1 && !d->msaaBuffer) {
1281 d->msaaBuffer = d->rhi->newRenderBuffer(QRhiRenderBuffer::Color, fboSize, samples);
1282 if (!d->msaaBuffer->create()) {
1283 qWarning("QQuickWidget: failed to create multisample renderbuffer of size %dx%d and sample count %d",
1284 fboSize.width(), fboSize.height(), samples);
1285 }
1286 }
1287 if (!d->rt) {
1288 QRhiTextureRenderTargetDescription rtDesc;
1289 QRhiColorAttachment colorAtt;
1290 if (samples <= 1) {
1291 colorAtt.setTexture(d->outputTexture);
1292 } else {
1293 colorAtt.setRenderBuffer(d->msaaBuffer);
1294 colorAtt.setResolveTexture(d->outputTexture);
1295 }
1296 rtDesc.setColorAttachments({ colorAtt });
1297 rtDesc.setDepthStencilBuffer(d->depthStencil);
1298 d->rt = d->rhi->newTextureRenderTarget(rtDesc);
1299 d->rtRp = d->rt->newCompatibleRenderPassDescriptor();
1300 d->rt->setRenderPassDescriptor(d->rtRp);
1301 d->rt->create();
1302 }
1303 if (d->outputTexture->pixelSize() != fboSize) {
1304 d->outputTexture->setPixelSize(fboSize);
1305 if (!d->outputTexture->create()) {
1306 qWarning("QQuickWidget: failed to create resized output texture of size %dx%d",
1307 fboSize.width(), fboSize.height());
1308 }
1309 d->depthStencil->setPixelSize(fboSize);
1310 if (!d->depthStencil->create()) {
1311 qWarning("QQuickWidget: failed to create resized depth/stencil buffer of size %dx%d",
1312 fboSize.width(), fboSize.height());
1313 }
1314 if (d->msaaBuffer) {
1315 d->msaaBuffer->setPixelSize(fboSize);
1316 if (!d->msaaBuffer->create()) {
1317 qWarning("QQuickWidget: failed to create resized multisample renderbuffer of size %dx%d",
1318 fboSize.width(), fboSize.height());
1319 }
1320 }
1321 }
1322
1323 d->offscreenWindow->setRenderTarget(QQuickRenderTarget::fromRhiRenderTarget(d->rt));
1324
1325 d->renderControl->setSamples(samples);
1326
1327 // Sanity check: The window must not have an underlying platform window.
1328 // Having one would mean create() was called and platforms that only support
1329 // a single native window were in trouble.
1330 Q_ASSERT(!d->offscreenWindow->handle());
1331}
1332
1333void QQuickWidget::destroyFramebufferObject()
1334{
1335 Q_D(QQuickWidget);
1336
1337 if (d->useSoftwareRenderer) {
1338 d->softwareImage = QImage();
1339 return;
1340 }
1341
1342 delete d->rt;
1343 d->rt = nullptr;
1344 delete d->rtRp;
1345 d->rtRp = nullptr;
1346 delete d->depthStencil;
1347 d->depthStencil = nullptr;
1348 delete d->msaaBuffer;
1349 d->msaaBuffer = nullptr;
1350 delete d->outputTexture;
1351 d->outputTexture = nullptr;
1352}
1353
1354QQuickWidget::ResizeMode QQuickWidget::resizeMode() const
1355{
1356 Q_D(const QQuickWidget);
1357 return d->resizeMode;
1358}
1359
1360/*!
1361 \internal
1362 */
1363void QQuickWidget::continueExecute()
1364{
1365 Q_D(QQuickWidget);
1366 disconnect(d->component, SIGNAL(statusChanged(QQmlComponent::Status)), this, SLOT(continueExecute()));
1367
1368 if (d->component->isError()) {
1369 const QList<QQmlError> errorList = d->component->errors();
1370 for (const QQmlError &error : errorList) {
1371 QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), nullptr).warning()
1372 << error;
1373 }
1374 emit statusChanged(status());
1375 return;
1376 }
1377
1378 std::unique_ptr<QObject> obj(d->initialProperties.empty()
1379 ? d->component->create()
1380 : d->component->createWithInitialProperties(d->initialProperties));
1381
1382 if (d->component->isError()) {
1383 const QList<QQmlError> errorList = d->component->errors();
1384 for (const QQmlError &error : errorList) {
1385 QMessageLogger(error.url().toString().toLatin1().constData(), error.line(), nullptr).warning()
1386 << error;
1387 }
1388 emit statusChanged(status());
1389 return;
1390 }
1391
1392 // If we used loadFromModule, we might not have a URL so far.
1393 // Thus, query the component to retrieve the associated URL, if any
1394 if (d->source.isEmpty())
1395 d->source = d->component->url();
1396
1397 d->setRootObject(obj.release());
1398 emit statusChanged(status());
1399}
1400
1401/*!
1402 \internal
1403*/
1405{
1406 Q_Q(QQuickWidget);
1407 if (root == obj)
1408 return true;
1409
1410 if (QQuickItem *sgItem = qobject_cast<QQuickItem *>(obj)) {
1411 root = sgItem;
1412 sgItem->setParentItem(offscreenWindow->contentItem());
1413 } else if (qobject_cast<QWindow *>(obj)) {
1414 qWarning() << "QQuickWidget does not support using windows as a root item." << Qt::endl
1415 << Qt::endl
1416 << "If you wish to create your root window from QML, consider using QQmlApplicationEngine instead." << Qt::endl;
1417 } else {
1418 qWarning() << "QQuickWidget only supports loading of root objects that derive from QQuickItem." << Qt::endl
1419 << Qt::endl
1420 << "Ensure your QML code is written for QtQuick 2, and uses a root that is or" << Qt::endl
1421 << "inherits from QtQuick's Item (not a Timer, QtObject, etc)." << Qt::endl;
1422 delete obj;
1423 root = nullptr;
1424 }
1425 if (root) {
1426 initialSize = rootObjectSize();
1427 bool resized = q->testAttribute(Qt::WA_Resized);
1428 if ((resizeMode == QQuickWidget::SizeViewToRootObject || !resized) &&
1429 initialSize != q->size()) {
1430 q->resize(initialSize);
1431 }
1433 return true;
1434 }
1435
1436 return false;
1437}
1438
1440{
1443 return {};
1444
1445 QPlatformBackingStoreRhiConfig config(graphicsApiToBackingStoreRhiApi(QQuickWindow::graphicsApi()));
1446
1447 QQuickWindowPrivate *wd = QQuickWindowPrivate::get(offscreenWindow);
1448 // This is only here to support some of the env.vars. (such as
1449 // QSG_RHI_DEBUG_LAYER). There is currently no way to set a
1450 // QQuickGraphicsConfiguration for a QQuickWidget, which means things like
1451 // the pipeline cache are just not available. That is something to support
1452 // on the widget/backingstore level since that's where the QRhi is
1453 // controlled in this case.
1454 const bool debugLayerRequested = wd->graphicsConfig.isDebugLayerEnabled();
1455 config.setDebugLayer(debugLayerRequested);
1456 return config;
1457}
1458
1460{
1461 return { outputTexture, nullptr };
1462}
1463
1465{
1466 QPlatformTextureList::Flags flags = QWidgetPrivate::textureListFlags();
1467 flags |= QPlatformTextureList::NeedsPremultipliedAlphaBlending;
1468 return flags;
1469}
1470
1471/*!
1472 \internal
1473 Handle item resize and scene updates.
1474 */
1475void QQuickWidget::timerEvent(QTimerEvent* e)
1476{
1477 Q_D(QQuickWidget);
1478 if (!e || e->timerId() == d->resizetimer.timerId()) {
1479 d->updateSize();
1480 d->resizetimer.stop();
1481 } else if (e->timerId() == d->updateTimer.timerId()) {
1482 d->eventPending = false;
1483 d->updateTimer.stop();
1484 if (d->updatePending)
1485 d->renderSceneGraph();
1486 }
1487}
1488
1489/*!
1490 \internal
1491 Preferred size follows the root object geometry.
1492*/
1493QSize QQuickWidget::sizeHint() const
1494{
1495 Q_D(const QQuickWidget);
1496 QSize rootObjectSize = d->rootObjectSize();
1497 if (rootObjectSize.isEmpty()) {
1498 return size();
1499 } else {
1500 return rootObjectSize;
1501 }
1502}
1503
1504/*!
1505 Returns the initial size of the root object.
1506
1507 If \l resizeMode is SizeRootObjectToView, the root object will be
1508 resized to the size of the view. This function returns the size of the
1509 root object before it was resized.
1510*/
1511QSize QQuickWidget::initialSize() const
1512{
1513 Q_D(const QQuickWidget);
1514 return d->initialSize;
1515}
1516
1517/*!
1518 Returns the view's root \l {QQuickItem} {item}. Can be \nullptr
1519 when setSource() has not been called, if it was called with
1520 broken \l[QML]{QtQuick} code or if the root item is otherwise
1521 undefined.
1522 */
1523QQuickItem *QQuickWidget::rootObject() const
1524{
1525 Q_D(const QQuickWidget);
1526 return d->root;
1527}
1528
1529/*!
1530 \internal
1531 This function handles the \l {QResizeEvent} {resize event}
1532 \a e.
1533 */
1534void QQuickWidget::resizeEvent(QResizeEvent *e)
1535{
1536 Q_D(QQuickWidget);
1537 if (d->resizeMode == SizeRootObjectToView)
1538 d->updateSize();
1539
1540 if (e->size().isEmpty()) {
1541 //stop rendering
1542 d->fakeHidden = true;
1543 return;
1544 }
1545
1546 bool needsSync = false;
1547 if (d->fakeHidden) {
1548 //restart rendering
1549 d->fakeHidden = false;
1550 needsSync = true;
1551 }
1552
1553 // Software Renderer
1554 if (d->useSoftwareRenderer) {
1555 needsSync = true;
1556 if (d->softwareImage.size() != size() * devicePixelRatio()) {
1557 createFramebufferObject();
1558 }
1559 } else {
1560 if (d->rhi) {
1561 // Bail out when receiving a resize after scenegraph invalidation. This can happen
1562 // during hide - resize - show sequences and also during application exit.
1563 if (!d->outputTexture && !d->offscreenWindow->isSceneGraphInitialized())
1564 return;
1565 if (!d->outputTexture || d->outputTexture->pixelSize() != size() * devicePixelRatio()) {
1566 needsSync = true;
1567 createFramebufferObject();
1568 }
1569 } else {
1570 // This will result in a scenegraphInitialized() signal which
1571 // is connected to createFramebufferObject().
1572 needsSync = true;
1573 d->initializeWithRhi();
1574 }
1575
1576 if (!d->rhi) {
1577 qWarning("QQuickWidget::resizeEvent() no QRhi");
1578 return;
1579 }
1580 }
1581
1582 d->render(needsSync);
1583}
1584
1585/*! \reimp */
1586bool QQuickWidget::focusNextPrevChild(bool next)
1587{
1588 Q_D(QQuickWidget);
1589
1590 const auto *da = QQuickWindowPrivate::get(d->offscreenWindow)->deliveryAgentPrivate();
1591 Q_ASSERT(da);
1592
1593 auto *currentTarget = da->focusTargetItem();
1594 Q_ASSERT(currentTarget);
1595
1596 auto *nextTarget = QQuickItemPrivate::nextPrevItemInTabFocusChain(currentTarget, next, false);
1597 // If no child to focus, behaves like its base class (QWidget)
1598 if (!nextTarget)
1599 return QWidget::focusNextPrevChild(next);
1600
1601 // Otherwise, simulates focus event for the offscreen window (QQuickWindow)
1602 const Qt::Key k = next ? Qt::Key_Tab : Qt::Key_Backtab;
1603 QKeyEvent event(QEvent::KeyPress, k, Qt::NoModifier);
1604 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Key, QQuickProfiler::InputKeyPress, k, Qt::NoModifier);
1605 QCoreApplication::sendEvent(d->offscreenWindow, &event);
1606
1607 QKeyEvent releaseEvent(QEvent::KeyRelease, k, Qt::NoModifier);
1608 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Key, QQuickProfiler::InputKeyRelease, k, Qt::NoModifier);
1609 QCoreApplication::sendEvent(d->offscreenWindow, &releaseEvent);
1610
1611 return event.isAccepted();
1612}
1613
1614/*! \reimp */
1615void QQuickWidget::keyPressEvent(QKeyEvent *e)
1616{
1617 Q_D(QQuickWidget);
1618 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Key, QQuickProfiler::InputKeyPress, e->key(),
1619 e->modifiers());
1620
1621 QCoreApplication::sendEvent(d->offscreenWindow, e);
1622}
1623
1624/*! \reimp */
1625void QQuickWidget::keyReleaseEvent(QKeyEvent *e)
1626{
1627 Q_D(QQuickWidget);
1628 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Key, QQuickProfiler::InputKeyRelease, e->key(),
1629 e->modifiers());
1630
1631 QCoreApplication::sendEvent(d->offscreenWindow, e);
1632}
1633
1634/*! \reimp */
1635void QQuickWidget::mouseMoveEvent(QMouseEvent *e)
1636{
1637 Q_D(QQuickWidget);
1638 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Mouse, QQuickProfiler::InputMouseMove, e->position().x(),
1639 e->position().y());
1640
1641 // Put position into the event's position and scenePosition, and globalPosition into the
1642 // event's globalPosition. This way the scenePosition in e is ignored and is replaced by
1643 // position. This is necessary because QQuickWindow thinks of itself as a
1644 // top-level window always.
1645 QMouseEvent mappedEvent(e->type(), e->position(), e->position(), e->globalPosition(),
1646 e->button(), e->buttons(), e->modifiers(), e->source());
1647 // It's not just the timestamp but also the globalPressPosition, velocity etc.
1648 mappedEvent.setTimestamp(e->timestamp());
1649 QCoreApplication::sendEvent(d->offscreenWindow, &mappedEvent);
1650 e->setAccepted(mappedEvent.isAccepted());
1651}
1652
1653/*! \reimp */
1654void QQuickWidget::mouseDoubleClickEvent(QMouseEvent *e)
1655{
1656 Q_D(QQuickWidget);
1657 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Mouse, QQuickProfiler::InputMouseDoubleClick,
1658 e->button(), e->buttons());
1659
1660 // As the second mouse press is suppressed in widget windows we emulate it here for QML.
1661 // See QTBUG-25831
1662 QMouseEvent pressEvent(QEvent::MouseButtonPress, e->position(), e->position(), e->globalPosition(),
1663 e->button(), e->buttons(), e->modifiers(), e->source());
1664 pressEvent.setTimestamp(e->timestamp());
1665 QCoreApplication::sendEvent(d->offscreenWindow, &pressEvent);
1666 e->setAccepted(pressEvent.isAccepted());
1667 QMouseEvent mappedEvent(e->type(), e->position(), e->position(), e->globalPosition(),
1668 e->button(), e->buttons(), e->modifiers(), e->source());
1669 mappedEvent.setTimestamp(e->timestamp());
1670 QCoreApplication::sendEvent(d->offscreenWindow, &mappedEvent);
1671}
1672
1673/*! \reimp */
1674void QQuickWidget::showEvent(QShowEvent *)
1675{
1676 Q_D(QQuickWidget);
1677 bool shouldTriggerUpdate = true;
1678
1679 if (!d->useSoftwareRenderer) {
1680 d->initializeWithRhi();
1681
1682 if (d->offscreenWindow->isSceneGraphInitialized()) {
1683 shouldTriggerUpdate = false;
1684 d->render(true);
1685 // render() may have led to a QQuickWindow::update() call (for
1686 // example, having a scene with a QQuickFramebufferObject::Renderer
1687 // calling update() in its render()) which in turn results in
1688 // renderRequested in the rendercontrol, ending up in
1689 // triggerUpdate. In this case just calling update() is not
1690 // acceptable, we need the full renderSceneGraph issued from
1691 // timerEvent().
1692 if (!d->eventPending && d->updatePending) {
1693 d->updatePending = false;
1694 update();
1695 }
1696 }
1697 }
1698
1699 if (shouldTriggerUpdate)
1700 triggerUpdate();
1701
1702 // note offscreenWindow is "QQuickWidgetOffscreenWindow" instance
1703 d->offscreenWindow->setVisible(true);
1704 if (QQmlInspectorService *service = QQmlDebugConnector::service<QQmlInspectorService>())
1705 service->setParentWindow(d->offscreenWindow, window()->windowHandle());
1706}
1707
1708/*! \reimp */
1709void QQuickWidget::hideEvent(QHideEvent *)
1710{
1711 Q_D(QQuickWidget);
1712 if (!d->offscreenWindow->isPersistentSceneGraph())
1713 d->invalidateRenderControl();
1714 // note offscreenWindow is "QQuickWidgetOffscreenWindow" instance
1715 d->offscreenWindow->setVisible(false);
1716 if (QQmlInspectorService *service = QQmlDebugConnector::service<QQmlInspectorService>())
1717 service->setParentWindow(d->offscreenWindow, d->offscreenWindow);
1718}
1719
1720/*! \reimp */
1721void QQuickWidget::mousePressEvent(QMouseEvent *e)
1722{
1723 Q_D(QQuickWidget);
1724 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Mouse, QQuickProfiler::InputMousePress, e->button(),
1725 e->buttons());
1726
1727 QMouseEvent mappedEvent(e->type(), e->position(), e->position(), e->globalPosition(),
1728 e->button(), e->buttons(), e->modifiers(), e->source());
1729 mappedEvent.setTimestamp(e->timestamp());
1730 QCoreApplication::sendEvent(d->offscreenWindow, &mappedEvent);
1731 e->setAccepted(mappedEvent.isAccepted());
1732}
1733
1734/*! \reimp */
1735void QQuickWidget::mouseReleaseEvent(QMouseEvent *e)
1736{
1737 Q_D(QQuickWidget);
1738 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Mouse, QQuickProfiler::InputMouseRelease, e->button(),
1739 e->buttons());
1740
1741 QMouseEvent mappedEvent(e->type(), e->position(), e->position(), e->globalPosition(),
1742 e->button(), e->buttons(), e->modifiers(), e->source());
1743 mappedEvent.setTimestamp(e->timestamp());
1744 QCoreApplication::sendEvent(d->offscreenWindow, &mappedEvent);
1745 e->setAccepted(mappedEvent.isAccepted());
1746}
1747
1748#if QT_CONFIG(wheelevent)
1749/*! \reimp */
1750void QQuickWidget::wheelEvent(QWheelEvent *e)
1751{
1752 Q_D(QQuickWidget);
1753 Q_QUICK_INPUT_PROFILE(QQuickProfiler::Mouse, QQuickProfiler::InputMouseWheel,
1754 e->angleDelta().x(), e->angleDelta().y());
1755
1756 // Wheel events only have local and global positions, no need to map.
1757 QCoreApplication::sendEvent(d->offscreenWindow, e);
1758}
1759#endif
1760
1761/*!
1762 \reimp
1763*/
1764void QQuickWidget::focusInEvent(QFocusEvent * event)
1765{
1766 Q_D(QQuickWidget);
1767
1768 using FocusTarget = QWindowPrivate::FocusTarget;
1769 const Qt::FocusReason reason = event->reason();
1770
1771 switch (reason) {
1772 // if there has been an item focused:
1773 // set the first item focused, when the reason is TabFocusReason
1774 // set the last item focused, when the reason is BacktabFocusReason
1775 case Qt::TabFocusReason:
1776 case Qt::BacktabFocusReason: {
1777 const bool forward = reason == Qt::FocusReason::TabFocusReason;
1778 const FocusTarget target = forward ? FocusTarget::First : FocusTarget::Last;
1779 QQuickWindowPrivate::get(d->offscreenWindow)->setFocusToTarget(target, reason);
1780 } break;
1781 default:
1782 break;
1783 }
1784
1785 d->offscreenWindow->focusInEvent(event);
1786}
1787
1788/*!
1789 \reimp
1790*/
1791void QQuickWidget::focusOutEvent(QFocusEvent * event)
1792{
1793 Q_D(QQuickWidget);
1794 d->offscreenWindow->focusOutEvent(event);
1795}
1796
1797static Qt::WindowState resolveWindowState(Qt::WindowStates states)
1798{
1799 // No more than one of these 3 can be set
1800 if (states & Qt::WindowMinimized)
1801 return Qt::WindowMinimized;
1802 if (states & Qt::WindowMaximized)
1803 return Qt::WindowMaximized;
1804 if (states & Qt::WindowFullScreen)
1805 return Qt::WindowFullScreen;
1806
1807 // No state means "windowed" - we ignore Qt::WindowActive
1808 return Qt::WindowNoState;
1809}
1810
1811static void remapInputMethodQueryEvent(QObject *object, QInputMethodQueryEvent *e)
1812{
1813 auto item = qobject_cast<QQuickItem *>(object);
1814 if (!item)
1815 return;
1816
1817 // Remap all QRectF values.
1818 for (auto query : {Qt::ImCursorRectangle, Qt::ImAnchorRectangle, Qt::ImInputItemClipRectangle}) {
1819 if (e->queries() & query) {
1820 auto value = e->value(query);
1821 if (value.canConvert<QRectF>())
1822 e->setValue(query, item->mapRectToScene(value.toRectF()));
1823 }
1824 }
1825 // Remap all QPointF values.
1826 if (e->queries() & Qt::ImCursorPosition) {
1827 auto value = e->value(Qt::ImCursorPosition);
1828 if (value.canConvert<QPointF>())
1829 e->setValue(Qt::ImCursorPosition, item->mapToScene(value.toPointF()));
1830 }
1831}
1832
1833/*! \reimp */
1834bool QQuickWidget::event(QEvent *e)
1835{
1836 Q_D(QQuickWidget);
1837
1838 switch (e->type()) {
1839
1840 case QEvent::Leave:
1841 case QEvent::TouchBegin:
1842 case QEvent::TouchEnd:
1843 case QEvent::TouchUpdate:
1844 case QEvent::TouchCancel: {
1845 // Touch events only have local and global positions, no need to map.
1846 bool res = QCoreApplication::sendEvent(d->offscreenWindow, e);
1847 if (e->isAccepted() && e->type() == QEvent::TouchBegin) {
1848 // If the TouchBegin got accepted, then make sure all points that have
1849 // an exclusive grabber are also accepted so that the widget code for
1850 // delivering touch events make this widget an implicit grabber of those
1851 // points.
1852 QPointerEvent *pointerEvent = static_cast<QPointerEvent *>(e);
1853 auto deliveredPoints = pointerEvent->points();
1854 for (auto &point : deliveredPoints) {
1855 if (pointerEvent->exclusiveGrabber(point) || !pointerEvent->passiveGrabbers(point).isEmpty())
1856 point.setAccepted(true);
1857 }
1858 }
1859 return res;
1860 }
1861
1862 case QEvent::FocusAboutToChange:
1863 return QCoreApplication::sendEvent(d->offscreenWindow, e);
1864
1865 case QEvent::InputMethod:
1866 return QCoreApplication::sendEvent(d->offscreenWindow->focusObject(), e);
1867 case QEvent::InputMethodQuery:
1868 {
1869 bool eventResult = QCoreApplication::sendEvent(d->offscreenWindow->focusObject(), e);
1870 // The result in focusObject are based on offscreenWindow. But
1871 // the inputMethodTransform won't get updated because the focus
1872 // is on QQuickWidget. We need to remap the value based on the
1873 // widget.
1874 remapInputMethodQueryEvent(d->offscreenWindow->focusObject(), static_cast<QInputMethodQueryEvent *>(e));
1875 return eventResult;
1876 }
1877
1878 case QEvent::WindowAboutToChangeInternal:
1879 d->handleWindowAboutToChange();
1880 break;
1881
1882 case QEvent::WindowChangeInternal:
1883 d->handleWindowChange();
1884 break;
1885
1886 case QEvent::ScreenChangeInternal:
1887 {
1888 QScreen *newScreen = screen();
1889 if (d->offscreenWindow)
1890 d->offscreenWindow->setScreen(newScreen);
1891 break;
1892 }
1893 case QEvent::DevicePixelRatioChange:
1894 if (d->useSoftwareRenderer || d->outputTexture) {
1895 // This will check the size taking the devicePixelRatio into account
1896 // and recreate if needed.
1897 createFramebufferObject();
1898 d->render(true);
1899 }
1900 if (d->offscreenWindow) {
1901 QEvent dprChangeEvent(QEvent::DevicePixelRatioChange);
1902 QGuiApplication::sendEvent(d->offscreenWindow, &dprChangeEvent);
1903 }
1904 break;
1905 case QEvent::Show:
1906 case QEvent::Move:
1907 d->updatePosition();
1908 break;
1909
1910 case QEvent::WindowStateChange:
1911 d->offscreenWindow->setWindowState(resolveWindowState(windowState()));
1912 break;
1913
1914 case QEvent::ShortcutOverride:
1915 return QCoreApplication::sendEvent(d->offscreenWindow, e);
1916
1917 case QEvent::Enter: {
1918 QEnterEvent *enterEvent = static_cast<QEnterEvent *>(e);
1919 QEnterEvent mappedEvent(enterEvent->position(), enterEvent->scenePosition(),
1920 enterEvent->globalPosition());
1921 const bool ret = QCoreApplication::sendEvent(d->offscreenWindow, &mappedEvent);
1922 e->setAccepted(mappedEvent.isAccepted());
1923 return ret;
1924 }
1925 default:
1926 break;
1927 }
1928
1929 return QWidget::event(e);
1930}
1931
1932#if QT_CONFIG(quick_draganddrop)
1933
1934/*! \reimp */
1935void QQuickWidget::dragEnterEvent(QDragEnterEvent *e)
1936{
1937 Q_D(QQuickWidget);
1938 // Don't reject drag events for the entire widget when one
1939 // item rejects the drag enter
1940 d->offscreenWindow->event(e);
1941 e->accept();
1942}
1943
1944/*! \reimp */
1945void QQuickWidget::dragMoveEvent(QDragMoveEvent *e)
1946{
1947 Q_D(QQuickWidget);
1948 // Drag/drop events only have local pos, so no need to map,
1949 // but QQuickWindow::event() does not return true
1950 d->offscreenWindow->event(e);
1951}
1952
1953/*! \reimp */
1954void QQuickWidget::dragLeaveEvent(QDragLeaveEvent *e)
1955{
1956 Q_D(QQuickWidget);
1957 d->offscreenWindow->event(e);
1958}
1959
1960/*! \reimp */
1961void QQuickWidget::dropEvent(QDropEvent *e)
1962{
1963 Q_D(QQuickWidget);
1964 d->offscreenWindow->event(e);
1965}
1966
1967#endif // quick_draganddrop
1968
1969// TODO: try to separate the two cases of
1970// 1. render() unconditionally without sync
1971// 2. sync() and then render if necessary
1972void QQuickWidget::triggerUpdate()
1973{
1974 Q_D(QQuickWidget);
1975 d->updatePending = true;
1976 if (!d->eventPending) {
1977 // There's no sense in immediately kicking a render off now, as
1978 // there may be a number of triggerUpdate calls to come from a multitude
1979 // of different sources (network, touch/mouse/keyboard, timers,
1980 // animations, ...), and we want to batch them all into single frames as
1981 // much as possible for the sake of interactivity and responsiveness.
1982 //
1983 // To achieve this, we set a timer and only perform the rendering when
1984 // this is complete.
1985 const int exhaustDelay = 5;
1986 d->updateTimer.start(exhaustDelay, Qt::PreciseTimer, this);
1987 d->eventPending = true;
1988 }
1989}
1990
1991/*!
1992 Sets the surface \a format for the context and offscreen surface used
1993 by this widget.
1994
1995 Call this function when there is a need to request a context for a
1996 given OpenGL version or profile. The sizes for depth, stencil and
1997 alpha buffers are taken care of automatically and there is no need
1998 to request those explicitly.
1999
2000 \sa QWindow::setFormat(), QWindow::format(), format()
2001*/
2002void QQuickWidget::setFormat(const QSurfaceFormat &format)
2003{
2004 Q_D(QQuickWidget);
2005 QSurfaceFormat currentFormat = d->offscreenWindow->format();
2006 QSurfaceFormat newFormat = format;
2007 newFormat.setDepthBufferSize(qMax(newFormat.depthBufferSize(), currentFormat.depthBufferSize()));
2008 newFormat.setStencilBufferSize(qMax(newFormat.stencilBufferSize(), currentFormat.stencilBufferSize()));
2009 newFormat.setAlphaBufferSize(qMax(newFormat.alphaBufferSize(), currentFormat.alphaBufferSize()));
2010
2011 // Do not include the sample count. Requesting a multisampled context is not necessary
2012 // since we render into an FBO, never to an actual surface. What's more, attempting to
2013 // create a pbuffer with a multisampled config crashes certain implementations. Just
2014 // avoid the entire hassle, the result is the same.
2015 d->requestedSamples = newFormat.samples();
2016 newFormat.setSamples(0);
2017
2018 d->offscreenWindow->setFormat(newFormat);
2019}
2020
2021/*!
2022 Returns the actual surface format.
2023
2024 If the widget has not yet been shown, the requested format is returned.
2025
2026 \sa setFormat()
2027*/
2028QSurfaceFormat QQuickWidget::format() const
2029{
2030 Q_D(const QQuickWidget);
2031 return d->offscreenWindow->format();
2032}
2033
2034/*!
2035 Renders a frame and reads it back into an image.
2036
2037 \note This is a potentially expensive operation.
2038 */
2039QImage QQuickWidget::grabFramebuffer() const
2040{
2041 return const_cast<QQuickWidgetPrivate *>(d_func())->grabFramebuffer();
2042}
2043
2044/*!
2045 Sets the clear \a color. By default this is an opaque color.
2046
2047 To get a semi-transparent QQuickWidget, call this function with
2048 \a color set to Qt::transparent, set the Qt::WA_TranslucentBackground
2049 widget attribute on the top-level window, and request an alpha
2050 channel via setFormat().
2051
2052 \sa QQuickWindow::setColor()
2053 */
2054void QQuickWidget::setClearColor(const QColor &color)
2055{
2056 Q_D(QQuickWidget);
2057 d->offscreenWindow->setColor(color);
2058}
2059
2060/*!
2061 \since 5.5
2062
2063 Returns the offscreen QQuickWindow which is used by this widget to drive
2064 the Qt Quick rendering. This is useful if you want to use QQuickWindow
2065 APIs that are not currently exposed by QQuickWidget, for instance
2066 connecting to the QQuickWindow::beforeRendering() signal in order
2067 to draw native OpenGL content below Qt Quick's own rendering.
2068
2069 \warning Use the return value of this function with caution. In
2070 particular, do not ever attempt to show the QQuickWindow, and be
2071 very careful when using other QWindow-only APIs.
2072
2073 \warning The offscreen window may be deleted (and recreated) during
2074 the life time of the QQuickWidget, particularly when the widget is
2075 moved to another QQuickWindow. If you need to know when the window
2076 has been replaced, connect to its destroyed() signal.
2077*/
2078QQuickWindow *QQuickWidget::quickWindow() const
2079{
2080 Q_D(const QQuickWidget);
2081 return d->offscreenWindow;
2082}
2083
2084/*!
2085 \reimp
2086 */
2087void QQuickWidget::paintEvent(QPaintEvent *event)
2088{
2089 Q_D(QQuickWidget);
2090 if (d->useSoftwareRenderer) {
2091 QPainter painter(this);
2092 d->updateRegion = d->updateRegion.united(event->region());
2093 if (d->updateRegion.isNull()) {
2094 //Paint everything
2095 painter.drawImage(rect(), d->softwareImage);
2096 } else {
2097 QTransform transform;
2098 transform.scale(devicePixelRatio(), devicePixelRatio());
2099 //Paint only the updated areas
2100 QRegion targetRegion;
2101 d->updateRegion.swap(targetRegion);
2102 for (auto targetRect : targetRegion) {
2103 auto sourceRect = transform.mapRect(QRectF(targetRect));
2104 painter.drawImage(targetRect, d->softwareImage, sourceRect);
2105 }
2106 }
2107 }
2108}
2109
2110void QQuickWidget::propagateFocusObjectChanged(QObject *focusObject)
2111{
2112 Q_D(QQuickWidget);
2113 if (QApplication::focusObject() != this)
2114 return;
2115 if (QWindow *window = d->windowHandle(QWidgetPrivate::WindowHandleMode::TopLevel))
2116 emit window->focusObjectChanged(focusObject);
2117}
2118
2119QT_END_NAMESPACE
2120
2121#include "moc_qquickwidget_p.cpp"
2122
2123#include "moc_qquickwidget.cpp"
void setVisible(bool visible) override
QRhiRenderBuffer * depthStencil
QSize rootObjectSize() const
bool setRootObject(QObject *)
QImage grabFramebuffer() override
void execute(QAnyStringView uri, QAnyStringView typeName)
QQuickRenderControl * renderControl
void itemGeometryChanged(QQuickItem *item, QQuickGeometryChange change, const QRectF &oldGeometry) override
void handleContextCreationFailure(const QSurfaceFormat &format)
void ensureEngine() const
void init(QQmlEngine *e=nullptr)
QQmlComponent * component
QRhiRenderBuffer * msaaBuffer
QPlatformTextureList::Flags textureListFlags() override
QRhiTexture * outputTexture
TextureData texture() const override
QPlatformBackingStoreRhiConfig rhiConfig() const override
void render(bool needsSync)
bool isRenderWindow(const QWindow *w) override
QWindow * renderWindow(QPoint *offset) override
Reimplemented in subclasses to return the real window this render control is rendering into.
static QWidget * compositingWidgetFor(QWidget *widget)
static void remapInputMethodQueryEvent(QObject *object, QInputMethodQueryEvent *e)
static QPlatformBackingStoreRhiConfig::Api graphicsApiToBackingStoreRhiApi(QSGRendererInterface::GraphicsApi api)
static Qt::WindowState resolveWindowState(Qt::WindowStates states)
\inmodule QtGuiPrivate \inheaderfile rhi/qrhi.h
Definition qrhi.h:1950