Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
QQmlComponent Class Reference

The QQmlComponent class encapsulates a QML component definition. More...

#include <qqmlcomponent.h>

+ Inheritance diagram for QQmlComponent:
+ Collaboration diagram for QQmlComponent:

Public Types

enum  CompilationMode { PreferSynchronous , Asynchronous }
 Specifies whether the QQmlComponent should load the component immediately, or asynchonously. More...
 
enum  Status { Null , Ready , Loading , Error }
 \qmltype Component \instantiates QQmlComponent\inqmlmodule QtQml More...
 

Public Slots

void loadUrl (const QUrl &url)
 Load the QQmlComponent from the provided url.
 
void loadUrl (const QUrl &url, CompilationMode mode)
 Load the QQmlComponent from the provided url.
 
void loadFromModule (QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode=PreferSynchronous)
 Load the QQmlComponent for typeName in the module uri.
 
void setData (const QByteArray &, const QUrl &baseUrl)
 Sets the QQmlComponent to use the given QML data.
 
- Public Slots inherited from QObject
void deleteLater ()
 \threadsafe
 

Signals

void statusChanged (QQmlComponent::Status)
 Emitted whenever the component's status changes.
 
void progressChanged (qreal)
 Emitted whenever the component's loading progress changes.
 
- Signals inherited from QObject
void destroyed (QObject *=nullptr)
 This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.
 
void objectNameChanged (const QString &objectName, QPrivateSignal)
 This signal is emitted after the object's name has been changed.
 

Public Member Functions

 QQmlComponent (QObject *parent=nullptr)
 
 QQmlComponent (QQmlEngine *, QObject *parent=nullptr)
 Create a QQmlComponent with no data and give it the specified engine and parent.
 
 QQmlComponent (QQmlEngine *, const QString &fileName, QObject *parent=nullptr)
 Create a QQmlComponent from the given fileName and give it the specified parent and engine.
 
 QQmlComponent (QQmlEngine *, const QString &fileName, CompilationMode mode, QObject *parent=nullptr)
 Create a QQmlComponent from the given fileName and give it the specified parent and engine.
 
 QQmlComponent (QQmlEngine *, const QUrl &url, QObject *parent=nullptr)
 Create a QQmlComponent from the given url and give it the specified parent and engine.
 
 QQmlComponent (QQmlEngine *, const QUrl &url, CompilationMode mode, QObject *parent=nullptr)
 Create a QQmlComponent from the given url and give it the specified parent and engine.
 
 QQmlComponent (QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QObject *parent=nullptr)
 Create a QQmlComponent from the given uri and typeName and give it the specified parent and engine.
 
 QQmlComponent (QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, CompilationMode mode, QObject *parent=nullptr)
 Create a QQmlComponent from the given uri and typeName and give it the specified parent and engine.
 
 ~QQmlComponent () override
 Destruct the QQmlComponent.
 
Status status () const
 
bool isNull () const
 Returns true if status() == QQmlComponent::Null.
 
bool isReady () const
 Returns true if status() == QQmlComponent::Ready.
 
bool isError () const
 Returns true if status() == QQmlComponent::Error.
 
bool isLoading () const
 Returns true if status() == QQmlComponent::Loading.
 
bool isBound () const
 Returns true if the component was created in a QML files that specifies {pragma ComponentBehavior: Bound}, otherwise returns false.
 
QList< QQmlErrorerrors () const
 Returns the list of errors that occurred during the last compile or create operation.
 
Q_INVOKABLE QString errorString () const
 \qmlmethod string Component::errorString()
 
qreal progress () const
 
QUrl url () const
 
virtual QObjectcreate (QQmlContext *context=nullptr)
 Create an object instance from this component, within the specified context.
 
QObjectcreateWithInitialProperties (const QVariantMap &initialProperties, QQmlContext *context=nullptr)
 Create an object instance of this component, within the specified context, and initialize its top-level properties with initialProperties.
 
void setInitialProperties (QObject *component, const QVariantMap &properties)
 Set top-level properties of the component.
 
virtual QObjectbeginCreate (QQmlContext *)
 Create an object instance from this component, within the specified context.
 
virtual void completeCreate ()
 This method provides advanced control over component instance creation.
 
void create (QQmlIncubator &, QQmlContext *context=nullptr, QQmlContext *forContext=nullptr)
 Create an object instance from this component using the provided incubator.
 
QQmlContextcreationContext () const
 Returns the QQmlContext the component was created in.
 
QQmlEngineengine () const
 Returns the QQmlEngine of this component.
 
