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
qqmlcontext.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
6
7#include <private/qmetaobject_p.h>
8#include <private/qqmlcomponent_p.h>
9#include <private/qqmlexpression_p.h>
10#include <private/qv4codegen_p.h>
11
12#include <QtQml/qjsengine.h>
13#include <QtQml/qqmlabstracturlinterceptor.h>
14#include <QtQml/qqmlengine.h>
15
16#include <QtCore/qvarlengtharray.h>
17#include <QtCore/qdebug.h>
18#include <QtCore/qqueue.h>
19
21
22/*!
23 \class QQmlContext
24 \brief The QQmlContext class defines a context within a QML engine.
25 \inmodule QtQml
26
27 Contexts hold the objects identified by \e id in a QML document. You
28 can use \l{nameForObject()} and \l{objectForName()} to retrieve them.
29
30 \note It is the responsibility of the creator to delete any QQmlContext it
31 constructs. If a QQmlContext is no longer needed, it must be destroyed
32 explicitly. The simplest way to ensure this is to give the QQmlContext a
33 \l{QObject::setParent()}{parent}.
34
35 \section1 The Context Hierarchy
36
37 Contexts form a hierarchy. The root of this hierarchy is the QML engine's
38 \l {QQmlEngine::rootContext()}{root context}. Each QML component creates its
39 own context when instantiated and some QML elements create extra contexts
40 for themselves.
41
42 While QML objects instantiated in a context are not strictly owned by that
43 context, their bindings are. If a context is destroyed, the property bindings of
44 outstanding QML objects will stop evaluating.
45
46 \section1 Context Properties
47
48 Contexts also allow data to be exposed to the QML components instantiated
49 by the QML engine. Such data is invisible to any tooling, including the
50 \l{Qt Quick Compiler} and to future readers of the QML documents in
51 question. It will only be exposed if the QML component is instantiated in
52 the specific C++ context you are envisioning. In other places, different
53 context data may be exposed instead.
54
55 Instead of using the QML context to expose data to your QML components, you
56 should either create additional object properties to hold the data or use
57 \l{QML_SINGLETON}{singletons}. See
58 \l{qtqml-cppintegration-exposecppstate.html}{Exposing C++ State to QML} for
59 a detailed explanation.
60
61 Each QQmlContext contains a set of properties, distinct from its QObject
62 properties, that allow data to be explicitly bound to a context by name. The
63 context properties can be defined and updated by calling
64 QQmlContext::setContextProperty().
65
66 To simplify binding and maintaining larger data sets, a context object can be set
67 on a QQmlContext. All the properties of the context object are available
68 by name in the context, as though they were all individually added through calls
69 to QQmlContext::setContextProperty(). Changes to the property's values are
70 detected through the property's notify signal. Setting a context object is both
71 faster and easier than manually adding and maintaining context property values.
72
73 All properties added explicitly by QQmlContext::setContextProperty() take
74 precedence over the context object's properties.
75
76 Child contexts inherit the context properties of their parents; if a child
77 context sets a context property that already exists in its parent, the new
78 context property overrides that of the parent.
79
80 \warning Setting the context object or adding new context properties after
81 an object has been created in that context is an expensive operation
82 (essentially forcing all bindings to re-evaluate). Thus, if you need to use
83 context properties, you should at least complete the "setup" of the context
84 before using it to create any objects.
85
86 \sa {qtqml-cppintegration-exposecppattributes.html}{Exposing Attributes of C++ Types to QML}
87*/
88
89/*! \internal */
90QQmlContext::QQmlContext(QQmlEngine *e, bool)
91 : QObject(*(new QQmlContextPrivate(this, QQmlRefPointer<QQmlContextData>(), e)))
92{
93}
94
95/*!
96 Create a new QQmlContext as a child of \a engine's root context, and the
97 QObject \a parent.
98*/
99QQmlContext::QQmlContext(QQmlEngine *engine, QObject *parent)
100 : QObject(*(new QQmlContextPrivate(this, engine
101 ? QQmlContextData::get(engine->rootContext())
102 : QQmlRefPointer<QQmlContextData>())), parent)
103{
104}
105
106/*!
107 Create a new QQmlContext with the given \a parentContext, and the
108 QObject \a parent.
109*/
110QQmlContext::QQmlContext(QQmlContext *parentContext, QObject *parent)
111 : QObject(*(new QQmlContextPrivate(this, parentContext
112 ? QQmlContextData::get(parentContext)
113 : QQmlRefPointer<QQmlContextData>())), parent)
114{
115}
116
117/*!
118 \internal
119*/
120QQmlContext::QQmlContext(QQmlContextPrivate &dd, QObject *parent)
121 : QObject(dd, parent)
122{
123}
124
125/*!
126 Destroys the QQmlContext.
127
128 Any expressions, or sub-contexts dependent on this context will be
129 invalidated, but not destroyed (unless they are parented to the QQmlContext
130 object).
131 */
132QQmlContext::~QQmlContext()
133{
134 Q_D(QQmlContext);
135 d->m_data->clearPublicContext();
136}
137
138/*!
139 Returns whether the context is valid.
140
141 To be valid, a context must have a engine, and it's contextObject(), if any,
142 must not have been deleted.
143*/
144bool QQmlContext::isValid() const
145{
146 Q_D(const QQmlContext);
147 return d->m_data->isValid();
148}
149
150/*!
151 Return the context's QQmlEngine, or \nullptr if the context has no QQmlEngine or the
152 QQmlEngine was destroyed.
153*/
154QQmlEngine *QQmlContext::engine() const
155{
156 Q_D(const QQmlContext);
157 return d->m_data->engine();
158}
159
160/*!
161 Return the context's parent QQmlContext, or \nullptr if this context has no
162 parent or if the parent has been destroyed.
163*/
164QQmlContext *QQmlContext::parentContext() const
165{
166 Q_D(const QQmlContext);
167
168 if (QQmlRefPointer<QQmlContextData> parent = d->m_data->parent())
169 return parent->asQQmlContext();
170 return nullptr;
171}
172
173/*!
174 \since 6.11
175
176 Return the context's immediate child QQmlContexts.
177
178 \sa parentContext(), findObjectRecursively(), findObjectsRecursively()
179*/
180QList<QQmlContext *> QQmlContext::childContexts() const
181{
182 Q_D(const QQmlContext);
183 QList<QQmlContext *> result;
184 for (auto child = d->m_data->childContexts(); child; child = child->nextChild())
185 result.append(child->asQQmlContext());
186 return result;
187}
188
189/*!
190 Return the context object, or \nullptr if there is no context object.
191*/
192QObject *QQmlContext::contextObject() const
193{
194 Q_D(const QQmlContext);
195 return d->m_data->contextObject();
196}
197
198/*!
199 Set the context \a object.
200
201 \note You should not use context objects to inject values into your QML
202 components. Use singletons or regular object properties instead.
203*/
204void QQmlContext::setContextObject(QObject *object)
205{
206 Q_D(QQmlContext);
207
208 QQmlRefPointer<QQmlContextData> data = d->m_data;
209
210 if (data->isInternal()) {
211 qWarning("QQmlContext: Cannot set context object for internal context.");
212 return;
213 }
214
215 if (!data->isValid()) {
216 qWarning("QQmlContext: Cannot set context object on invalid context.");
217 return;
218 }
219
220 data->setContextObject(object);
221 data->refreshExpressions();
222}
223
224/*!
225 Set a the \a value of the \a name property on this context.
226
227 \note You should not use context properties to inject values into your QML
228 components. Use singletons or regular object properties instead.
229
230 \note You should not try to override members of the JavaScript global object
231 using context properties. This works by accident, but only for
232 interpreted or JIT'ed code (not for AOT-compiled code) and only if you
233 set the context property before resolving the name for the first time.
234 The precedence between context properties and members of the JavaScript
235 global object has changed in the past and will change again.
236*/
237void QQmlContext::setContextProperty(const QString &name, const QVariant &value)
238{
239 Q_D(QQmlContext);
240
241 const QQmlContextData *data = d->m_data;
242
243 if (data->isInternal()) {
244 qWarning("QQmlContext: Cannot set property on internal context.");
245 return;
246 }
247
248 if (!data->isValid()) {
249 qWarning("QQmlContext: Cannot set property on invalid context.");
250 return;
251 }
252
253 if (QV4::Compiler::Codegen::isNameGlobal(name)) {
254 QQmlEnginePrivate::get(data->engine())->preferContextPropertiesOverJavaScriptGlobals = true;
255
256 qWarning("Setting a context property '%s' tries to override a member of the JavaScript "
257 "global object. This only works if you run the code through the interpreter or "
258 "the JIT. You can't do this in AOT-compiled code. Furthermore, it only works if "
259 "you set the context property before resolving the name for the first "
260 "time in this context. This behavior has changed in the past and will change "
261 "again. You must not rely on it.", qPrintable(name));
262 if (name == QLatin1String("console")) {
263 qWarning("In order to intercept messages sent via the 'console' object, use logging "
264 "categories and/or qInstallMessageHandler(). The QML engine sends all "
265 "messages with no explicit logging category to the 'qml' logging category.");
266 }
267 } else if (bool isNumber = false; name.toUInt(&isNumber), isNumber) {
268 qWarning("QQmlContext: Using numbers as context properties will be disallowed in a future "
269 "Qt version.");
270 QT7_ONLY(return;)
271 }
272
273 d->setContextProperty(name, value);
274}
275
276/*!
277 Set the \a value of the \a name property on this context.
278
279 QQmlContext does \b not take ownership of \a value.
280
281 \note You should not use context properties to inject values into your QML
282 components. Use singletons or regular object properties instead.
283
284 \note You should not try to override members of the JavaScript global object
285 using context properties. This works by accident, but only for
286 interpreted or JIT'ed code (not for AOT-compiled code) and only if you
287 set the context property before resolving the name for the first time.
288 The precedence between context properties and members of the JavaScript
289 global object has changed in the past and will change again.
290*/
291void QQmlContext::setContextProperty(const QString &name, QObject *value)
292{
293 setContextProperty(name, QVariant::fromValue(value));
294}
295
296/*!
297 \since 5.11
298
299 Set a batch of \a properties on this context.
300
301 Setting all properties in one batch avoids unnecessary
302 refreshing expressions, and is therefore recommended
303 instead of calling \l setContextProperty() for each individual property.
304
305 \note You should not use context properties to inject values into your QML
306 components. Use singletons or regular object properties instead.
307
308 \note You should not try to override members of the JavaScript global object
309 using context properties. This works by accident, but only for
310 interpreted or JIT'ed code (not for AOT-compiled code) and only if you
311 set the context property before resolving the name for the first time.
312 The precedence between context properties and members of the JavaScript
313 global object has changed in the past and will change again.
314
315 \sa QQmlContext::setContextProperty()
316*/
317void QQmlContext::setContextProperties(const QList<PropertyPair> &properties)
318{
319 Q_D(const QQmlContext);
320
321 QQmlRefPointer<QQmlContextData> data = d->m_data;
322 QQmlJavaScriptExpression *expressions = data->takeExpressions();
323 QQmlRefPointer<QQmlContextData> childContexts = data->takeChildContexts();
324
325 for (const auto &property : properties)
326 setContextProperty(property.name, property.value);
327
328 data->setExpressions(expressions);
329 data->setChildContexts(childContexts);
330 data->refreshExpressions();
331}
332
333/*!
334 \since 5.11
335
336 \class QQmlContext::PropertyPair
337 \inmodule QtQml
338
339 This struct contains a property name and a property value.
340 It is used as a parameter for the \c setContextProperties function.
341
342 \sa QQmlContext::setContextProperties()
343*/
344
346 const QQmlRefPointer<QQmlContextData> &data, QObject *object, const QString &name,
347 QVariant *target)
348{
349 QQmlPropertyData local;
350 if (const QQmlPropertyData *property = QQmlPropertyCache::property(object, name, data, &local)) {
351 *target = object->metaObject()->property(property->coreIndex()).read(object);
352 return true;
353 }
354 return false;
355}
356
357/*!
358 Returns the value of the \a name property for this context as a QVariant.
359 If you know that the property you're looking for is a QObject assigned using
360 a QML id in the current context, \l objectForName() is more convenient and
361 faster. In contrast to \l objectForName() and \l nameForObject(), this method
362 does traverse the context hierarchy and searches in parent contexts if the
363 \a name is not found in the current one. It also considers any
364 \l contextObject() you may have set.
365
366 \sa objectForName(), nameForObject(), contextObject()
367 */
368QVariant QQmlContext::contextProperty(const QString &name) const
369{
370 Q_D(const QQmlContext);
371
372 const QQmlRefPointer<QQmlContextData> data = d->m_data;
373
374 const int idx = data->propertyIndex(name);
375 if (idx == -1) {
376 if (QObject *obj = data->contextObject()) {
377 QVariant value;
378 if (readObjectProperty(data, obj, name, &value))
379 return value;
380 }
381
382 if (parentContext())
383 return parentContext()->contextProperty(name);
384 } else {
385 if (idx >= d->numPropertyValues())
386 return QVariant::fromValue(data->idValue(idx - d->numPropertyValues()));
387 else
388 return d->propertyValue(idx);
389 }
390
391 return QVariant();
392}
393
394/*!
395 Returns the name of \a object in this context, or an empty string if \a object
396 is not named in the context. Objects are named by \l setContextProperty(), or
397 as properties of a context object, or by ids in the case of QML created
398 contexts.
399
400 If the object has multiple names, the first is returned.
401
402 In contrast to \l contextProperty(), this method does not traverse the
403 context hierarchy. If the name is not found in the current context, an empty
404 String is returned.
405
406 \sa contextProperty(), objectForName()
407*/
408QString QQmlContext::nameForObject(const QObject *object) const
409{
410 Q_D(const QQmlContext);
411
412 return d->m_data->findObjectId(object);
413}
414
416 const QQmlRefPointer<QQmlContextData> &data, const QQmlContextPrivate *d,
417 const QString &name)
418{
419 if (const int propertyIndex = data->propertyIndex(name); propertyIndex >= 0) {
420 const int numPropertyValues = d ? d->numPropertyValues() : 0;
421 if (propertyIndex < numPropertyValues)
422 return qvariant_cast<QObject *>(d->propertyValue(propertyIndex));
423 return data->idValue(propertyIndex - numPropertyValues);
424 }
425
426 if (QObject *obj = data->contextObject()) {
427 QVariant result;
428 if (readObjectProperty(data, obj, name, &result))
429 return qvariant_cast<QObject *>(result);
430 }
431
432 return nullptr;
433}
434
435/*!
436 \since 6.2
437
438 Returns the object for a given \a name in this context. Returns nullptr if
439 \a name is not available in the context or if the value associated with
440 \a name is not a QObject. Objects are named by \l setContextProperty(),
441 or as properties of a context object, or by ids in the case of QML created
442 contexts. In contrast to \l contextProperty(), this method does not traverse
443 the context hierarchy. If the name is not found in the current context,
444 nullptr is returned.
445
446 \sa contextProperty(), nameForObject()
447*/
448QObject *QQmlContext::objectForName(const QString &name) const
449{
450 Q_D(const QQmlContext);
451 return objectForNameInQQmlContextData(d->m_data, d, name);
452}
453
454/*!
455 \since 6.11
456
457 Searches this context and its children recursively for an object with
458 ID \a id. If such an object is found, the object is returned. Otherwise
459 returns \nullptr.
460
461 There can only be one object with the given \a id in any given context,
462 but you can create many contexts within one document, for example with
463 views and delegates. Each of those contexts can contain an object with
464 the given \a id. Only the first one found is returned here. The search
465 is conducted using breadth-first search.
466
467 \sa findObjectsRecursively(), objectForName(), childContexts()
468 */
469QObject *QQmlContext::findObjectRecursively(const QString &id) const
470{
471 Q_D(const QQmlContext);
472 QQueue<QQmlRefPointer<QQmlContextData>> contexts;
473 contexts.enqueue(d->m_data);
474
475 while (!contexts.isEmpty()) {
476 const QQmlRefPointer<QQmlContextData> context = contexts.dequeue();
477 const QQmlContext *c = context->publicContext();
478 if (QObject *found = objectForNameInQQmlContextData(context, c ? c->d_func() : nullptr, id))
479 return found;
480
481 for (auto child = context->childContexts(); child; child = child->nextChild())
482 contexts.enqueue(child);
483 }
484
485 return nullptr;
486}
487
488/*!
489 \since 6.11
490
491 Searches this context and its children recursively for objects with
492 ID \a id. Returns a list of these objects.
493
494 There can only be one object with the given \a id in any given context,
495 but you can create many contexts within one document, for example with
496 views and delegates. Each of those contexts can contain an object with
497 the given \a id.
498
499 \sa findObjectRecursively(), objectForName(), childContexts()
500 */
501QList<QObject *> QQmlContext::findObjectsRecursively(const QString &id) const
502{
503 Q_D(const QQmlContext);
504
505 QList<QObject *> result;
506 QQueue<QQmlRefPointer<QQmlContextData>> contexts;
507 contexts.enqueue(d->m_data);
508
509 while (!contexts.isEmpty()) {
510 const QQmlRefPointer<QQmlContextData> context = contexts.dequeue();
511 const QQmlContext *c = context->publicContext();
512 if (QObject *found = objectForNameInQQmlContextData(context, c ? c->d_func() : nullptr, id))
513 result.append(found);
514
515 for (auto child = context->childContexts(); child; child = child->nextChild())
516 contexts.enqueue(child);
517 }
518
519 return result;
520}
521
522/*!
523 Resolves the URL \a src relative to the URL of the
524 containing component.
525
526 \sa QQmlEngine::baseUrl(), setBaseUrl()
527*/
528QUrl QQmlContext::resolvedUrl(const QUrl &src) const
529{
530 Q_D(const QQmlContext);
531 return d->m_data->resolvedUrl(src);
532}
533
534/*!
535 Explicitly sets the url resolvedUrl() will use for relative references to \a baseUrl.
536
537 Calling this function will override the url of the containing
538 component used by default.
539
540 \sa resolvedUrl()
541*/
542void QQmlContext::setBaseUrl(const QUrl &baseUrl)
543{
544 Q_D(QQmlContext);
545 d->m_data->setBaseUrl(baseUrl);
546 d->m_data->setBaseUrlString(baseUrl.toString());
547}
548
549/*!
550 Returns the base url of the component, or the containing component
551 if none is set.
552*/
553QUrl QQmlContext::baseUrl() const
554{
555 Q_D(const QQmlContext);
556 return d->m_data->baseUrl();
557}
558
559/*!
560 * \internal
561 */
562QJSValue QQmlContext::importedScript(const QString &name) const
563{
564 Q_D(const QQmlContext);
565
566 QV4::ExecutionEngine *v4 = engine()->handle();
567 QQmlTypeNameCache::Result r = d->m_data->imports()->query(name, v4->typeLoader());
568 QV4::Scope scope(v4);
569 QV4::ScopedObject scripts(scope, d->m_data->importedScripts());
570 return scripts ? QJSValuePrivate::fromReturnedValue(scripts->get(r.scriptIndex))
571 : QJSValue(QJSValue::UndefinedValue);
572}
573
574qsizetype QQmlContextPrivate::context_count(QQmlListProperty<QObject> *prop)
575{
576 QQmlContext *context = static_cast<QQmlContext*>(prop->object);
577 QQmlContextPrivate *d = QQmlContextPrivate::get(context);
578 int contextProperty = (int)(quintptr)prop->data;
579
580 if (d->propertyValue(contextProperty).userType() != qMetaTypeId<QList<QObject*> >())
581 return 0;
582 else
583 return ((const QList<QObject> *)d->propertyValue(contextProperty).constData())->size();
584}
585
586QObject *QQmlContextPrivate::context_at(QQmlListProperty<QObject> *prop, qsizetype index)
587{
588 QQmlContext *context = static_cast<QQmlContext*>(prop->object);
589 QQmlContextPrivate *d = QQmlContextPrivate::get(context);
590 int contextProperty = (int)(quintptr)prop->data;
591
592 if (d->propertyValue(contextProperty).userType() != qMetaTypeId<QList<QObject*> >())
593 return nullptr;
594 else
595 return ((const QList<QObject*> *)d->propertyValue(contextProperty).constData())->at(index);
596}
597
598void QQmlContextPrivate::dropDestroyedQObject(const QString &name, QObject *destroyed)
599{
600 if (!m_data->isValid())
601 return;
602
603 const int idx = m_data->propertyIndex(name);
604 Q_ASSERT(idx >= 0);
605 if (qvariant_cast<QObject *>(propertyValue(idx)) != destroyed)
606 return;
607
608 setPropertyValue(idx, QVariant::fromValue<QObject *>(nullptr));
609 QMetaObject::activate(q_func(), notifyIndex(), idx, nullptr);
610}
611
613{
614 m_data->emitDestruction();
615}
616
617void QQmlContextPrivate::setContextProperty(const QString &name, const QVariant &value)
618{
619 Q_Q(QQmlContext);
620
621 if (notifyIndex() == -1)
622 setNotifyIndex(QMetaObjectPrivate::absoluteSignalCount(&QQmlContext::staticMetaObject));
623
624 int idx = m_data->propertyIndex(name);
625 if (idx == -1) {
626 m_data->addPropertyNameAndIndex(name, m_data->numIdValues() + numPropertyValues());
627 appendPropertyValue(value);
628 m_data->refreshExpressions();
629 } else {
630 setPropertyValue(idx, value);
631 QMetaObject::activate(q, notifyIndex(), idx, nullptr);
632 }
633
634 if (auto *obj = qvariant_cast<QObject *>(value)) {
635 QObject::connect(obj, &QObject::destroyed, q, [this, name](QObject *destroyed) {
636 dropDestroyedQObject(name, destroyed);
637 });
638 }
639}
640
641// m_data is owned by the public context. When the public context is reset to nullptr, it will be
642// deref'd. It's OK to pass a half-created publicContext here. We will not dereference it during
643// construction.
644QQmlContextPrivate::QQmlContextPrivate(
645 QQmlContext *publicContext, const QQmlRefPointer<QQmlContextData> &parent,
646 QQmlEngine *engine) :
647 m_data(new QQmlContextData(QQmlContextData::OwnedByPublicContext, publicContext,
648 parent, engine))
649{
650 Q_ASSERT(publicContext != nullptr);
651}
652
653QT_END_NAMESPACE
654
655#include "moc_qqmlcontext.cpp"
void dropDestroyedQObject(const QString &name, QObject *destroyed)
void setNotifyIndex(int notifyIndex)
int notifyIndex() const
int numPropertyValues() const
Q_QML_AUTOTEST_EXPORT void setContextProperty(const QString &name, const QVariant &value)
Combined button and popup list for selecting options.
static bool readObjectProperty(const QQmlRefPointer< QQmlContextData > &data, QObject *object, const QString &name, QVariant *target)
static QObject * objectForNameInQQmlContextData(const QQmlRefPointer< QQmlContextData > &data, const QQmlContextPrivate *d, const QString &name)