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
qqmlcomponent.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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// Qt-Security score:significant
4
8
9#include "qqmlengine_p.h"
10#include "qqmlvme_p.h"
11#include "qqml.h"
12#include "qqmlengine.h"
13#include "qqmlincubator.h"
15#include <private/qqmljavascriptexpression_p.h>
16#include <private/qqmlsourcecoordinate_p.h>
17
18#include <private/qv4functionobject_p.h>
19#include <private/qv4script_p.h>
20#include <private/qv4scopedvalue_p.h>
21#include <private/qv4objectiterator_p.h>
22#include <private/qv4qobjectwrapper_p.h>
23#include <private/qv4jscall_p.h>
24
25#include <QDir>
26#include <QStack>
27#include <QStringList>
28#include <QThreadStorage>
29#include <QtCore/qdebug.h>
30#include <QtCore/qloggingcategory.h>
31#include <qqmlinfo.h>
32
33
34using namespace Qt::Literals::StringLiterals;
35
36namespace {
37 Q_CONSTINIT thread_local int creationDepth = 0;
38}
39
40Q_STATIC_LOGGING_CATEGORY(lcQmlComponentGeneral, "qt.qml.qmlcomponent")
41
42QT_BEGIN_NAMESPACE
43
44class QQmlComponentExtension : public QV4::ExecutionEngine::Deletable
45{
46public:
47 QQmlComponentExtension(QV4::ExecutionEngine *v4);
48 virtual ~QQmlComponentExtension();
49
50 QV4::PersistentValue incubationProto;
51};
53
54/*!
55 \class QQmlComponent
56 \since 5.0
57 \inmodule QtQml
58
59 \brief The QQmlComponent class encapsulates a QML component definition.
60
61 Components are reusable, encapsulated QML types with well-defined interfaces.
62
63 A QQmlComponent instance can be created from a QML file.
64 For example, if there is a \c main.qml file like this:
65
66 \qml
67 import QtQuick 2.0
68
69 Item {
70 width: 200
71 height: 200
72 }
73 \endqml
74
75 The following code loads this QML file as a component, creates an instance of
76 this component using create(), and then queries the \l Item's \l {Item::}{width}
77 value:
78
79 \code
80 QQmlEngine *engine = new QQmlEngine;
81 QQmlComponent component(engine, QUrl::fromLocalFile("main.qml"));
82 if (component.isError()) {
83 qWarning() << "Failed to load main.qml:" << component.errors();
84 return 1;
85 }
86
87 QObject *myObject = component.create();
88 if (component.isError()) {
89 qWarning() << "Failed to create instance of main.qml:" << component.errors();
90 return 1;
91 }
92
93 QQuickItem *item = qobject_cast<QQuickItem*>(myObject);
94 int width = item->width(); // width = 200
95 \endcode
96
97 To create instances of a component in code where a QQmlEngine instance is
98 not available, you can use \l qmlContext() or \l qmlEngine(). For example,
99 in the scenario below, child items are being created within a QQuickItem
100 subclass:
101
102 \code
103 void MyCppItem::init()
104 {
105 QQmlEngine *engine = qmlEngine(this);
106 // Or:
107 // QQmlEngine *engine = qmlContext(this)->engine();
108 QQmlComponent component(engine, QUrl::fromLocalFile("MyItem.qml"));
109 QQuickItem *childItem = qobject_cast<QQuickItem*>(component.create());
110 childItem->setParentItem(this);
111 }
112 \endcode
113
114 Note that these functions will return \c null when called inside the
115 constructor of a QObject subclass, as the instance will not yet have
116 a context nor engine.
117
118 \section1 Network Components
119
120 If the URL passed to QQmlComponent is a network resource, or if the QML document references a
121 network resource, the QQmlComponent has to fetch the network data before it is able to create
122 objects. In this case, the QQmlComponent will have a \l {QQmlComponent::Loading}{Loading}
123 \l {QQmlComponent::status()}{status}. An application will have to wait until the component
124 is \l {QQmlComponent::Ready}{Ready} before calling \l {QQmlComponent::create()}.
125
126 The following example shows how to load a QML file from a network resource. After creating
127 the QQmlComponent, it tests whether the component is loading. If it is, it connects to the
128 QQmlComponent::statusChanged() signal and otherwise calls the \c {continueLoading()} method
129 directly. Note that QQmlComponent::isLoading() may be false for a network component if the
130 component has been cached and is ready immediately.
131
132 \code
133 MyApplication::MyApplication()
134 {
135 // ...
136 component = new QQmlComponent(engine, QUrl("http://www.example.com/main.qml"));
137 if (component->isLoading()) {
138 QObject::connect(component, &QQmlComponent::statusChanged,
139 this, &MyApplication::continueLoading);
140 } else {
141 continueLoading();
142 }
143 }
144
145 void MyApplication::continueLoading()
146 {
147 if (component->isError()) {
148 qWarning() << component->errors();
149 } else {
150 QObject *myObject = component->create();
151 }
152 }
153 \endcode
154*/
155
156/*!
157 \qmltype Component
158 \nativetype QQmlComponent
159 \ingroup qml-utility-elements
160 \inqmlmodule QtQml
161 \brief Encapsulates a QML component definition.
162
163 Components are reusable, encapsulated QML types with well-defined interfaces.
164
165 QML objects used as components are often defined in component files, which are
166 regular \l{QML Documents} stored as \c .qml files. The Component type also
167 allows QML components to be defined inline, within a QML document, instead of
168 as a separate QML file. This is a useful way to define a small component for
169 reuse within a QML file, or for defining a component that logically belongs
170 with other QML components within a file.
171
172 For example, here is a component that is used by multiple \l Loader objects.
173 It contains a single item, a \l Rectangle:
174
175 \snippet qml/component.qml 0
176
177 Notice that, while a \l Rectangle by itself would be automatically rendered and
178 displayed, this is not the case for the above rectangle because it is defined
179 inside a Component. The component encapsulates the QML types within, as if they
180 were defined in a separate QML file, and is not loaded until requested, in this
181 case, by the two \l Loader objects. Because Component is not derived from Item,
182 you cannot anchor anything to it.
183
184 Defining a component is similar to defining a \l {QML Documents}{QML document}.
185 A QML document has a single top-level item that defines the behavior and
186 properties of that component, and cannot define properties or behavior outside
187 of that top-level item. In the same way, a Component definition contains a single
188 top level item, which in the above example is a \l Rectangle, and cannot define
189 any data outside of this item, with the exception of an \e id, which in the
190 above example is \e redSquare.
191
192 The Component type is commonly used to provide graphical components for views.
193 For example, the \l{ListView.delegate} property requires a Component to specify
194 how each list item is to be displayed.
195
196 \c Component objects can also be created dynamically using
197 \l{QtQml::Qt::createComponent()}{Qt.createComponent()}.
198
199 \c {Component}s are useful to declare a type where you only need an
200 instance of the type without having to add an entire new file. However,
201 you cannot name this type and consequently can't use it to declare a
202 property or use it in a type annotation. If you need this, prefer using
203 \l{Defining Object Types with QML Documents#Inline Components}{inline components}.
204
205 \section1 Creation Context
206
207 The creation context of a Component corresponds to the context where the
208 Component was declared. This context is used as the parent context (creating a
209 \l{Scope and Naming Resolution#component-instance-hierarchy}{context hierarchy})
210 when the component is instantiated by an object such as a ListView or a Loader.
211
212 In the following example, \c comp1 is created within the root context of
213 MyItem.qml, and any objects instantiated from this component will have access
214 to the ids and properties within that context, such as \c internalSettings.color.
215 When \c comp1 is used as a ListView delegate in another context (as in main.qml
216 below), it will continue to have access to the properties of its creation context
217 (which would otherwise be private to external users).
218
219 \table
220 \row
221 \li MyItem.qml
222 \li \snippet qml/component/MyItem.qml 0
223 \row
224 \li main.qml
225 \li \snippet qml/component/main.qml 0
226 \endtable
227
228 It is important that the lifetime of the creation context outlive any created objects. See
229 \l{Maintaining Dynamically Created Objects} for more details.
230*/
231
232/*!
233 \qmlattachedsignal Component::completed()
234
235 Emitted after the object has been instantiated. This can be used to
236 execute script code at startup, once the full QML environment has been
237 established.
238
239 The \c onCompleted signal handler can be declared on any object. The order
240 of running the handlers is undefined.
241
242 \qml
243 Rectangle {
244 Component.onCompleted: console.log("Completed Running!")
245 Rectangle {
246 Component.onCompleted: console.log("Nested Completed Running!")
247 }
248 }
249 \endqml
250*/
251
252/*!
253 \qmlattachedsignal Component::destruction()
254
255 Emitted as the object begins destruction. This can be used to undo
256 work done in response to the \l {completed}{completed()} signal, or other
257 imperative code in your application.
258
259 The \c onDestruction signal handler can be declared on any object. The
260 order of running the handlers is undefined.
261
262 \qml
263 Rectangle {
264 Component.onDestruction: console.log("Destruction Beginning!")
265 Rectangle {
266 Component.onDestruction: console.log("Nested Destruction Beginning!")
267 }
268 }
269 \endqml
270
271 \sa {Qt Qml}
272*/
273
274/*!
275 \enum QQmlComponent::Status
276
277 Specifies the loading status of the QQmlComponent.
278
279 \value Null This QQmlComponent has no data. Call loadUrl() or setData() to add QML content.
280 \value Ready This QQmlComponent is ready and create() may be called.
281 \value Loading This QQmlComponent is loading network data.
282 \value Error An error has occurred. Call errors() to retrieve a list of \l {QQmlError}{errors}.
283*/
284
285/*!
286 \enum QQmlComponent::CompilationMode
287
288 Specifies whether the QQmlComponent should load the component immediately, or asynchonously.
289
290 \value PreferSynchronous Prefer loading/compiling the component immediately, blocking the thread.
291 This is not always possible; for example, remote URLs will always load asynchronously.
292 \value Asynchronous Load/compile the component in a background thread.
293*/
294
295void QQmlComponentPrivate::ready(QQmlNotifyingBlob *)
296{
297 Q_Q(QQmlComponent);
298
299 Q_ASSERT(m_typeData);
300
301 fromTypeData(m_typeData);
302 m_typeData.reset();
303 setProgress(1.0);
304 emit q->statusChanged(q->status());
305}
306
307void QQmlComponentPrivate::progress(QQmlNotifyingBlob *, qreal p)
308{
309 setProgress(p);
310}
311
312void QQmlComponentPrivate::fromTypeData(const QQmlRefPointer<QQmlTypeData> &data)
313{
314 m_url = data->finalUrl();
315 if (auto cu = data->compilationUnit())
316 m_compilationUnit = m_engine->handle()->executableCompilationUnit(std::move(cu));
317
318 if (!m_compilationUnit) {
319 Q_ASSERT(data->isError());
320 m_state.errors.clear();
321 m_state.appendErrors(data->errors());
322 }
323}
324
325bool QQmlComponentPrivate::hadTopLevelRequiredProperties() const
326{
327 return m_state.creator()->componentHadTopLevelRequiredProperties();
328}
329
330void QQmlComponentPrivate::clear()
331{
332 if (m_typeData) {
333 m_typeData->unregisterCallback(this);
334 m_typeData.reset();
335 }
336
337 if (m_loadHelper) {
338 m_loadHelper->unregisterCallback(this);
339 m_loadHelper.reset();
340 }
341
342 m_compilationUnit.reset();
343 m_inlineComponentName.reset();
344}
345
346QObject *QQmlComponentPrivate::doBeginCreate(QQmlComponent *q, QQmlContext *context)
347{
348 if (!m_engine) {
349 // ###Qt6: In Qt 6, it should be impossible for users to create a QQmlComponent without an engine, and we can remove this check
350 qWarning("QQmlComponent: Must provide an engine before calling create");
351 return nullptr;
352 }
353 if (!context)
354 context = m_engine->rootContext();
355 return q->beginCreate(context);
356}
357
359 QV4::Value *object, const QString &propertyName, const QQmlObjectCreator *creator)
360{
361 if (!creator)
362 return;
363
364 QV4::QObjectWrapper *wrapper = object->as<QV4::QObjectWrapper>();
365 if (!wrapper)
366 return;
367
368 QObject *o = wrapper->object();
369 if (!o)
370 return;
371
372 if (QQmlData *ddata = QQmlData::get(o)) {
373 const QQmlPropertyData *propData = ddata->propertyCache->property(
374 propertyName, o, ddata->outerContext);
375 if (propData && propData->acceptsQBinding())
376 creator->removePendingBinding(o, propData->coreIndex());
377 return;
378 }
379
380 const QMetaObject *meta = o->metaObject();
381 Q_ASSERT(meta);
382 const int index = meta->indexOfProperty(propertyName.toUtf8());
383 if (index != -1 && meta->property(index).isBindable())
384 creator->removePendingBinding(o, index);
385}
386
387bool QQmlComponentPrivate::setInitialProperty(
388 QObject *base, const QString &name, const QVariant &value)
389{
390 bool isComplexProperty = name.contains(u'.');
391 QQmlProperty prop;
392 // we don't allow "fixing" inner required properties - that would seriously hamper local reasoning
393 if (m_state.hasUnsetRequiredProperties() && !isComplexProperty)
394 prop = QQmlComponentPrivate::removePropertyFromRequired(
395 base, name, m_state.requiredProperties(), m_engine);
396 else if (QQmlContext *ctxt = qmlContext(base); ctxt)
397 prop = QQmlProperty(base, name, ctxt);
398 else
399 prop = QQmlProperty(base, name, m_engine);
400
401 if (!prop.isValid()) {
402 // Having extra properties in the object that contains initial properties is not a problem.
403 // In JavaScript you can hardly ensure the _absence_ of properties. There are implicitly
404 // added properties on many objects, properties added via prototype, etc.
405 if (!isComplexProperty)
406 return true;
407
408 // QQmlProperty can't handle accesses on value types
409 const QStringList properties = name.split(u'.');
410 QV4::Scope scope(m_engine->handle());
411 QV4::ScopedObject object(scope, QV4::QObjectWrapper::wrap(scope.engine, base));
412 QV4::ScopedString segment(scope);
413 for (int i = 0; i < properties.size() - 1; ++i) {
414 segment = scope.engine->newString(properties.at(i));
415 object = object->get(segment);
416 if (scope.engine->hasException || object->isNullOrUndefined())
417 break;
418 }
419
420 const QString lastProperty = properties.last();
421 if (!object->isNullOrUndefined()) {
422 segment = scope.engine->newString(lastProperty);
423 QV4::ScopedValue v(scope, scope.engine->metaTypeToJS(value.metaType(), value.constData()));
424 object->put(segment, v);
425 } else {
426 return false;
427 }
428
429 if (scope.engine->hasException) {
430 qmlWarning(base, scope.engine->catchExceptionAsQmlError());
431 scope.engine->hasException = false;
432 return false;
433 }
434
435 removePendingQPropertyBinding(object, lastProperty, m_state.creator());
436 return true;
437 }
438
439 if (QQmlPropertyPrivate::get(prop)->writeValueProperty(value, {})) {
440 if (prop.isBindable()) {
441 if (QQmlObjectCreator *creator = m_state.creator())
442 creator->removePendingBinding(prop.object(), prop.index());
443 }
444 return true;
445 }
446
447 QQmlError error{};
448 error.setUrl(m_url);
449 error.setDescription(QStringLiteral("Could not set initial property %1").arg(name));
450 qmlWarning(base, error);
451 return false;
452}
453
454/*!
455 \internal
456*/
457QQmlComponent::QQmlComponent(QObject *parent)
458 : QObject(*(new QQmlComponentPrivate), parent)
459{
460}
461
462/*!
463 Destruct the QQmlComponent.
464*/
465QQmlComponent::~QQmlComponent()
466{
467 Q_D(QQmlComponent);
468
469 if (d->m_state.isCompletePending()) {
470 qWarning("QQmlComponent: Component destroyed while completion pending");
471
472 if (isError()) {
473 qWarning() << "This may have been caused by one of the following errors:";
474 for (const QQmlComponentPrivate::AnnotatedQmlError &e : std::as_const(d->m_state.errors))
475 qWarning().nospace().noquote() << QLatin1String(" ") << e.error;
476 }
477
478 // we might not have the creator anymore if the engine is gone
479 if (d->m_state.hasCreator())
480 d->completeCreate();
481 }
482
483 if (d->m_typeData) {
484 d->m_typeData->unregisterCallback(d);
485 if (d->m_engine && !d->m_typeData->isCompleteOrError()) {
486 // In this case we have to send it to the type loader thread to be dropped. It will
487 // manipulate its "waiting" lists that other blobs may be using concurrently.
488 QQmlTypeLoader::get(d->m_engine)->drop(QQmlDataBlob::Ptr(d->m_typeData.data()));
489 }
490 d->m_typeData.reset();
491 }
492}
493
494/*!
495 \qmlproperty enumeration Component::status
496
497 This property holds the status of component loading. The status can be one of the
498 following:
499
500 \value Component.Null no data is available for the component
501 \value Component.Ready the component has been loaded, and can be used to create instances.
502 \value Component.Loading the component is currently being loaded
503 \value Component.Error an error occurred while loading the component.
504 Calling \l errorString() will provide a human-readable description of any errors.
505 */
506
507/*!
508 \property QQmlComponent::status
509 The component's current \l{QQmlComponent::Status} {status}.
510 */
511QQmlComponent::Status QQmlComponent::status() const
512{
513 Q_D(const QQmlComponent);
514
515 if (d->m_typeData)
516 return Loading;
517 else if (!d->m_state.errors.isEmpty())
518 return Error;
519 else if (d->m_engine && (d->m_compilationUnit || d->loadedType().isValid()))
520 return Ready;
521 else if (d->m_loadHelper)
522 return Loading;
523 else
524 return Null;
525}
526
527/*!
528 Returns true if status() == QQmlComponent::Null.
529*/
530bool QQmlComponent::isNull() const
531{
532 return status() == Null;
533}
534
535/*!
536 Returns true if status() == QQmlComponent::Ready.
537*/
538bool QQmlComponent::isReady() const
539{
540 return status() == Ready;
541}
542
543/*!
544 Returns true if status() == QQmlComponent::Error.
545*/
546bool QQmlComponent::isError() const
547{
548 return status() == Error;
549}
550
551/*!
552 Returns true if status() == QQmlComponent::Loading.
553*/
554bool QQmlComponent::isLoading() const
555{
556 return status() == Loading;
557}
558
559/*!
560 Returns true if the component was created in a QML files that specifies
561 \c{pragma ComponentBehavior: Bound}, otherwise returns false.
562
563 \since 6.5
564 */
565bool QQmlComponent::isBound() const
566{
567 Q_D(const QQmlComponent);
568 return d->isBound();
569}
570
571/*!
572 \qmlproperty real Component::progress
573 The progress of loading the component, from 0.0 (nothing loaded)
574 to 1.0 (finished).
575*/
576
577/*!
578 \property QQmlComponent::progress
579 The progress of loading the component, from 0.0 (nothing loaded)
580 to 1.0 (finished).
581*/
582qreal QQmlComponent::progress() const
583{
584 Q_D(const QQmlComponent);
585 return d->m_progress;
586}
587
588/*!
589 \fn void QQmlComponent::progressChanged(qreal progress)
590
591 Emitted whenever the component's loading progress changes. \a progress will be the
592 current progress between 0.0 (nothing loaded) and 1.0 (finished).
593*/
594
595/*!
596 \fn void QQmlComponent::statusChanged(QQmlComponent::Status status)
597
598 Emitted whenever the component's status changes. \a status will be the
599 new status.
600*/
601
602/*!
603 Create a QQmlComponent with no data and give it the specified
604 \a engine and \a parent. Set the data with setData().
605*/
606QQmlComponent::QQmlComponent(QQmlEngine *engine, QObject *parent)
607 : QObject(*(new QQmlComponentPrivate), parent)
608{
609 Q_D(QQmlComponent);
610 d->m_engine = engine;
611 QObject::connect(engine, &QObject::destroyed, this, [d]() {
612 d->m_state.clear();
613 d->m_engine = nullptr;
614 });
615}
616
617/*!
618 Create a QQmlComponent from the given \a url and give it the
619 specified \a parent and \a engine.
620
621 \include qqmlcomponent.qdocinc url-note
622
623 \sa loadUrl()
624*/
625QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, QObject *parent)
626 : QQmlComponent(engine, url, QQmlComponent::PreferSynchronous, parent)
627{
628}
629
630/*!
631 Create a QQmlComponent from the given \a url and give it the
632 specified \a parent and \a engine. If \a mode is \l Asynchronous,
633 the component will be loaded and compiled asynchronously.
634
635 \include qqmlcomponent.qdocinc url-note
636
637 \sa loadUrl()
638*/
639QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, CompilationMode mode,
640 QObject *parent)
641 : QQmlComponent(engine, parent)
642{
643 Q_D(QQmlComponent);
644 d->loadUrl(url, mode);
645}
646
647/*!
648 Create a QQmlComponent from the given \a uri and \a typeName and give it
649 the specified \a parent and \a engine. If possible, the component will
650 be loaded synchronously.
651
652 \sa loadFromModule()
653 \since 6.5
654 \overload
655*/
656QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QObject *parent)
657 : QQmlComponent(engine, uri, typeName, QQmlComponent::PreferSynchronous, parent)
658{
659
660}
661
662/*!
663 Create a QQmlComponent from the given \a uri and \a typeName and give it
664 the specified \a parent and \a engine. If \a mode is \l Asynchronous,
665 the component will be loaded and compiled asynchronously.
666
667 \sa loadFromModule()
668 \since 6.5
669 \overload
670*/
671QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, CompilationMode mode, QObject *parent)
672 : QQmlComponent(engine, parent)
673{
674 loadFromModule(uri, typeName, mode);
675}
676
677/*!
678 Create a QQmlComponent from the given \a fileName and give it the specified
679 \a parent and \a engine.
680
681 \sa loadUrl()
682*/
683QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName,
684 QObject *parent)
685 : QQmlComponent(engine, fileName, QQmlComponent::PreferSynchronous, parent)
686{
687}
688
689/*!
690 Create a QQmlComponent from the given \a fileName and give it the specified
691 \a parent and \a engine. If \a mode is \l Asynchronous,
692 the component will be loaded and compiled asynchronously.
693
694 \sa loadUrl()
695*/
696QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName,
697 CompilationMode mode, QObject *parent)
698 : QQmlComponent(engine, parent)
699{
700 Q_D(QQmlComponent);
701 if (fileName.startsWith(u':'))
702 d->loadUrl(QUrl(QLatin1String("qrc") + fileName), mode);
703 else if (QDir::isAbsolutePath(fileName))
704 d->loadUrl(QUrl::fromLocalFile(fileName), mode);
705 else
706 d->loadUrl(QUrl(fileName), mode);
707}
708
709/*!
710 \internal
711*/
712QQmlComponent::QQmlComponent(QQmlEngine *engine, QV4::ExecutableCompilationUnit *compilationUnit,
713 int start, QObject *parent)
714 : QQmlComponent(engine, parent)
715{
716 Q_D(QQmlComponent);
717 d->m_compilationUnit.reset(compilationUnit);
718 d->m_start = start;
719 d->m_url = compilationUnit->finalUrl();
720 d->m_progress = 1.0;
721}
722
723void QQmlComponentPrivate::setData(const QByteArray &data, const QUrl &url, QQmlComponent::CompilationMode compilationMode)
724{
725 if (!m_engine) {
726 // ###Qt6: In Qt 6, it should be impossible for users to create a QQmlComponent without an engine, and we can remove this check
727 qWarning("QQmlComponent: Must provide an engine before calling setData");
728 return;
729 }
730
731 clear();
732
733 m_url = url;
734
735 // trim existing components with same URL; they would bloat the cache
736 // While the warning tries to discourage it, using an empty URL for the
737 // creation of a one-off component is a somewhat common use-case
738 m_engine->handle()->trimCompilationUnitsForUrl(url);
739
740 QQmlTypeLoader::Mode mode = compilationMode == QQmlComponent::Asynchronous
741 ? QQmlTypeLoader::Asynchronous
742 : QQmlTypeLoader::PreferSynchronous;
743 QQmlRefPointer<QQmlTypeData> typeData = QQmlTypeLoader::get(m_engine)->getType(data, url, mode);
744
745 if (typeData->isCompleteOrError()) {
746 fromTypeData(typeData);
747 setProgress(1.0);
748 } else {
749 m_typeData = typeData;
750 m_typeData->registerCallback(this);
751 setProgress(typeData->progress());
752 }
753}
754
755/*!
756 Sets the QQmlComponent to use the given QML \a data. If \a url
757 is provided, it is used to set the component name and to provide
758 a base path for items resolved by this component. The component will
759 be loaded and compiled synchronously.
760
761 \warning The new component will shadow any existing component of
762 the same URL. You should not pass a URL of an existing component.
763*/
764void QQmlComponent::setData(const QByteArray &data, const QUrl &url)
765{
766 Q_D(QQmlComponent);
767 d->setData(data, url, PreferSynchronous);
768 emit statusChanged(status());
769}
770
771/*!
772 Returns the QQmlContext the component was created in. This is only
773 valid for components created directly from QML.
774*/
775QQmlContext *QQmlComponent::creationContext() const
776{
777 Q_D(const QQmlComponent);
778 if (!d->m_creationContext.isNull())
779 return d->m_creationContext->asQQmlContext();
780
781 return qmlContext(this);
782}
783
784/*!
785 Returns the QQmlEngine of this component.
786
787 \since 5.12
788*/
789QQmlEngine *QQmlComponent::engine() const
790{
791 Q_D(const QQmlComponent);
792 return d->m_engine;
793}
794
795/*!
796 Load the QQmlComponent from the provided \a url.
797
798 \include qqmlcomponent.qdocinc url-note
799*/
800void QQmlComponent::loadUrl(const QUrl &url)
801{
802 Q_D(QQmlComponent);
803 d->loadUrl(url);
804}
805
806/*!
807 Load the QQmlComponent from the provided \a url.
808 If \a mode is \l Asynchronous, the component will be loaded and compiled asynchronously.
809
810 \include qqmlcomponent.qdocinc url-note
811*/
812void QQmlComponent::loadUrl(const QUrl &url, QQmlComponent::CompilationMode mode)
813{
814 Q_D(QQmlComponent);
815 d->loadUrl(url, mode);
816}
817
818void QQmlComponentPrivate::loadUrl(const QUrl &newUrl, QQmlComponent::CompilationMode mode)
819{
820 Q_Q(QQmlComponent);
821 clear();
822
823 if (newUrl.isRelative()) {
824 // The new URL is a relative URL like QUrl("main.qml").
825 m_url = m_engine->baseUrl().resolved(QUrl(newUrl.toString()));
826 } else if (m_engine->baseUrl().isLocalFile() && newUrl.isLocalFile() && !QDir::isAbsolutePath(newUrl.toLocalFile())) {
827 // The new URL is a file on disk but it's a relative path; e.g.:
828 // QUrl::fromLocalFile("main.qml") or QUrl("file:main.qml")
829 // We need to remove the scheme so that it becomes a relative URL with a relative path:
830 QUrl fixedUrl(newUrl);
831 fixedUrl.setScheme(QString());
832 // Then, turn it into an absolute URL with an absolute path by resolving it against the engine's baseUrl().
833 // This is a compatibility hack for QTBUG-58837.
834 m_url = m_engine->baseUrl().resolved(fixedUrl);
835 } else {
836 m_url = newUrl;
837 }
838
839 if (m_url.scheme() == "qrc"_L1 && !m_url.path().startsWith("/"_L1)) {
840 qWarning().nospace().noquote()
841 << "QQmlComponent: attempted to load via a relative URL '" << m_url.toString()
842 << "' in resource file system. This is not fully supported and may not work";
843 }
844
845 if (newUrl.isEmpty()) {
846 QQmlError error;
847 error.setDescription(QQmlComponent::tr("Invalid empty URL"));
848 m_state.errors.emplaceBack(error);
849 return;
850 }
851
852 setProgress(0.0);
853
854 QQmlTypeLoader::Mode loaderMode = (mode == QQmlComponent::Asynchronous)
855 ? QQmlTypeLoader::Asynchronous
856 : QQmlTypeLoader::PreferSynchronous;
857 QQmlRefPointer<QQmlTypeData> data = QQmlTypeLoader::get(m_engine)->getType(m_url, loaderMode);
858
859 if (data->isCompleteOrError()) {
860 fromTypeData(data);
861 setProgress(1.0);
862 } else {
863 m_typeData = data;
864 m_typeData->registerCallback(this);
865 setProgress(data->progress());
866 }
867
868 emit q->statusChanged(q->status());
869}
870
871/*!
872 Returns the list of errors that occurred during the last compile or create
873 operation. An empty list is returned if isError() is not set.
874*/
875QList<QQmlError> QQmlComponent::errors() const
876{
877 Q_D(const QQmlComponent);
878 QList<QQmlError> errors;
879 errors.reserve(d->m_state.errors.size());
880 for (const QQmlComponentPrivate::AnnotatedQmlError &annotated : d->m_state.errors)
881 errors.emplaceBack(annotated.error);
882 return errors;
883}
884
885/*!
886 \qmlmethod string Component::errorString()
887
888 Returns a human-readable description of any error.
889
890 The string includes the file, location, and description of each error.
891 If multiple errors are present, they are separated by a newline character.
892
893 If no errors are present, an empty string is returned.
894*/
895
896/*!
897 \internal
898 errorString() is only meant as a way to get the errors from QML side.
899*/
900QString QQmlComponent::errorString() const
901{
902 Q_D(const QQmlComponent);
903 QString ret;
904 if(!isError())
905 return ret;
906 for (const QQmlComponentPrivate::AnnotatedQmlError &annotated : d->m_state.errors) {
907 ret += annotated.error.toString() + QLatin1Char('\n');
908 }
909 return ret;
910}
911
912/*!
913 \qmlproperty url Component::url
914 The component URL. This is the URL that was used to construct the component.
915*/
916
917/*!
918 \property QQmlComponent::url
919 The component URL. This is the URL passed to either the constructor,
920 or the loadUrl(), or setData() methods.
921*/
922QUrl QQmlComponent::url() const
923{
924 Q_D(const QQmlComponent);
925 return d->m_url;
926}
927
928/*!
929 \internal
930*/
931QQmlComponent::QQmlComponent(QQmlComponentPrivate &dd, QObject *parent)
932 : QObject(dd, parent)
933{
934}
935
936/*!
937 Create an object instance from this component, within the specified \a context.
938 Returns \nullptr if creation failed.
939
940 If \a context is \nullptr (the default), it will create the instance in the
941 \l {QQmlEngine::rootContext()}{root context} of the engine.
942
943 The ownership of the returned object instance is transferred to the caller.
944
945 If the object being created from this component is a visual item, it must
946 have a visual parent, which can be set by calling
947 QQuickItem::setParentItem(). See \l {Concepts - Visual Parent in Qt Quick}
948 for more details.
949
950 \sa QQmlEngine::ObjectOwnership
951*/
952QObject *QQmlComponent::create(QQmlContext *context)
953{
954 Q_D(QQmlComponent);
955 return d->createWithProperties(
956 nullptr, QVariantMap {}, context, QQmlComponentPrivate::CreateBehavior::Cpp);
957}
958
959/*!
960 Create an object instance of this component, within the specified \a context,
961 and initialize its top-level properties with \a initialProperties.
962
963 \omit
964 TODO: also mention errorString() when QTBUG-93239 is fixed
965 \endomit
966
967 If any of the \a initialProperties cannot be set, a warning is issued. If
968 there are unset required properties, the object creation fails and returns
969 \c nullptr, in which case \l isError() will return \c true.
970
971 If \a context is \nullptr (the default), it will create the instance in the
972 \l {QQmlEngine::rootContext()}{root context} of the engine.
973
974 The ownership of the returned object instance is transferred to the caller.
975
976 \sa QQmlComponent::create
977 \since 5.14
978*/
979QObject *QQmlComponent::createWithInitialProperties(
980 const QVariantMap& initialProperties, QQmlContext *context)
981{
982 Q_D(QQmlComponent);
983 return d->createWithProperties(
984 nullptr, initialProperties, context, QQmlComponentPrivate::CreateBehavior::Cpp);
985}
986
987static void QQmlComponent_setQmlParent(QObject *me, QObject *parent); // forward declaration
988
989/*! \internal
990 */
991QObject *QQmlComponentPrivate::createWithProperties(
992 QObject *parent, const QVariantMap &properties,
993 QQmlContext *context, CreateBehavior behavior)
994{
995 Q_Q(QQmlComponent);
996
997 QObject *rv = doBeginCreate(q, context);
998 if (!rv) {
999 if (m_state.isCompletePending()) {
1000 // overridden completCreate might assume that
1001 // the object has actually been created
1002 ++creationDepth;
1003 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(m_engine);
1004 complete(ep, &m_state);
1005 --creationDepth;
1006 }
1007 return nullptr;
1008 }
1009
1010 QQmlComponent_setQmlParent(rv, parent); // internally checks if parent is nullptr
1011
1012 if (behavior == CreateBehavior::Qml) {
1013 bool ok = true;
1014 for (auto it = properties.cbegin(), end = properties.cend(); it != end; ++it)
1015 ok = setInitialProperty(rv, it.key(), it.value()) && ok;
1016 q->completeCreate();
1017 if (m_state.hasUnsetRequiredProperties()) {
1018 for (const auto &unsetRequiredProperty : std::as_const(*m_state.requiredProperties())) {
1019 const QQmlError error = unsetRequiredPropertyToQQmlError(unsetRequiredProperty);
1020 qmlWarning(rv, error);
1021 }
1022 delete std::exchange(rv, nullptr);
1023 } else if (!ok) {
1024 // We've already warned about this before
1025 delete std::exchange(rv, nullptr);
1026 }
1027 } else {
1028 setInitialProperties(rv, properties);
1029 q->completeCreate();
1030 if (m_state.hasUnsetRequiredProperties())
1031 delete std::exchange(rv, nullptr);
1032 }
1033
1034 return rv;
1035}
1036
1037/*!
1038 Create an object instance from this component, within the specified \a context.
1039 Returns \nullptr if creation failed.
1040
1041 \note This method provides advanced control over component instance creation.
1042 In general, programmers should use QQmlComponent::create() to create object
1043 instances.
1044
1045 When QQmlComponent constructs an instance, it occurs in three steps:
1046
1047 \list 1
1048 \li The object hierarchy is created, and constant values are assigned.
1049 \li Property bindings are evaluated for the first time.
1050 \li If applicable, QQmlParserStatus::componentComplete() is called on objects.
1051 \endlist
1052
1053 QQmlComponent::beginCreate() differs from QQmlComponent::create() in that it
1054 only performs step 1. QQmlComponent::completeCreate() must be called to
1055 complete steps 2 and 3.
1056
1057 This breaking point is sometimes useful when using attached properties to
1058 communicate information to an instantiated component, as it allows their
1059 initial values to be configured before property bindings take effect.
1060
1061 The ownership of the returned object instance is transferred to the caller.
1062
1063 \note The categorization of bindings into constant values and actual
1064 bindings is intentionally unspecified and may change between versions of Qt
1065 and depending on whether and how you are using \l{qmlcachegen}. You should
1066 not rely on any particular binding to be evaluated either before or after
1067 beginCreate() returns. For example a constant expression like
1068 \e{MyType.EnumValue} may be recognized as such at compile time or deferred
1069 to be executed as binding. The same holds for constant expressions like
1070 \e{-(5)} or \e{"a" + " constant string"}.
1071
1072 \sa completeCreate(), QQmlEngine::ObjectOwnership
1073*/
1074QObject *QQmlComponent::beginCreate(QQmlContext *context)
1075{
1076 Q_D(QQmlComponent);
1077 Q_ASSERT(context);
1078 return d->beginCreate(QQmlContextData::get(context));
1079}
1080
1081static QQmlParserStatus *parserStatusCast(const QQmlType &type, QObject *rv)
1082{
1083 const int parserStatusCast = type.parserStatusCast();
1084 return parserStatusCast == -1
1085 ? nullptr
1086 : reinterpret_cast<QQmlParserStatus *>(reinterpret_cast<char *>(rv) + parserStatusCast);
1087}
1088
1089QObject *QQmlComponentPrivate::beginCreate(QQmlRefPointer<QQmlContextData> context)
1090{
1091 Q_Q(QQmlComponent);
1092 auto cleanup = qScopeGuard([this] {
1093 if (!m_state.errors.isEmpty() && lcQmlComponentGeneral().isDebugEnabled()) {
1094 for (const auto &e : std::as_const(m_state.errors)) {
1095 qCDebug(lcQmlComponentGeneral) << "QQmlComponent: " << e.error.toString();
1096 }
1097 }
1098 });
1099 if (!context) {
1100 qWarning("QQmlComponent: Cannot create a component in a null context");
1101 return nullptr;
1102 }
1103
1104 if (!context->isValid()) {
1105 qWarning("QQmlComponent: Cannot create a component in an invalid context");
1106 return nullptr;
1107 }
1108
1109 if (context->engine() != m_engine) {
1110 qWarning("QQmlComponent: Must create component in context from the same QQmlEngine");
1111 return nullptr;
1112 }
1113
1114 if (m_state.isCompletePending()) {
1115 qWarning("QQmlComponent: Cannot create new component instance before completing the previous");
1116 return nullptr;
1117 }
1118
1119 // filter out temporary errors as they do not really affect component's
1120 // state (they are not part of the document compilation)
1121 m_state.errors.removeIf([](const auto &e) { return e.isTransient; });
1122 m_state.clearRequiredProperties();
1123
1124 if (!q->isReady()) {
1125 qWarning("QQmlComponent: Component is not ready");
1126 return nullptr;
1127 }
1128
1129 // Do not create infinite recursion in object creation
1130 static const int maxCreationDepth = 10;
1131 if (creationDepth >= maxCreationDepth) {
1132 qWarning("QQmlComponent: Component creation is recursing - aborting");
1133 return nullptr;
1134 }
1135
1136 QQmlEnginePrivate *enginePriv = QQmlEnginePrivate::get(m_engine);
1137
1138 enginePriv->inProgressCreations++;
1139 m_state.errors.clear();
1140 m_state.setCompletePending(true);
1141
1142 QObject *rv = nullptr;
1143 auto setupDData = [&]() {
1144 QQmlData *ddata = QQmlData::get(rv);
1145 Q_ASSERT(ddata);
1146 // top-level objects should never get JS ownership.
1147 // if JS ownership is needed this needs to be explicitly undone (like in createObject())
1148 ddata->indestructible = true;
1149 ddata->explicitIndestructibleSet = true;
1150 ddata->rootObjectInCreation = false;
1151
1152 // Assign parent context to the object if we haven't created one.
1153 if (!ddata->outerContext)
1154 ddata->outerContext = context.data();
1155 if (!ddata->context)
1156 ddata->context = context.data();
1157 };
1158
1159 const QQmlType type = loadedType();
1160 if (!type.isValid()) {
1161 enginePriv->referenceScarceResources();
1162 const QString *icName = m_inlineComponentName.get();
1163 m_state.initCreator(
1164 context, m_compilationUnit, m_creationContext, icName ? *icName : QString());
1165
1166 QQmlObjectCreator::CreationFlags flags;
1167 if (icName) {
1168 flags = QQmlObjectCreator::InlineComponent;
1169 if (m_start == -1)
1170 m_start = m_compilationUnit->inlineComponentId(*icName);
1171 Q_ASSERT(m_start > 0);
1172 } else {
1173 flags = QQmlObjectCreator::NormalObject;
1174 }
1175
1176 rv = m_state.creator()->create(m_start, nullptr, nullptr, flags);
1177 if (!rv)
1178 m_state.appendCreatorErrors();
1179 else
1180 setupDData();
1181 enginePriv->dereferenceScarceResources();
1182 } else {
1183 // TODO: extract into function
1184 rv = type.createWithQQmlData();
1185 QQmlPropertyCache::ConstPtr propertyCache = QQmlData::ensurePropertyCache(rv);
1186 setupDData();
1187 if (QQmlParserStatus *parserStatus = parserStatusCast(type, rv)) {
1188 parserStatus->classBegin();
1189 m_state.ensureRequiredPropertyStorage(rv);
1190 } else if (type.finalizerCast() != -1) {
1191 m_state.ensureRequiredPropertyStorage(rv);
1192 }
1193
1194 if (propertyCache) {
1195 for (int i = 0, propertyCount = propertyCache->propertyCount(); i < propertyCount; ++i) {
1196 if (const QQmlPropertyData *propertyData = propertyCache->property(i); propertyData->isRequired()) {
1197 m_state.ensureRequiredPropertyStorage(rv);
1198 RequiredPropertyInfo info;
1199 info.propertyName = propertyData->name(rv);
1200 m_state.addPendingRequiredProperty(rv, propertyData, info);
1201 }
1202 }
1203 } else {
1204 // we couldn't get a propertyCache from ensurePropertyCache
1205 // it is unclear what we can do in that case
1206 // ### TOOD: QTBUG-136560
1207 }
1208 }
1209
1210 return rv;
1211}
1212
1213void QQmlComponentPrivate::beginDeferred(QQmlEnginePrivate *enginePriv,
1214 QObject *object, DeferredState *deferredState)
1215{
1216 QQmlData *ddata = QQmlData::get(object);
1217 Q_ASSERT(!ddata->deferredData.isEmpty());
1218
1219 deferredState->reserve(ddata->deferredData.size());
1220
1221 for (QQmlData::DeferredData *deferredData : std::as_const(ddata->deferredData)) {
1222 enginePriv->inProgressCreations++;
1223
1224 ConstructionState state;
1225 state.setCompletePending(true);
1226
1227 auto creator = state.initCreator(
1228 deferredData->context->parent(),
1229 deferredData->compilationUnit,
1230 QQmlRefPointer<QQmlContextData>(),
1231 deferredData->inlineComponentName
1232 );
1233
1234 if (!creator->populateDeferredProperties(object, deferredData))
1235 state.appendCreatorErrors();
1236 deferredData->bindings.clear();
1237
1238 deferredState->push_back(std::move(state));
1239 }
1240}
1241
1242void QQmlComponentPrivate::completeDeferred(QQmlEnginePrivate *enginePriv, QQmlComponentPrivate::DeferredState *deferredState)
1243{
1244 for (ConstructionState &state : *deferredState)
1245 complete(enginePriv, &state);
1246}
1247
1248void QQmlComponentPrivate::complete(QQmlEnginePrivate *enginePriv, ConstructionState *state)
1249{
1250 if (state->isCompletePending()) {
1251 QQmlInstantiationInterrupt interrupt;
1252 state->creator()->finalize(interrupt);
1253
1254 state->setCompletePending(false);
1255
1256 enginePriv->inProgressCreations--;
1257
1258 if (0 == enginePriv->inProgressCreations) {
1259 while (enginePriv->erroredBindings) {
1260 enginePriv->warning(enginePriv->erroredBindings->removeError());
1261 }
1262 }
1263 }
1264}
1265
1266/*!
1267 \internal
1268 Finds the matching top-level property with name \a name of the component \a createdComponent.
1269 If it was a required property or an alias to a required property contained in \a
1270 requiredProperties, it is removed from it.
1271 \a requiredProperties must be non-null.
1272
1273 If wasInRequiredProperties is non-null, the referenced boolean is set to true iff the property
1274 was found in requiredProperties.
1275
1276 Returns the QQmlProperty with name \a name (which might be invalid if there is no such property),
1277 for further processing (for instance, actually setting the property value).
1278
1279 Note: This method is used in QQmlComponent and QQmlIncubator to manage required properties. Most
1280 classes which create components should not need it and should only need to call
1281 setInitialProperties.
1282 */
1283QQmlProperty QQmlComponentPrivate::removePropertyFromRequired(
1284 QObject *target, const QString &name, RequiredProperties *requiredProperties,
1285 QQmlEngine *engine, bool *wasInRequiredProperties)
1286{
1287 Q_ASSERT(requiredProperties);
1288
1289 const QQmlProperty prop(target, name, engine);
1290 if (!prop.isValid()) {
1291 if (wasInRequiredProperties)
1292 *wasInRequiredProperties = false;
1293 return prop;
1294 }
1295
1296 const QQmlPropertyPrivate *privProp = QQmlPropertyPrivate::get(prop);
1297 bool found = false;
1298
1299 // resolve outstanding required properties
1300 const QQmlPropertyData *targetProp = &privProp->core;
1301 QQmlData *data = QQmlData::get(target);
1302 Q_ASSERT(data && data->propertyCache);
1303
1304 if (targetProp->isAlias()) {
1305 if (requiredProperties->remove(
1306 { target, data->propertyCache->property(targetProp->coreIndex()) })) {
1307 found = true;
1308 }
1309
1310 QQmlPropertyIndex originalIndex(targetProp->coreIndex());
1311 QQmlPropertyIndex propIndex;
1312 QQmlPropertyPrivate::findAliasTarget(target, originalIndex, &target, &propIndex);
1313 data = QQmlData::get(target);
1314 Q_ASSERT(data && data->propertyCache);
1315 targetProp = data->propertyCache->property(propIndex.coreIndex());
1316 } else {
1317 // we need to get the pointer from the property cache instead of directly using
1318 // targetProp, or else the lookup will fail
1319 targetProp = data->propertyCache->property(targetProp->coreIndex());
1320 }
1321
1322 // Check if the resolved target property itself is required.
1323 if (requiredProperties->remove({target, targetProp}))
1324 found = true;
1325
1326 if (wasInRequiredProperties)
1327 *wasInRequiredProperties = found;
1328
1329 return prop;
1330}
1331
1332/*!
1333 This method provides advanced control over component instance creation.
1334 In general, programmers should use QQmlComponent::create() to create a
1335 component.
1336
1337 This function completes the component creation begun with QQmlComponent::beginCreate()
1338 and must be called afterwards.
1339
1340 \sa beginCreate()
1341*/
1342void QQmlComponent::completeCreate()
1343{
1344 Q_D(QQmlComponent);
1345
1346 d->completeCreate();
1347}
1348
1349void QQmlComponentPrivate::completeCreate()
1350{
1351 if (m_state.hasUnsetRequiredProperties()) {
1352 for (const auto& unsetRequiredProperty: std::as_const(*m_state.requiredProperties())) {
1353 QQmlError error = unsetRequiredPropertyToQQmlError(unsetRequiredProperty);
1354 m_state.errors.push_back(QQmlComponentPrivate::AnnotatedQmlError { error, true });
1355 }
1356 }
1357
1358 const QQmlType type = loadedType();
1359 if (type.isValid()) {
1360 QObject *rv = m_state.target();
1361 if (QQmlParserStatus *parserStatus = parserStatusCast(type, rv))
1362 parserStatus->componentComplete();
1363
1364 if (const int finalizerCast = type.finalizerCast(); finalizerCast != -1) {
1365 auto *hook = reinterpret_cast<QQmlFinalizerHook *>(
1366 reinterpret_cast<char *>(rv) + finalizerCast);
1367 hook->componentFinalized();
1368 }
1369
1370 /*
1371 We can directly set completePending to false, as finalize is only concerned
1372 with setting up pending bindings, but that cannot happen here, as we're
1373 dealing with a pure C++ type, which cannot have pending bindings
1374 */
1375 m_state.setCompletePending(false);
1376 QQmlEnginePrivate::get(m_engine)->inProgressCreations--;
1377 } else if (m_state.isCompletePending()) {
1378 ++creationDepth;
1379 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(m_engine);
1380 complete(ep, &m_state);
1381 --creationDepth;
1382 }
1383}
1384
1385QQmlComponentAttached::QQmlComponentAttached(QObject *parent)
1386: QObject(parent), m_prev(nullptr), m_next(nullptr)
1387{
1388}
1389
1390QQmlComponentAttached::~QQmlComponentAttached()
1391{
1392 if (m_prev) *m_prev = m_next;
1393 if (m_next) m_next->m_prev = m_prev;
1394 m_prev = nullptr;
1395 m_next = nullptr;
1396}
1397
1398/*!
1399 \internal
1400*/
1401QQmlComponentAttached *QQmlComponent::qmlAttachedProperties(QObject *obj)
1402{
1403 QQmlComponentAttached *a = new QQmlComponentAttached(obj);
1404
1405 QQmlEngine *engine = qmlEngine(obj);
1406 if (!engine)
1407 return a;
1408
1409 QQmlEnginePrivate *p = QQmlEnginePrivate::get(engine);
1410 if (p->activeObjectCreator) { // XXX should only be allowed during begin
1411 a->insertIntoList(p->activeObjectCreator->componentAttachment());
1412 } else {
1413 QQmlData *d = QQmlData::get(obj);
1414 Q_ASSERT(d);
1415 Q_ASSERT(d->context);
1416 d->context->addComponentAttached(a);
1417 }
1418
1419 return a;
1420}
1421
1422/*!
1423 Load the QQmlComponent for \a typeName in the module \a uri.
1424 If the type is implemented via a QML file, \a mode is used to
1425 load it. Types backed by C++ are always loaded synchronously.
1426
1427 \code
1428 QQmlEngine engine;
1429 QQmlComponent component(&engine);
1430 component.loadFromModule("QtQuick", "Item");
1431 // once the component is ready
1432 std::unique_ptr<QObject> item(component.create());
1433 Q_ASSERT(item->metaObject() == &QQuickItem::staticMetaObject);
1434 \endcode
1435
1436 \since 6.5
1437 \sa loadUrl()
1438 */
1439void QQmlComponent::loadFromModule(QAnyStringView uri, QAnyStringView typeName,
1440 QQmlComponent::CompilationMode mode)
1441{
1442 Q_D(QQmlComponent);
1443
1444 QQmlTypeLoader::Mode typeLoaderMode = QQmlTypeLoader::Synchronous;
1445 switch (mode) {
1446 case QQmlComponent::PreferSynchronous:
1447 typeLoaderMode = QQmlTypeLoader::PreferSynchronous;
1448 break;
1449 case QQmlComponent::Asynchronous:
1450 typeLoaderMode = QQmlTypeLoader::Asynchronous;
1451 break;
1452 }
1453
1454 d->prepareLoadFromModule(uri, typeName, typeLoaderMode);
1455 if (d->m_loadHelper->isCompleteOrError())
1456 d->completeLoadFromModule(uri, typeName);
1457 else
1458 d->m_loadHelper->registerCallback(d);
1459}
1460
1461void QQmlComponentPrivate::prepareLoadFromModule(
1462 QAnyStringView uri, QAnyStringView typeName, QQmlTypeLoader::Mode mode)
1463{
1464 // Don't let any old loadHelper call us back anymore.
1465 if (m_loadHelper)
1466 m_loadHelper->unregisterCallback(this);
1467
1468 // LoadHelper must be on the Heap as it derives from QQmlRefCount
1469 m_loadHelper = QQml::makeRefPointer<LoadHelper>(QQmlTypeLoader::get(m_engine), uri, typeName, mode);
1470}
1471
1472void QQmlComponentPrivate::completeLoadFromModule(QAnyStringView uri, QAnyStringView typeName)
1473{
1474 Q_Q(QQmlComponent);
1475
1476 // we always mimic the progressChanged behavior from loadUrl
1477 auto reportError = [&](QString msg) {
1478 QQmlError error;
1479 error.setDescription(msg);
1480 m_state.errors.push_back(std::move(error));
1481 setProgress(1);
1482 emit q->statusChanged(q->Error);
1483 };
1484 auto emitComplete = [&]() {
1485 setProgress(1);
1486 emit q->statusChanged(q->status());
1487 };
1488
1489 setProgress(0);
1490
1491 const QQmlType type = m_loadHelper->type();
1492
1493 if (m_loadHelper->resolveTypeResult() == LoadHelper::ResolveTypeResult::NoSuchModule) {
1494 reportError(QLatin1String(R"(No module named "%1" found)").arg(uri.toString()));
1495 } else if (!type.isValid()) {
1496 reportError(QLatin1String(R"(Module "%1" contains no type named "%2")")
1497 .arg(uri.toString(), typeName.toString()));
1498 } else if (type.isCreatable()) {
1499 emitComplete();
1500 } else if (type.isInlineComponent()) {
1501 auto baseUrl = type.sourceUrl();
1502 baseUrl.setFragment(QString());
1503
1504 Q_ASSERT(m_progress == 0.0);
1505 {
1506 // we don't want to emit status changes from the "helper" loadUrl below
1507 // because it would signal success to early
1508 QSignalBlocker blockSignals(q);
1509 // we really need to continue in a synchronous way, otherwise we can't check the CU
1510 loadUrl(baseUrl, QQmlComponent::PreferSynchronous);
1511 }
1512 // We do want to emit any progress change that happened in the "helper" loadUrl.
1513 if (m_progress != 0.0)
1514 emit q->progressChanged(m_progress);
1515
1516 if (q->isError()) {
1517 emitComplete();
1518 return;
1519 }
1520 QString elementName = type.elementName();
1521 if (m_compilationUnit->inlineComponentId(elementName) == -1) {
1522 QString realTypeName = typeName.toString();
1523 realTypeName.truncate(realTypeName.indexOf(u'.'));
1524 QString errorMessage = R"(Type "%1" from module "%2" contains no inline component named "%3".)"_L1.arg(
1525 realTypeName, uri.toString(), elementName);
1526 if (elementName == u"qml")
1527 errorMessage += " To load the type \"%1\", drop the \".qml\" extension."_L1.arg(realTypeName);
1528 reportError(std::move(errorMessage));
1529 } else {
1530 m_inlineComponentName = std::make_unique<QString>(std::move(elementName));
1531 emitComplete();
1532 }
1533 } else if (type.isComposite()) {
1534 QQmlComponent::CompilationMode mode = QQmlComponent::PreferSynchronous;
1535 switch (m_loadHelper->mode()) {
1536 case QQmlTypeLoader::Asynchronous:
1537 mode = QQmlComponent::Asynchronous;
1538 break;
1539 case QQmlTypeLoader::PreferSynchronous:
1540 case QQmlTypeLoader::Synchronous:
1541 mode = QQmlComponent::PreferSynchronous;
1542 break;
1543 }
1544
1545 // loadUrl takes care of signal emission
1546 loadUrl(type.sourceUrl(), mode);
1547 } else if (type.isSingleton()) {
1548 // TODO: This is meant to cover composite singletons but doesn't.
1549 reportError(QLatin1String(R"(%1 is a singleton, and cannot be loaded)").arg(typeName.toString()));
1550 } else {
1551 reportError(QLatin1String("Could not load %1, as the type is uncreatable").arg(typeName.toString()));
1552 }
1553}
1554
1555/*!
1556 Create an object instance from this component using the provided
1557 \a incubator. \a context specifies the context within which to create the object
1558 instance.
1559
1560 If \a context is \nullptr (the default), it will create the instance in the
1561 \l {QQmlEngine::rootContext()}{root context} of the engine.
1562
1563 \a forContext specifies a context that this object creation depends upon.
1564 If the \a forContext is being created asynchronously, and the
1565 \l QQmlIncubator::IncubationMode is \l QQmlIncubator::AsynchronousIfNested,
1566 this object will also be created asynchronously.
1567 If \a forContext is \nullptr (by default), the \a context will be used for this decision.
1568
1569 The created object and its creation status are available via the
1570 \a incubator.
1571
1572 \sa QQmlIncubator
1573*/
1574
1575void QQmlComponent::create(QQmlIncubator &incubator, QQmlContext *context, QQmlContext *forContext)
1576{
1577 Q_D(QQmlComponent);
1578
1579 if (!context)
1580 context = d->m_engine->rootContext();
1581
1582 QQmlRefPointer<QQmlContextData> contextData = QQmlContextData::get(context);
1583 QQmlRefPointer<QQmlContextData> forContextData =
1584 forContext ? QQmlContextData::get(forContext) : contextData;
1585
1586 if (!contextData->isValid()) {
1587 qWarning("QQmlComponent: Cannot create a component in an invalid context");
1588 return;
1589 }
1590
1591 if (contextData->engine() != d->m_engine) {
1592 qWarning("QQmlComponent: Must create component in context from the same QQmlEngine");
1593 return;
1594 }
1595
1596 if (!isReady()) {
1597 qWarning("QQmlComponent: Component is not ready");
1598 return;
1599 }
1600
1601 incubator.clear();
1602 QExplicitlySharedDataPointer<QQmlIncubatorPrivate> p(incubator.d);
1603
1604 if (d->loadedType().isValid()) {
1605 // there isn't really an incubation process for C++ backed types
1606 // so just create the object and signal that we are ready
1607
1608 p->incubateCppBasedComponent(this, context);
1609 return;
1610 }
1611
1612 QQmlEnginePrivate *enginePriv = QQmlEnginePrivate::get(d->m_engine);
1613
1614 p->compilationUnit = d->m_compilationUnit;
1615 p->enginePriv = enginePriv;
1616 p->creator.reset(new QQmlObjectCreator(
1617 contextData, d->m_compilationUnit, d->m_creationContext,
1618 d->m_inlineComponentName ? *d->m_inlineComponentName : QString(), p.data()));
1619 p->subComponentToCreate = d->m_start;
1620
1621 enginePriv->incubate(incubator, forContextData);
1622}
1623
1624/*!
1625 Set top-level \a properties of the \a object that was created from a
1626 QQmlComponent.
1627
1628 This method provides advanced control over component instance creation.
1629 In general, programmers should use
1630 \l QQmlComponent::createWithInitialProperties to create an object instance
1631 from a component.
1632
1633 Use this method after beginCreate and before completeCreate has been called.
1634 If a provided property does not exist, a warning is issued.
1635
1636 This method does not allow setting initial nested properties directly.
1637 Instead, setting an initial value for value type properties with nested
1638 properties can be achieved by creating that value type, assigning its nested
1639 property and then passing the value type as an initial property of the
1640 object to be constructed.
1641
1642 For example, in order to set fond.bold, you can create a QFont, set its
1643 weight to bold and then pass the font as an initial property.
1644
1645 \since 5.14
1646*/
1647void QQmlComponent::setInitialProperties(QObject *object, const QVariantMap &properties)
1648{
1649 Q_D(QQmlComponent);
1650 d->setInitialProperties(object, properties);
1651}
1652
1653bool QQmlComponentPrivate::setInitialProperties(QObject *object, const QVariantMap &properties)
1654{
1655 bool result = true;
1656 for (auto it = properties.constBegin(); it != properties.constEnd(); ++it) {
1657 if (it.key().contains(u'.')) {
1658 auto segments = it.key().split(u'.');
1659 QString description = u"Setting initial properties failed: Cannot initialize nested "_s
1660 u"property."_s;
1661 if (segments.size() >= 2) {
1662 QString s = u" To set %1.%2 as an initial property, create %1, set its "_s
1663 u"property %2, and pass %1 as an initial property."_s;
1664 description += s.arg(segments[0], segments[1]);
1665 }
1666 QQmlError error{};
1667 error.setUrl(m_url);
1668 error.setDescription(description);
1669 qmlWarning(object, error);
1670 return false;
1671 }
1672
1673 // Still try to set them, even if a previous one has failed.
1674 result = setInitialProperty(object, it.key(), it.value()) && result;
1675 }
1676 return result;
1677}
1678
1679/*
1680 This is essentially a copy of QQmlComponent::create(); except it takes the QQmlContextData
1681 arguments instead of QQmlContext which means we don't have to construct the rather weighty
1682 wrapper class for every delegate item.
1683
1684 This is used by QQmlDelegateModel.
1685*/
1686void QQmlComponentPrivate::incubateObject(
1687 QQmlIncubator *incubationTask,
1688 QQmlComponent *component,
1689 QQmlEngine *engine,
1690 const QQmlRefPointer<QQmlContextData> &context,
1691 const QQmlRefPointer<QQmlContextData> &forContext)
1692{
1693 QQmlIncubatorPrivate *incubatorPriv = QQmlIncubatorPrivate::get(incubationTask);
1694 QQmlEnginePrivate *enginePriv = QQmlEnginePrivate::get(engine);
1695 QQmlComponentPrivate *componentPriv = QQmlComponentPrivate::get(component);
1696
1697 incubatorPriv->compilationUnit = componentPriv->m_compilationUnit;
1698 incubatorPriv->enginePriv = enginePriv;
1699 incubatorPriv->creator.reset(new QQmlObjectCreator(
1700 context, componentPriv->m_compilationUnit, componentPriv->m_creationContext,
1701 m_inlineComponentName ? *m_inlineComponentName : QString()));
1702
1703 if (m_start == -1) {
1704 if (const QString *icName = componentPriv->m_inlineComponentName.get()) {
1705 m_start = m_compilationUnit->inlineComponentId(*icName);
1706 Q_ASSERT(m_start > 0);
1707 }
1708 }
1709 incubatorPriv->subComponentToCreate = componentPriv->m_start;
1710
1711 enginePriv->incubate(*incubationTask, forContext);
1712}
1713
1714
1715
1717
1718namespace QV4 {
1719
1720namespace Heap {
1721
1722#define QmlIncubatorObjectMembers(class, Member)
1723 Member(class, HeapValue, HeapValue, valuemapOrObject)
1724 Member(class, HeapValue, HeapValue, statusChanged)
1725 Member(class, Pointer, QmlContext *, qmlContext)
1726 Member(class, NoMark, QQmlComponentIncubator *, incubator)
1727 Member(class, NoMark, QV4QPointer<QObject>, parent)
1728
1730 DECLARE_MARKOBJECTS(QmlIncubatorObject)
1731
1732 void init(QQmlIncubator::IncubationMode = QQmlIncubator::Asynchronous);
1733 inline void destroy();
1734};
1735
1736}
1737
1739{
1740 V4_OBJECT2(QmlIncubatorObject, Object)
1742
1744 static ReturnedValue method_set_statusChanged(const FunctionObject *, const Value *thisObject, const Value *argv, int argc);
1745 static ReturnedValue method_get_status(const FunctionObject *, const Value *thisObject, const Value *argv, int argc);
1746 static ReturnedValue method_get_object(const FunctionObject *, const Value *thisObject, const Value *argv, int argc);
1747 static ReturnedValue method_forceCompletion(const FunctionObject *, const Value *thisObject, const Value *argv, int argc);
1748
1750 void setInitialState(QObject *, RequiredProperties *requiredProperties);
1751};
1752
1753}
1754
1756
1758{
1759public:
1760 QQmlComponentIncubator(QV4::Heap::QmlIncubatorObject *inc, IncubationMode mode)
1762 {
1763 incubatorObject.set(inc->internalClass->engine, inc);
1764 }
1765
1767 QV4::Scope scope(incubatorObject.engine());
1768 QV4::Scoped<QV4::QmlIncubatorObject> i(scope, incubatorObject.as<QV4::QmlIncubatorObject>());
1769 i->statusChanged(s);
1770 }
1771
1772 void setInitialState(QObject *o) override {
1773 QV4::Scope scope(incubatorObject.engine());
1774 QV4::Scoped<QV4::QmlIncubatorObject> i(scope, incubatorObject.as<QV4::QmlIncubatorObject>());
1775 auto d = QQmlIncubatorPrivate::get(this);
1776 i->setInitialState(o, d->requiredProperties());
1777 }
1778
1779 QV4::PersistentValue incubatorObject; // keep a strong internal reference while incubating
1780};
1781
1782
1783static void QQmlComponent_setQmlParent(QObject *me, QObject *parent)
1784{
1785 if (parent) {
1786 me->setParent(parent);
1787 typedef QQmlPrivate::AutoParentFunction APF;
1788 QList<APF> functions = QQmlMetaType::parentFunctions();
1789
1790 bool needParent = false;
1791 for (int ii = 0; ii < functions.size(); ++ii) {
1792 QQmlPrivate::AutoParentResult res = functions.at(ii)(me, parent);
1793 if (res == QQmlPrivate::Parented) {
1794 needParent = false;
1795 break;
1796 } else if (res == QQmlPrivate::IncompatibleParent) {
1797 needParent = true;
1798 }
1799 }
1800 if (needParent)
1801 qmlWarning(me) << "Created graphical object was not placed in the graphics scene.";
1802 }
1803}
1804
1805/*!
1806 \qmlmethod QtObject Component::createObject(QtObject parent, var properties)
1807
1808 Creates and returns an object instance of this component that will have
1809 the given \a parent and \a properties. The \a properties argument is optional.
1810 Returns null if object creation fails.
1811
1812 The object will be created in the same context as the one in which the component
1813 was created. This function will always return null when called on components
1814 which were not created in QML.
1815
1816 If you wish to create an object without setting a parent, specify \c null for
1817 the \a parent value. Note that if the returned object is to be displayed, you
1818 must provide a valid \a parent value or set the returned object's \l{Item::parent}{parent}
1819 property, otherwise the object will not be visible.
1820
1821 If a \a parent is not provided to createObject(), a reference to the returned object must be held so that
1822 it is not destroyed by the garbage collector. This is true regardless of whether \l{Item::parent} is set afterwards,
1823 because setting the Item parent does not change object ownership. Only the graphical parent is changed.
1824
1825 This method accepts an optional \a properties argument that specifies a
1826 map of initial property values for the created object. These values are applied before the object
1827 creation is finalized. This is more efficient than setting property values after object creation,
1828 particularly where large sets of property values are defined, and also allows property bindings
1829 to be set up (using \l{Qt::binding}{Qt.binding}) before the object is created.
1830
1831 The \a properties argument is specified as a map of property-value items. For example, the code
1832 below creates an object with initial \c x and \c y values of 100 and 100, respectively:
1833
1834 \qml
1835 const component = Qt.createComponent("Button.qml");
1836 if (component.status === Component.Ready) {
1837 component.createObject(parent, { x: 100, y: 100 });
1838 }
1839 \endqml
1840
1841 Dynamically created instances can be deleted with the \c destroy() method.
1842 See \l {Dynamic QML Object Creation from JavaScript} for more information.
1843
1844 \sa incubateObject()
1845*/
1846
1847
1848void QQmlComponentPrivate::setInitialProperties(
1849 QV4::ExecutionEngine *engine, QV4::QmlContext *qmlContext, const QV4::Value &o,
1850 const QV4::Value &v, RequiredProperties *requiredProperties, QObject *createdComponent,
1851 const QQmlObjectCreator *creator)
1852{
1853 QV4::Scope scope(engine);
1854 QV4::ScopedObject object(scope);
1855 QV4::ScopedObject valueMap(scope, v);
1856 QV4::ObjectIterator it(scope, valueMap, QV4::ObjectIterator::EnumerableOnly);
1857 QV4::ScopedString name(scope);
1858 QV4::ScopedValue val(scope);
1859 if (engine->hasException)
1860 return;
1861
1862 // js modules (mjs) have no qmlContext
1863 QV4::ScopedStackFrame frame(scope, qmlContext ? qmlContext : engine->scriptContext());
1864
1865 while (1) {
1866 name = it.nextPropertyNameAsString(val);
1867 if (!name)
1868 break;
1869 object = o;
1870 const QStringList properties = name->toQString().split(QLatin1Char('.'));
1871 bool isTopLevelProperty = properties.size() == 1;
1872 for (int i = 0; i < properties.size() - 1; ++i) {
1873 name = engine->newString(properties.at(i));
1874 object = object->get(name);
1875 if (engine->hasException || !object) {
1876 break;
1877 }
1878 }
1879 if (engine->hasException) {
1880 qmlWarning(createdComponent, engine->catchExceptionAsQmlError());
1881 continue;
1882 }
1883 if (!object) {
1884 QQmlError error;
1885 error.setUrl(qmlContext ? qmlContext->qmlContext()->url() : QUrl());
1886 error.setDescription(QLatin1String("Cannot resolve property \"%1\".")
1887 .arg(properties.join(u'.')));
1888 qmlWarning(createdComponent, error);
1889 continue;
1890 }
1891 const QString lastProperty = properties.last();
1892 name = engine->newString(lastProperty);
1893 object->put(name, val);
1894 if (engine->hasException) {
1895 qmlWarning(createdComponent, engine->catchExceptionAsQmlError());
1896 continue;
1897 } else if (isTopLevelProperty && requiredProperties) {
1898 auto prop = removePropertyFromRequired(createdComponent, name->toQString(),
1899 requiredProperties, engine->qmlEngine());
1900 }
1901
1902 removePendingQPropertyBinding(object, lastProperty, creator);
1903 }
1904
1905 engine->hasException = false;
1906}
1907
1908QQmlError QQmlComponentPrivate::unsetRequiredPropertyToQQmlError(const RequiredPropertyInfo &unsetRequiredProperty)
1909{
1910 QQmlError error;
1911 QString description = QLatin1String("Required property %1 was not initialized").arg(unsetRequiredProperty.propertyName);
1912 switch (unsetRequiredProperty.aliasesToRequired.size()) {
1913 case 0:
1914 break;
1915 case 1: {
1916 const auto info = unsetRequiredProperty.aliasesToRequired.first();
1917 description += QLatin1String("\nIt can be set via the alias property %1 from %2\n").arg(info.propertyName, info.fileUrl.toString());
1918 break;
1919 }
1920 default:
1921 description += QLatin1String("\nIt can be set via one of the following alias properties:");
1922 for (const auto &aliasInfo: unsetRequiredProperty.aliasesToRequired) {
1923 description += QLatin1String("\n- %1 (%2)").arg(aliasInfo.propertyName, aliasInfo.fileUrl.toString());
1924 }
1925 description += QLatin1Char('\n');
1926 }
1927 error.setDescription(description);
1928 error.setUrl(unsetRequiredProperty.fileUrl);
1929 error.setLine(qmlConvertSourceCoordinate<quint32, int>(
1930 unsetRequiredProperty.location.line()));
1931 error.setColumn(qmlConvertSourceCoordinate<quint32, int>(
1932 unsetRequiredProperty.location.column()));
1933 return error;
1934}
1935
1936#if QT_DEPRECATED_SINCE(6, 3)
1937/*!
1938 \internal
1939*/
1940void QQmlComponent::createObject(QQmlV4FunctionPtr args)
1941{
1942 Q_D(QQmlComponent);
1943 Q_ASSERT(d->m_engine);
1944 Q_ASSERT(args);
1945
1946 qmlWarning(this) << "Unsuitable arguments passed to createObject(). The first argument should "
1947 "be a QObject* or null, and the second argument should be a JavaScript "
1948 "object or a QVariantMap";
1949
1950 QObject *parent = nullptr;
1951 QV4::ExecutionEngine *v4 = args->v4engine();
1952 QV4::Scope scope(v4);
1953 QV4::ScopedValue valuemap(scope, QV4::Value::undefinedValue());
1954
1955 if (args->length() >= 1) {
1956 QV4::Scoped<QV4::QObjectWrapper> qobjectWrapper(scope, (*args)[0]);
1957 if (qobjectWrapper)
1958 parent = qobjectWrapper->object();
1959 }
1960
1961 if (args->length() >= 2) {
1962 QV4::ScopedValue v(scope, (*args)[1]);
1963 if (!v->as<QV4::Object>() || v->as<QV4::ArrayObject>()) {
1964 qmlWarning(this) << tr("createObject: value is not an object");
1965 args->setReturnValue(QV4::Encode::null());
1966 return;
1967 }
1968 valuemap = v;
1969 }
1970
1971 QQmlContext *ctxt = creationContext();
1972 if (!ctxt) ctxt = d->m_engine->rootContext();
1973
1974 QObject *rv = beginCreate(ctxt);
1975
1976 if (!rv) {
1977 args->setReturnValue(QV4::Encode::null());
1978 return;
1979 }
1980
1981 QQmlComponent_setQmlParent(rv, parent);
1982
1983 QV4::ScopedValue object(scope, QV4::QObjectWrapper::wrap(v4, rv));
1984 Q_ASSERT(object->isObject());
1985
1986 if (!valuemap->isUndefined()) {
1987 QV4::Scoped<QV4::QmlContext> qmlContext(scope, v4->qmlContext());
1988 QQmlComponentPrivate::setInitialProperties(
1989 v4, qmlContext, object, valuemap, d->m_state.requiredProperties(), rv,
1990 d->m_state.creator());
1991 }
1992 if (d->m_state.hasUnsetRequiredProperties()) {
1993 QList<QQmlError> errors;
1994 for (const auto &requiredProperty: std::as_const(*d->m_state.requiredProperties())) {
1995 errors.push_back(QQmlComponentPrivate::unsetRequiredPropertyToQQmlError(requiredProperty));
1996 }
1997 qmlWarning(rv, errors);
1998 args->setReturnValue(QV4::Encode::null());
1999 delete rv;
2000 return;
2001 }
2002
2003 d->completeCreate();
2004
2005 Q_ASSERT(QQmlData::get(rv));
2006 QQmlData::get(rv)->explicitIndestructibleSet = false;
2007 QQmlData::get(rv)->indestructible = false;
2008
2009 args->setReturnValue(object->asReturnedValue());
2010}
2011#endif
2012
2013/*!
2014 \internal
2015 */
2016QObject *QQmlComponent::createObject(QObject *parent, const QVariantMap &properties)
2017{
2018 Q_D(QQmlComponent);
2019 Q_ASSERT(d->m_engine);
2020 QObject *rv = d->createWithProperties(
2021 parent, properties, creationContext(), QQmlComponentPrivate::CreateBehavior::Qml);
2022 if (rv) {
2023 QQmlData *qmlData = QQmlData::get(rv);
2024 Q_ASSERT(qmlData);
2025 qmlData->explicitIndestructibleSet = false;
2026 qmlData->indestructible = false;
2027 }
2028 return rv;
2029}
2030
2031/*!
2032 \qmlmethod var Component::incubateObject(QtObject parent, var properties, enumeration mode)
2033
2034 Creates an incubator for an instance of this component. Incubators allow new component
2035 instances to be instantiated asynchronously and do not cause freezes in the UI.
2036
2037 The \a parent argument specifies the parent the created instance will have. Omitting the
2038 parameter or passing null will create an object with no parent. In this case, a reference
2039 to the created object must be held so that it is not destroyed by the garbage collector.
2040
2041 The \a properties argument is specified as a map of property-value items which will be
2042 set on the created object during its construction. \a mode may be Qt.Synchronous or
2043 Qt.Asynchronous, and controls whether the instance is created synchronously or asynchronously.
2044 The default is asynchronous. In some circumstances, even if Qt.Synchronous is specified,
2045 the incubator may create the object asynchronously. This happens if the component calling
2046 incubateObject() is itself being created asynchronously.
2047
2048 All three arguments are optional.
2049
2050 If successful, the method returns an incubator, otherwise null. The incubator has the following
2051 properties:
2052
2053 \list
2054 \li \c status - The status of the incubator. Valid values are Component.Ready, Component.Loading and
2055 Component.Error.
2056 \li \c object - The created object instance. Will only be available once the incubator is in the
2057 Ready status.
2058 \li \c onStatusChanged - Specifies a callback function to be invoked when the status changes. The
2059 status is passed as a parameter to the callback.
2060 \li \c{forceCompletion()} - Call to complete incubation synchronously.
2061 \endlist
2062
2063 The following example demonstrates how to use an incubator:
2064
2065 \qml
2066 const component = Qt.createComponent("Button.qml");
2067
2068 const incubator = component.incubateObject(parent, { x: 10, y: 10 });
2069 if (incubator.status !== Component.Ready) {
2070 incubator.onStatusChanged = function(status) {
2071 if (status === Component.Ready) {
2072 print("Object", incubator.object, "is now ready!");
2073 }
2074 };
2075 } else {
2076 print("Object", incubator.object, "is ready immediately!");
2077 }
2078 \endqml
2079
2080 Dynamically created instances can be deleted with the \c destroy() method.
2081 See \l {Dynamic QML Object Creation from JavaScript} for more information.
2082
2083 \sa createObject()
2084*/
2085
2086/*!
2087 \internal
2088*/
2089void QQmlComponent::incubateObject(QQmlV4FunctionPtr args)
2090{
2091 Q_D(QQmlComponent);
2092 Q_ASSERT(d->m_engine);
2093 Q_UNUSED(d);
2094 Q_ASSERT(args);
2095 QV4::ExecutionEngine *v4 = args->v4engine();
2096 QV4::Scope scope(v4);
2097
2098 QObject *parent = nullptr;
2099 QV4::ScopedValue valuemap(scope, QV4::Value::undefinedValue());
2100 QQmlIncubator::IncubationMode mode = QQmlIncubator::Asynchronous;
2101
2102 if (args->length() >= 1) {
2103 QV4::Scoped<QV4::QObjectWrapper> qobjectWrapper(scope, (*args)[0]);
2104 if (qobjectWrapper)
2105 parent = qobjectWrapper->object();
2106 }
2107
2108 if (args->length() >= 2) {
2109 QV4::ScopedValue v(scope, (*args)[1]);
2110 if (v->isNull()) {
2111 } else if (!v->as<QV4::Object>() || v->as<QV4::ArrayObject>()) {
2112 qmlWarning(this) << tr("createObject: value is not an object");
2113 args->setReturnValue(QV4::Encode::null());
2114 return;
2115 } else {
2116 valuemap = v;
2117 }
2118 }
2119
2120 if (args->length() >= 3) {
2121 QV4::ScopedValue val(scope, (*args)[2]);
2122 quint32 v = val->toUInt32();
2123 if (v == 0)
2124 mode = QQmlIncubator::Asynchronous;
2125 else if (v == 1)
2126 mode = QQmlIncubator::AsynchronousIfNested;
2127 }
2128
2129 QQmlComponentExtension *e = componentExtension(args->v4engine());
2130
2131 QV4::Scoped<QV4::QmlIncubatorObject> r(scope, v4->memoryManager->allocate<QV4::QmlIncubatorObject>(mode));
2132 QV4::ScopedObject p(scope, e->incubationProto.value());
2133 r->setPrototypeOf(p);
2134
2135 if (!valuemap->isUndefined())
2136 r->d()->valuemapOrObject.set(scope.engine, valuemap);
2137 r->d()->qmlContext.set(scope.engine, v4->qmlContext());
2138 r->d()->parent = parent;
2139
2140 QQmlIncubator *incubator = r->d()->incubator;
2141 create(*incubator, creationContext());
2142
2143 if (incubator->status() == QQmlIncubator::Null) {
2144 args->setReturnValue(QV4::Encode::null());
2145 } else {
2146 args->setReturnValue(r.asReturnedValue());
2147 }
2148}
2149
2150// XXX used by QSGLoader
2151void QQmlComponentPrivate::initializeObjectWithInitialProperties(QV4::QmlContext *qmlContext, const QV4::Value &valuemap, QObject *toCreate, RequiredProperties *requiredProperties)
2152{
2153 QV4::ExecutionEngine *v4engine = m_engine->handle();
2154 QV4::Scope scope(v4engine);
2155
2156 QV4::ScopedValue object(scope, QV4::QObjectWrapper::wrap(v4engine, toCreate));
2157 Q_ASSERT(object->as<QV4::Object>());
2158
2159 if (!valuemap.isUndefined()) {
2160 setInitialProperties(
2161 v4engine, qmlContext, object, valuemap, requiredProperties, toCreate, m_state.creator());
2162 }
2163}
2164
2165QQmlComponentExtension::QQmlComponentExtension(QV4::ExecutionEngine *v4)
2166{
2167 QV4::Scope scope(v4);
2168 QV4::ScopedObject proto(scope, v4->newObject());
2169 proto->defineAccessorProperty(QStringLiteral("onStatusChanged"),
2170 QV4::QmlIncubatorObject::method_get_statusChanged, QV4::QmlIncubatorObject::method_set_statusChanged);
2171 proto->defineAccessorProperty(QStringLiteral("status"), QV4::QmlIncubatorObject::method_get_status, nullptr);
2172 proto->defineAccessorProperty(QStringLiteral("object"), QV4::QmlIncubatorObject::method_get_object, nullptr);
2173 proto->defineDefaultProperty(QStringLiteral("forceCompletion"), QV4::QmlIncubatorObject::method_forceCompletion);
2174
2175 incubationProto.set(v4, proto);
2176}
2177
2178QV4::ReturnedValue QV4::QmlIncubatorObject::method_get_object(const FunctionObject *b, const Value *thisObject, const Value *, int)
2179{
2180 QV4::Scope scope(b);
2181 QV4::Scoped<QmlIncubatorObject> o(scope, thisObject->as<QmlIncubatorObject>());
2182 if (!o)
2183 THROW_TYPE_ERROR();
2184
2185 return QV4::QObjectWrapper::wrap(scope.engine, o->d()->incubator->object());
2186}
2187
2188QV4::ReturnedValue QV4::QmlIncubatorObject::method_forceCompletion(const FunctionObject *b, const Value *thisObject, const Value *, int)
2189{
2190 QV4::Scope scope(b);
2191 QV4::Scoped<QmlIncubatorObject> o(scope, thisObject->as<QmlIncubatorObject>());
2192 if (!o)
2193 THROW_TYPE_ERROR();
2194
2195 o->d()->incubator->forceCompletion();
2196
2197 RETURN_UNDEFINED();
2198}
2199
2200QV4::ReturnedValue QV4::QmlIncubatorObject::method_get_status(const FunctionObject *b, const Value *thisObject, const Value *, int)
2201{
2202 QV4::Scope scope(b);
2203 QV4::Scoped<QmlIncubatorObject> o(scope, thisObject->as<QmlIncubatorObject>());
2204 if (!o)
2205 THROW_TYPE_ERROR();
2206
2207 return QV4::Encode(o->d()->incubator->status());
2208}
2209
2210QV4::ReturnedValue QV4::QmlIncubatorObject::method_get_statusChanged(const FunctionObject *b, const Value *thisObject, const Value *, int)
2211{
2212 QV4::Scope scope(b);
2213 QV4::Scoped<QmlIncubatorObject> o(scope, thisObject->as<QmlIncubatorObject>());
2214 if (!o)
2215 THROW_TYPE_ERROR();
2216
2217 return QV4::Encode(o->d()->statusChanged);
2218}
2219
2220QV4::ReturnedValue QV4::QmlIncubatorObject::method_set_statusChanged(const FunctionObject *b, const Value *thisObject, const Value *argv, int argc)
2221{
2222 QV4::Scope scope(b);
2223 QV4::Scoped<QmlIncubatorObject> o(scope, thisObject->as<QmlIncubatorObject>());
2224 if (!o || argc < 1)
2225 THROW_TYPE_ERROR();
2226
2227 o->d()->statusChanged.set(scope.engine, argv[0]);
2228
2229 RETURN_UNDEFINED();
2230}
2231
2232QQmlComponentExtension::~QQmlComponentExtension()
2233{
2234}
2235
2236void QV4::Heap::QmlIncubatorObject::init(QQmlIncubator::IncubationMode m)
2237{
2238 Object::init();
2239 valuemapOrObject.set(internalClass->engine, QV4::Value::undefinedValue());
2240 statusChanged.set(internalClass->engine, QV4::Value::undefinedValue());
2241 parent.init();
2242 qmlContext.set(internalClass->engine, nullptr);
2243 incubator = new QQmlComponentIncubator(this, m);
2244}
2245
2246void QV4::Heap::QmlIncubatorObject::destroy() {
2247 delete incubator;
2248 parent.destroy();
2249 Object::destroy();
2250}
2251
2252void QV4::QmlIncubatorObject::setInitialState(QObject *o, RequiredProperties *requiredProperties)
2253{
2254 QQmlComponent_setQmlParent(o, d()->parent);
2255
2256 if (!d()->valuemapOrObject.isUndefined()) {
2257 QV4::ExecutionEngine *v4 = engine();
2258 QV4::Scope scope(v4);
2259 QV4::ScopedObject obj(scope, QV4::QObjectWrapper::wrap(v4, o));
2260 QV4::Scoped<QV4::QmlContext> qmlCtxt(scope, d()->qmlContext);
2261 QQmlComponentPrivate::setInitialProperties(
2262 v4, qmlCtxt, obj, d()->valuemapOrObject, requiredProperties, o,
2263 QQmlIncubatorPrivate::get(d()->incubator)->creator.data());
2264 }
2265}
2266
2267void QV4::QmlIncubatorObject::statusChanged(QQmlIncubator::Status s)
2268{
2269 QV4::Scope scope(engine());
2270
2271 QObject *object = d()->incubator->object();
2272
2273 if (s == QQmlIncubator::Ready) {
2274 // We don't need the arguments anymore, but we still want to hold on to the object so
2275 // that it doesn't get gc'd
2276 d()->valuemapOrObject.set(scope.engine, QV4::QObjectWrapper::wrap(scope.engine, object));
2277
2278 QQmlData *ddata = QQmlData::get(object);
2279 Q_ASSERT(ddata);
2280 ddata->explicitIndestructibleSet = false;
2281 ddata->indestructible = false;
2282 }
2283
2284 QV4::ScopedFunctionObject f(scope, d()->statusChanged);
2285 if (f) {
2286 QV4::JSCallArguments jsCallData(scope, 1);
2287 *jsCallData.thisObject = this;
2288 jsCallData.args[0] = QV4::Value::fromUInt32(s);
2289 f->call(jsCallData);
2290 if (scope.hasException()) {
2291 QQmlError error = scope.engine->catchExceptionAsQmlError();
2292 QQmlEnginePrivate::warning(QQmlEnginePrivate::get(scope.engine->qmlEngine()), error);
2293 }
2294 }
2295
2296 if (s != QQmlIncubator::Loading)
2297 d()->incubator->incubatorObject.clear();
2298}
2299
2300#undef INITIALPROPERTIES_SOURCE
2301
2302QT_END_NAMESPACE
2303
2304#include "moc_qqmlcomponent.cpp"
2305#include "moc_qqmlcomponentattached_p.cpp"
\inmodule QtCore
Definition qobject.h:106
void setInitialState(QObject *o) override
Called after the object is first created, but before complex property bindings are evaluated and,...
void statusChanged(Status s) override
Called when the status of the incubator changes.
QQmlComponentIncubator(QV4::Heap::QmlIncubatorObject *inc, IncubationMode mode)
QV4::PersistentValue incubatorObject
The QQmlError class encapsulates a QML error.
Definition qqmlerror.h:19
Status
Specifies the status of the QQmlIncubator.
DECLARE_HEAP_OBJECT(QmlContext, ExecutionContext)
Definition qjsvalue.h:24
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
static void removePendingQPropertyBinding(QV4::Value *object, const QString &propertyName, const QQmlObjectCreator *creator)
static void QQmlComponent_setQmlParent(QObject *me, QObject *parent)
DEFINE_OBJECT_VTABLE(QV4::QmlIncubatorObject)
V4_DEFINE_EXTENSION(QQmlComponentExtension, componentExtension)
static QQmlParserStatus * parserStatusCast(const QQmlType &type, QObject *rv)
static ReturnedValue method_set_statusChanged(const FunctionObject *, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_get_status(const FunctionObject *, const Value *thisObject, const Value *argv, int argc)
static ReturnedValue method_get_object(const FunctionObject *, const Value *thisObject, const Value *argv, int argc)
void statusChanged(QQmlIncubator::Status)
void setInitialState(QObject *, RequiredProperties *requiredProperties)
static ReturnedValue method_forceCompletion(const FunctionObject *, const Value *thisObject, const Value *argv, int argc)