- Public Member Functions inherited from QObject
Q_INVOKABLE QObject (QObject *parent=nullptr)
 Constructs an object with parent object parent.
 
virtual ~QObject ()
 Destroys the object, deleting all its child objects.
 
virtual bool event (QEvent *event)
 This virtual function receives events to an object and should return true if the event e was recognized and processed.
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 Filters events if this object has been installed as an event filter for the watched object.
 
QString objectName () const
 
Q_WEAK_OVERLOAD void setObjectName (const QString &name)
 Sets the object's name to name.
 
void setObjectName (QAnyStringView name)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
QBindable< QStringbindableObjectName ()
 
bool isWidgetType () const
 Returns true if the object is a widget; otherwise returns false.
 
bool isWindowType () const
 Returns true if the object is a window; otherwise returns false.
 
bool isQuickItemType () const
 Returns true if the object is a QQuickItem; otherwise returns false.
 
bool signalsBlocked () const noexcept
 Returns true if signals are blocked; otherwise returns false.
 
bool blockSignals (bool b) noexcept
 If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it).
 
QThreadthread () const
 Returns the thread in which the object lives.
 
bool moveToThread (QThread *thread QT6_DECL_NEW_OVERLOAD_TAIL)
 Changes the thread affinity for this object and its children and returns true on success.
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 This is an overloaded function that will start a timer of type timerType and a timeout of interval milliseconds.
 
int startTimer (std::chrono::nanoseconds time, Qt::TimerType timerType=Qt::CoarseTimer)
 
void killTimer (int id)
 Kills the timer with timer identifier, id.
 
void killTimer (Qt::TimerId id)
 
template<typename T >
findChild (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns the child of this object that can be cast into type T and that is called name, or \nullptr if there is no such object.
 
template<typename T >
QList< T > findChildren (QAnyStringView aName, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 Returns all children of this object with the given name that can be cast to type T, or an empty list if there are no such objects.
 
template<typename T >
findChild (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename T >
QList< T > findChildren (Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
const QObjectListchildren () const
 Returns a list of child objects.
 
void setParent (QObject *parent)
 Makes the object a child of parent.
 
void installEventFilter (QObject *filterObj)
 Installs an event filter filterObj on this object.
 
void removeEventFilter (QObject *obj)
 Removes an event filter object obj from this object.
 
QMetaObject::Connection connect (const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type=Qt::AutoConnection) const
 
bool disconnect (const char *signal=nullptr, const QObject *receiver=nullptr, const char *member=nullptr) const
 
bool disconnect (const QObject *receiver, const char *member=nullptr) const
 
void dumpObjectTree () const
 Dumps a tree of children to the debug output.
 
void dumpObjectInfo () const
 Dumps information about signal connections, etc.
 
bool setProperty (const char *name, const QVariant &value)
 Sets the value of the object's name property to value.
 
bool setProperty (const char *name, QVariant &&value)
 
QVariant property (const char *name) const
 Returns the value of the object's name property.
 
QList< QByteArraydynamicPropertyNames () const
 
QBindingStoragebindingStorage ()
 
const QBindingStoragebindingStorage () const
 
QObjectparent () const
 Returns a pointer to the parent object.
 
bool inherits (const char *classname) const
 Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
 

Static Public Member Functions

static QQmlComponentAttachedqmlAttachedProperties (QObject *)
 
- Static Public Member Functions inherited from QObject
static QMetaObject::Connection connect (const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType=Qt::AutoConnection)
 \threadsafe
 
static QMetaObject::Connection connect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::ContextTypeForFunctor< Func2 >::ContextType *context, Func2 &&slot, Qt::ConnectionType type=Qt::AutoConnection)
 
template<typename Func1 , typename Func2 >
static QMetaObject::Connection connect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, Func2 &&slot)
 
static bool disconnect (const QObject *sender, const char *signal, const QObject *receiver, const char *member)
 \threadsafe
 
static bool disconnect (const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &member)
 
static bool disconnect (const QMetaObject::Connection &)
 Disconnect a connection.
 
template<typename Func1 , typename Func2 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const typename QtPrivate::FunctionPointer< Func2 >::Object *receiver, Func2 slot)
 
template<typename Func1 >
static bool disconnect (const typename QtPrivate::FunctionPointer< Func1 >::Object *sender, Func1 signal, const QObject *receiver, void **zero)
 

Protected Member Functions

 QQmlComponent (QQmlComponentPrivate &dd, QObject *parent)
 
Q_INVOKABLE QObjectcreateObject (QObject *parent=nullptr, const QVariantMap &properties={})
 
Q_INVOKABLE void incubateObject (QQmlV4FunctionPtr)
 \qmlmethod object Component::incubateObject(QtObject parent, object properties, enumeration mode)
 
- Protected Member Functions inherited from QObject
QObjectsender () const
 Returns a pointer to the object that sent the signal, if called in a slot activated by a signal; otherwise it returns \nullptr.
 
int senderSignalIndex () const
 
int receivers (const char *signal) const
 Returns the number of receivers connected to the signal.
 
bool isSignalConnected (const QMetaMethod &signal) const
 
virtual void timerEvent (QTimerEvent *event)
 This event handler can be reimplemented in a subclass to receive timer events for the object.
 
virtual void childEvent (QChildEvent *event)
 This event handler can be reimplemented in a subclass to receive child events.
 
virtual void customEvent (QEvent *event)
 This event handler can be reimplemented in a subclass to receive custom events.
 
virtual void connectNotify (const QMetaMethod &signal)
 
virtual void disconnectNotify (const QMetaMethod &signal)
 
 QObject (QObjectPrivate &dd, QObject *parent=nullptr)
 

Properties

qreal progress
 \qmlproperty real Component::progress The progress of loading the component, from 0.0 (nothing loaded) to 1.0 (finished).
 
Status status
 \qmlproperty enumeration Component::status
 
QUrl url
 \qmlproperty url Component::url The component URL.
 
- Properties inherited from QObject
QString objectName
 the name of this object
 

Friends

class QQmlTypeData
 
class QQmlObjectCreator
 

Additional Inherited Members

- Protected Attributes inherited from QObject
QScopedPointer< QObjectDatad_ptr
 

Detailed Description

The QQmlComponent class encapsulates a QML component definition.

Since
5.0 \inmodule QtQml

Components are reusable, encapsulated QML types with well-defined interfaces.

A QQmlComponent instance can be created from a QML file. For example, if there is a main.qml file like this:

\qml import QtQuick 2.0

Item { width: 200 height: 200 } \endqml

The following code loads this QML file as a component, creates an instance of this component using create(), and then queries the \l Item's \l {Item::}{width} value:

int width = item->width(); // width = 200
\inmodule QtCore
Definition qobject.h:103
The QQmlComponent class encapsulates a QML component definition.
QQmlEngine * engine() const
Returns the QQmlEngine of this component.
The QQmlEngine class provides an environment for instantiating QML components.
Definition qqmlengine.h:57
The QQuickItem class provides the most basic of all visual items in \l {Qt Quick}.
Definition qquickitem.h:63
static QUrl fromLocalFile(const QString &localfile)
Returns a QUrl representation of localFile, interpreted as a local file.
Definition qurl.cpp:3367
GLint GLsizei width
static qreal component(const QPointF &point, unsigned int i)
QQuickItem * qobject_cast< QQuickItem * >(QObject *o)
Definition qquickitem.h:492
QGraphicsItem * item

To create instances of a component in code where a QQmlEngine instance is not available, you can use \l qmlContext() or \l qmlEngine(). For example, in the scenario below, child items are being created within a QQuickItem subclass:

void MyCppItem::init()
{
// Or:
// QQmlEngine *engine = qmlContext(this)->engine();
childItem->setParentItem(this);
}
QQmlEngine * qmlEngine(const QObject *obj)
Definition qqml.cpp:80

Note that these functions will return null when called inside the constructor of a QObject subclass, as the instance will not yet have a context nor engine.

Definition at line 31 of file qqmlcomponent.h.

Member Enumeration Documentation

◆ CompilationMode

Specifies whether the QQmlComponent should load the component immediately, or asynchonously.

\value PreferSynchronous Prefer loading/compiling the component immediately, blocking the thread. This is not always possible; for example, remote URLs will always load asynchronously. \value Asynchronous Load/compile the component in a background thread.

Enumerator
PreferSynchronous 
Asynchronous 

Definition at line 41 of file qqmlcomponent.h.

◆ Status

\qmltype Component \instantiates QQmlComponent\inqmlmodule QtQml

Encapsulates a QML component definition.

Components are reusable, encapsulated QML types with well-defined interfaces.

Components are often defined by \l {{QML Documents}}{component files} - that is, .qml files. The Component type essentially allows QML components to be defined inline, within a \l {QML Documents}{QML document}, rather than as a separate QML file. This may be useful for reusing a small component within a QML file, or for defining a component that logically belongs with other QML components within a file.

For example, here is a component that is used by multiple \l Loader objects. It contains a single item, a \l Rectangle:

import QtQuick
Item {
width: 100; height: 100
Component {
id: redSquare
Rectangle {
color: "red"
width: 10
height: 10
}
}
Loader { sourceComponent: redSquare }
Loader { sourceComponent: redSquare; x: 20 }
}

Notice that while a \l Rectangle by itself would be automatically rendered and displayed, this is not the case for the above rectangle because it is defined inside a Component. The component encapsulates the QML types within, as if they were defined in a separate QML file, and is not loaded until requested (in this case, by the two \l Loader objects). Because Component is not derived from Item, you cannot anchor anything to it.

Defining a Component is similar to defining a \l {QML Documents}{QML document}. A QML document has a single top-level item that defines the behavior and properties of that component, and cannot define properties or behavior outside of that top-level item. In the same way, a Component definition contains a single top level item (which in the above example is a \l Rectangle) and cannot define any data outside of this item, with the exception of an id (which in the above example is redSquare).

The Component type is commonly used to provide graphical components for views. For example, the ListView::delegate property requires a Component to specify how each list item is to be displayed.

Component objects can also be created dynamically using \l{QtQml::Qt::createComponent()}{Qt.createComponent()}.

Enumerator
Null 
Ready 
Loading 
Error 

Definition at line 56 of file qqmlcomponent.h.

Constructor & Destructor Documentation

◆ QQmlComponent() [1/9]

QQmlComponent::QQmlComponent ( QObject * parent = nullptr)

Definition at line 434 of file qqmlcomponent.cpp.

◆ QQmlComponent() [2/9]

QQmlComponent::QQmlComponent ( QQmlEngine * engine,
QObject * parent = nullptr )

Create a QQmlComponent with no data and give it the specified engine and parent.

Set the data with setData().

Definition at line 576 of file qqmlcomponent.cpp.

References QObject::connect(), d, QObject::destroyed(), and engine().

+ Here is the call graph for this function:

◆ QQmlComponent() [3/9]

QQmlComponent::QQmlComponent ( QQmlEngine * engine,
const QString & fileName,
QObject * parent = nullptr )

Create a QQmlComponent from the given fileName and give it the specified parent and engine.

See also
loadUrl()

Definition at line 653 of file qqmlcomponent.cpp.

◆ QQmlComponent() [4/9]

QQmlComponent::QQmlComponent ( QQmlEngine * engine,
const QString & fileName,
CompilationMode mode,
QObject * parent = nullptr )

Create a QQmlComponent from the given fileName and give it the specified parent and engine.

If mode is \l Asynchronous, the component will be loaded and compiled asynchronously.

See also
loadUrl()

Definition at line 666 of file qqmlcomponent.cpp.

References d, fileName, QUrl::fromLocalFile(), and QDir::isAbsolutePath().

+ Here is the call graph for this function:

◆ QQmlComponent() [5/9]

QQmlComponent::QQmlComponent ( QQmlEngine * engine,
const QUrl & url,
QObject * parent = nullptr )

Create a QQmlComponent from the given url and give it the specified parent and engine.

url-note

See also
loadUrl()

Definition at line 595 of file qqmlcomponent.cpp.

◆ QQmlComponent() [6/9]

QQmlComponent::QQmlComponent ( QQmlEngine * engine,
const QUrl & url,
CompilationMode mode,
QObject * parent = nullptr )

Create a QQmlComponent from the given url and give it the specified parent and engine.

If mode is \l Asynchronous, the component will be loaded and compiled asynchronously.

url-note

See also
loadUrl()

Definition at line 609 of file qqmlcomponent.cpp.

References d, and url.

◆ QQmlComponent() [7/9]

QQmlComponent::QQmlComponent ( QQmlEngine * engine,
QAnyStringView uri,
QAnyStringView typeName,
QObject * parent = nullptr )
explicit

Create a QQmlComponent from the given uri and typeName and give it the specified parent and engine.

If possible, the component will be loaded synchronously.

See also
loadFromModule()
Since
6.5 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 626 of file qqmlcomponent.cpp.

◆ QQmlComponent() [8/9]

QQmlComponent::QQmlComponent ( QQmlEngine * engine,
QAnyStringView uri,
QAnyStringView typeName,
CompilationMode mode,
QObject * parent = nullptr )
explicit

Create a QQmlComponent from the given uri and typeName and give it the specified parent and engine.

If mode is \l Asynchronous, the component will be loaded and compiled asynchronously.

See also
loadFromModule()
Since
6.5 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 641 of file qqmlcomponent.cpp.

References loadFromModule(), and typeName.

+ Here is the call graph for this function:

◆ ~QQmlComponent()

QQmlComponent::~QQmlComponent ( )
override

Destruct the QQmlComponent.

Definition at line 442 of file qqmlcomponent.cpp.

References d, isError(), and qWarning.

+ Here is the call graph for this function:

◆ QQmlComponent() [9/9]

QQmlComponent::QQmlComponent ( QQmlComponentPrivate & dd,
QObject * parent )
protected

Definition at line 888 of file qqmlcomponent.cpp.

Member Function Documentation

◆ beginCreate()

QObject * QQmlComponent::beginCreate ( QQmlContext * context)
virtual

Create an object instance from this component, within the specified context.

Returns \nullptr if creation failed.

Note
This method provides advanced control over component instance creation. In general, programmers should use QQmlComponent::create() to create object instances.

When QQmlComponent constructs an instance, it occurs in three steps:

\list 1

QQmlComponent::beginCreate() differs from QQmlComponent::create() in that it only performs step 1. QQmlComponent::completeCreate() must be called to complete steps 2 and 3.

This breaking point is sometimes useful when using attached properties to communicate information to an instantiated component, as it allows their initial values to be configured before property bindings take effect.

The ownership of the returned object instance is transferred to the caller.

Note
The categorization of bindings into constant values and actual bindings is intentionally unspecified and may change between versions of Qt and depending on whether and how you are using \l{qmlcachegen}. You should not rely on any particular binding to be evaluated either before or after beginCreate() returns. For example a constant expression like {MyType.EnumValue} may be recognized as such at compile time or deferred to be executed as binding. The same holds for constant expressions like {-(5)} or {"a" + " constant string"}.
See also
completeCreate(), QQmlEngine::ObjectOwnership

Definition at line 1013 of file qqmlcomponent.cpp.

References context, d, QQmlContextData::get(), and Q_ASSERT.

Referenced by QQuickMenuPrivate::beginCreateItem(), QQuickMenuBarPrivate::beginCreateItem(), QQuickSelectionRectanglePrivate::createHandle(), QQuickSplitViewPrivate::createHandleItem(), QQuickDialogButtonBoxPrivate::createStandardButton(), and QQuickListViewPrivate::getSectionItem().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ completeCreate()

void QQmlComponent::completeCreate ( )
virtual

This method provides advanced control over component instance creation.

In general, programmers should use QQmlComponent::create() to create a component.

This function completes the component creation begun with QQmlComponent::beginCreate() and must be called afterwards.

See also
beginCreate()

Definition at line 1248 of file qqmlcomponent.cpp.

References d.

Referenced by QQuickMenuPrivate::completeCreateItem(), QQuickMenuBarPrivate::completeCreateItem(), QQuickSelectionRectanglePrivate::createHandle(), QQuickSplitViewPrivate::createHandleItem(), QQuickDialogButtonBoxPrivate::createStandardButton(), and QQuickListViewPrivate::getSectionItem().

+ Here is the caller graph for this function:

◆ create() [1/2]

QObject * QQmlComponent::create ( QQmlContext * context = nullptr)
virtual

Create an object instance from this component, within the specified context.

Returns \nullptr if creation failed.

If context is \nullptr (the default), it will create the instance in the \l {QQmlEngine::rootContext()}{root context} of the engine.

The ownership of the returned object instance is transferred to the caller.

If the object being created from this component is a visual item, it must have a visual parent, which can be set by calling QQuickItem::setParentItem(). See \l {Concepts - Visual Parent in Qt Quick} for more details.

See also
QQmlEngine::ObjectOwnership

Definition at line 909 of file qqmlcomponent.cpp.

References context, and d.

Referenced by QQuickLoaderPrivate::_q_sourceLoaded(), QQuickPathViewPrivate::createHighlight(), QQuickStackElement::load(), and QmlJSDebugger::ObjectCreator::tryCreateObject().

+ Here is the caller graph for this function:

◆ create() [2/2]

void QQmlComponent::create ( QQmlIncubator & incubator,
QQmlContext * context = nullptr,
QQmlContext * forContext = nullptr )

Create an object instance from this component using the provided incubator.

context specifies the context within which to create the object instance.

If context is \nullptr (by default), it will create the instance in the engine's \l {QQmlEngine::rootContext()}{root context}.

forContext specifies a context that this object creation depends upon. If the forContext is being created asynchronously, and the \l QQmlIncubator::IncubationMode is \l QQmlIncubator::AsynchronousIfNested, this object will also be created asynchronously. If forContext is \nullptr (by default), the context will be used for this decision.

The created object and its creation status are available via the incubator.

See also
QQmlIncubator

Definition at line 1444 of file qqmlcomponent.cpp.

References QQmlIncubator::clear(), context, d, QQmlContextData::get(), QQmlEnginePrivate::get(), QQmlEnginePrivate::incubate(), isReady(), QQmlObjectCreator, and qWarning.

+ Here is the call graph for this function:

◆ createObject()

QObject * QQmlComponent::createObject ( QObject * parent = nullptr,
const QVariantMap & properties = {} )
protected

Definition at line 1845 of file qqmlcomponent.cpp.

References QQmlComponentPrivate::CreateWarnAboutRequiredProperties, creationContext(), d, QQmlData::explicitIndestructibleSet, QQmlData::get(), QQmlData::indestructible, QObject::parent(), properties, and Q_ASSERT.

+ Here is the call graph for this function:

◆ createWithInitialProperties()

QObject * QQmlComponent::createWithInitialProperties ( const QVariantMap & initialProperties,
QQmlContext * context = nullptr )

Create an object instance of this component, within the specified context, and initialize its top-level properties with initialProperties.

\omit TODO: also mention errorString() when QTBUG-93239 is fixed \endomit

If any of the initialProperties cannot be set, a warning is issued. If there are unset required properties, the object creation fails and returns nullptr, in which case \l isError() will return true.

See also
QQmlComponent::create
Since
5.14

Definition at line 930 of file qqmlcomponent.cpp.

References context, and d.

◆ creationContext()

QQmlContext * QQmlComponent::creationContext ( ) const

Returns the QQmlContext the component was created in.

This is only valid for components created directly from QML.

Definition at line 730 of file qqmlcomponent.cpp.

References d, and qmlContext().

Referenced by QQuickLoaderPrivate::_q_sourceLoaded(), QQuickMenuPrivate::beginCreateItem(), QQuickMenuBarPrivate::beginCreateItem(), QQuickSplitViewPrivate::createHandleItem(), QQuickPathViewPrivate::createHighlight(), createObject(), QQuickDialogButtonBoxPrivate::createStandardButton(), QQuickListViewPrivate::getSectionItem(), incubateObject(), and QQuickStackElement::load().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ engine()

QQmlEngine * QQmlComponent::engine ( ) const

Returns the QQmlEngine of this component.

Since
5.12

Definition at line 744 of file qqmlcomponent.cpp.

References d.

Referenced by QQmlComponent(), and qmlAttachedProperties().

+ Here is the caller graph for this function:

◆ errors()

QList< QQmlError > QQmlComponent::errors ( ) const

Returns the list of errors that occurred during the last compile or create operation.

An empty list is returned if isError() is not set.

Definition at line 829 of file qqmlcomponent.cpp.

References d, QList< T >::emplaceBack(), errors(), and QList< T >::reserve().

Referenced by QQuickLoaderPrivate::_q_sourceLoaded(), QQuickSwipePrivate::createBehindItem(), errors(), and QQmlDelegateModelPrivate::incubatorStatusChanged().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ errorString()

QString QQmlComponent::errorString ( ) const

\qmlmethod string Component::errorString()

Returns a human-readable description of any error.

The string includes the file, location, and description of each error. If multiple errors are present, they are separated by a newline character.

If no errors are present, an empty string is returned.

errorString() is only meant as a way to get the errors from QML side.

Definition at line 854 of file qqmlcomponent.cpp.

References d, QQmlError::description(), isError(), QQmlError::line(), QString::number(), ret, QUrl::toString(), and QQmlError::url().

Referenced by QQuickStackElement::load(), QQmlPreviewHandler::loadUrl(), and QQuickFolderBreadcrumbBarPrivate::repopulate().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ incubateObject()

void QQmlComponent::incubateObject ( QQmlV4FunctionPtr args)
protected

\qmlmethod object Component::incubateObject(QtObject parent, object properties, enumeration mode)

Creates an incubator for an instance of this component. Incubators allow new component instances to be instantiated asynchronously and do not cause freezes in the UI.

The parent argument specifies the parent the created instance will have. Omitting the parameter or passing null will create an object with no parent. In this case, a reference to the created object must be held so that it is not destroyed by the garbage collector.

The properties argument is specified as a map of property-value items which will be set on the created object during its construction. mode may be Qt.Synchronous or Qt.Asynchronous, and controls whether the instance is created synchronously or asynchronously. The default is asynchronous. In some circumstances, even if Qt.Synchronous is specified, the incubator may create the object asynchronously. This happens if the component calling incubateObject() is itself being created asynchronously.

All three arguments are optional.

If successful, the method returns an incubator, otherwise null. The incubator has the following properties:

\list

  • status - The status of the incubator. Valid values are Component.Ready, Component.Loading and Component.Error.
  • object - The created object instance. Will only be available once the incubator is in the Ready status.
  • onStatusChanged - Specifies a callback function to be invoked when the status changes. The status is passed as a parameter to the callback.
  • {forceCompletion()} - Call to complete incubation synchronously. \endlist

The following example demonstrates how to use an incubator:

\qml const component = Qt.createComponent("Button.qml");

const incubator = component.incubateObject(parent, { x: 10, y: 10 }); if (incubator.status !== Component.Ready) { incubator.onStatusChanged = function(status) { if (status === Component.Ready) { print("Object", incubator.object, "is now ready!"); } }; } else { print("Object", incubator.object, "is ready immediately!"); } \endqml

Dynamically created instances can be deleted with the destroy() method. See \l {Dynamic QML Object Creation from JavaScript} for more information.

See also
createObject()

Definition at line 1918 of file qqmlcomponent.cpp.

References QV4::MemoryManager::allocate(), args, QV4::Value::as(), QQmlIncubator::Asynchronous, QQmlIncubator::AsynchronousIfNested, create(), creationContext(), d, QV4::Scope::engine, QQmlComponentExtension::incubationProto, QList< T >::length(), QV4::EngineBase::memoryManager, QV4::Encode::null(), QQmlIncubator::Null, QObject::parent(), Q_ASSERT, Q_UNUSED, QV4::ExecutionEngine::qmlContext(), qmlWarning(), QQmlIncubator::status(), tr, QV4::Value::undefinedValue(), and QV4::PersistentValue::value().

+ Here is the call graph for this function:

◆ isBound()

bool QQmlComponent::isBound ( ) const

Returns true if the component was created in a QML files that specifies {pragma ComponentBehavior: Bound}, otherwise returns false.

Since
6.5

Definition at line 535 of file qqmlcomponent.cpp.

References d.

Referenced by QQuickListViewPrivate::getSectionItem().

+ Here is the caller graph for this function:

◆ isError()

bool QQmlComponent::isError ( ) const

Returns true if status() == QQmlComponent::Error.

Definition at line 516 of file qqmlcomponent.cpp.

References Error, and status.

Referenced by ~QQmlComponent(), errorString(), and QQuickStackElement::load().

+ Here is the caller graph for this function:

◆ isLoading()

bool QQmlComponent::isLoading ( ) const

Returns true if status() == QQmlComponent::Loading.

Definition at line 524 of file qqmlcomponent.cpp.

References Loading, and status.

Referenced by QQuickViewPrivate::execute(), QQuickWidgetPrivate::execute(), QQuickViewPrivate::execute(), QQuickLoaderPrivate::load(), QQuickStackElement::load(), and QQuick3DLoader::setAsynchronous().

+ Here is the caller graph for this function:

◆ isNull()

bool QQmlComponent::isNull ( ) const

Returns true if status() == QQmlComponent::Null.

Definition at line 500 of file qqmlcomponent.cpp.

References Null, and status.

◆ isReady()

bool QQmlComponent::isReady ( ) const

Returns true if status() == QQmlComponent::Ready.

Definition at line 508 of file qqmlcomponent.cpp.

References Ready, and status.

Referenced by create(), and QQmlPreviewHandler::rerun().

+ Here is the caller graph for this function:

◆ loadFromModule

void QQmlComponent::loadFromModule ( QAnyStringView uri,
QAnyStringView typeName,
QQmlComponent::CompilationMode mode = PreferSynchronous )
slot

Load the QQmlComponent for typeName in the module uri.

If the type is implemented via a QML file, mode is used to load it. Types backed by C++ are always loaded synchronously.

component.loadFromModule("QtQuick", "Item");
// once the component is ready
std::unique_ptr<QObject> item(component.create());
Q_ASSERT(item->metaObject() == &QQuickItem::staticMetaObject);
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
Since
6.5
See also
loadUrl()

Definition at line 1333 of file qqmlcomponent.cpp.

References d, status, and typeName.

Referenced by QQmlComponent().

+ Here is the caller graph for this function:

◆ loadUrl [1/2]

void QQmlComponent::loadUrl ( const QUrl & url)
slot

Load the QQmlComponent from the provided url.

url-note

Definition at line 755 of file qqmlcomponent.cpp.

References d, and url.

◆ loadUrl [2/2]

void QQmlComponent::loadUrl ( const QUrl & url,
QQmlComponent::CompilationMode mode )
slot

Load the QQmlComponent from the provided url.

If mode is \l Asynchronous, the component will be loaded and compiled asynchronously.

url-note

Definition at line 767 of file qqmlcomponent.cpp.

References d, and url.

◆ progress()

qreal QQmlComponent::progress ( ) const

Definition at line 552 of file qqmlcomponent.cpp.

References d.

◆ progressChanged

void QQmlComponent::progressChanged ( qreal progress)
signal

Emitted whenever the component's loading progress changes.

progress will be the current progress between 0.0 (nothing loaded) and 1.0 (finished).

Referenced by setData().

+ Here is the caller graph for this function:

◆ qmlAttachedProperties()

QQmlComponentAttached * QQmlComponent::qmlAttachedProperties ( QObject * obj)
static

Definition at line 1295 of file qqmlcomponent.cpp.

References d, engine(), QQmlData::get(), QQmlEnginePrivate::get(), Q_ASSERT, and qmlEngine().

+ Here is the call graph for this function:

◆ setData

void QQmlComponent::setData ( const QByteArray & data,
const QUrl & url )
slot

Sets the QQmlComponent to use the given QML data.

If url is provided, it is used to set the component name and to provide a base path for items resolved by this component.

Definition at line 698 of file qqmlcomponent.cpp.

References d, emit, QQmlEnginePrivate::get(), progressChanged(), qWarning, status, statusChanged(), and url.

Referenced by QmlJSDebugger::ObjectCreator::run().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ setInitialProperties()

void QQmlComponent::setInitialProperties ( QObject * component,
const QVariantMap & properties )

Set top-level properties of the component.

This method provides advanced control over component instance creation. In general, programmers should use \l QQmlComponent::createWithInitialProperties to create a component.

Use this method after beginCreate and before completeCreate has been called. If a provided property does not exist, a warning is issued.

Since
5.14

Definition at line 1503 of file qqmlcomponent.cpp.

References component(), d, it, and properties.

Referenced by QQuickListViewPrivate::getSectionItem().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ status()

QQmlComponent::Status QQmlComponent::status ( ) const

Definition at line 483 of file qqmlcomponent.cpp.

References d, Error, Loading, Null, and Ready.

◆ statusChanged

void QQmlComponent::statusChanged ( QQmlComponent::Status status)
signal

Emitted whenever the component's status changes.

status will be the new status.

Referenced by QmlJSDebugger::ObjectCreator::ObjectCreator(), QQmlApplicationEnginePrivate::ensureLoadingFinishes(), QQuickStackElement::load(), QQmlPreviewHandler::loadUrl(), and setData().

+ Here is the caller graph for this function:

◆ url()

QUrl QQmlComponent::url ( ) const

Definition at line 879 of file qqmlcomponent.cpp.

References d.

Friends And Related Symbol Documentation

◆ QQmlObjectCreator

friend class QQmlObjectCreator
friend

Definition at line 117 of file qqmlcomponent.h.

Referenced by create().

◆ QQmlTypeData

friend class QQmlTypeData
friend

Definition at line 116 of file qqmlcomponent.h.

Property Documentation

◆ progress

QQmlComponent::progress
read

\qmlproperty real Component::progress The progress of loading the component, from 0.0 (nothing loaded) to 1.0 (finished).

The progress of loading the component, from 0.0 (nothing loaded) to 1.0 (finished).

Definition at line 36 of file qqmlcomponent.h.

Referenced by QQuick3DLoader::progress().

◆ status

QQmlComponent::status
read

\qmlproperty enumeration Component::status

This property holds the status of component loading. The status can be one of the following:

\value Component.Null no data is available for the component \value Component.Ready the component has been loaded, and can be used to create instances. \value Component.Loading the component is currently being loaded \value Component.Error an error occurred while loading the component. Calling \l errorString() will provide a human-readable description of any errors.

The component's current \l{QQmlComponent::Status} {status}.

Definition at line 37 of file qqmlcomponent.h.

Referenced by QQuickLoaderPrivate::computeStatus(), isError(), isLoading(), isNull(), isReady(), loadFromModule(), QQmlPreviewHandler::loadUrl(), setData(), and QQuick3DLoader::status().

◆ url

QQmlComponent::url
read

\qmlproperty url Component::url The component URL.

This is the URL that was used to construct the component.

The component URL. This is the URL passed to either the constructor, or the loadUrl(), or setData() methods.

Definition at line 38 of file qqmlcomponent.h.

Referenced by QQmlComponent(), loadUrl(), loadUrl(), and setData().


The documentation for this class was generated from the following files: