PySide6.QtQml.QQmlComponent¶
- class QQmlComponent¶
- The - QQmlComponentclass encapsulates a QML component definition. More…- Synopsis¶- Properties¶- Methods¶- def - __init__()
- def - create()
- def - createObject()
- def - engine()
- def - errorString()
- def - errors()
- def - isBound()
- def - isError()
- def - isLoading()
- def - isNull()
- def - isReady()
- def - progress()
- def - status()
- def - url()
 - Virtual methods¶- def - beginCreate()
- def - completeCreate()
- def - create()
 - Slots¶- def - loadFromModule()
- def - loadUrl()
- def - setData()
 - Signals¶
- def - statusChanged()
 - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - Detailed Description¶- Components are reusable, encapsulated QML types with well-defined interfaces. - A - QQmlComponentinstance can be created from a QML file. For example, if there is a- main.qmlfile like this:- The following code loads this QML file as a component, creates an instance of this component using - create(), and then queries the Item’s width value:- QQmlEngine *engine = new QQmlEngine; QQmlComponent component(engine, QUrl::fromLocalFile("main.qml")); QObject *myObject = component.create(); QQuickItem *item = qobject_cast<QQuickItem*>(myObject); int width = item->width(); // width = 200 - To create instances of a component in code where a - QQmlEngineinstance is not available, you can use- qmlContext()or- qmlEngine(). For example, in the scenario below, child items are being created within a QQuickItem subclass:- void MyCppItem::init() { QQmlEngine *engine = qmlEngine(this); // Or: // QQmlEngine *engine = qmlContext(this)->engine(); QQmlComponent component(engine, QUrl::fromLocalFile("MyItem.qml")); QQuickItem *childItem = qobject_cast<QQuickItem*>(component.create()); childItem->setParentItem(this); } - Note that these functions will return - nullwhen called inside the constructor of a QObject subclass, as the instance will not yet have a context nor engine.- Network Components¶- If the URL passed to - QQmlComponentis a network resource, or if the QML document references a network resource, the- QQmlComponenthas to fetch the network data before it is able to create objects. In this case, the- QQmlComponentwill have a- Loading- status. An application will have to wait until the component is- Readybefore calling- create().- The following example shows how to load a QML file from a network resource. After creating the - QQmlComponent, it tests whether the component is loading. If it is, it connects to the- statusChanged()signal and otherwise calls the- continueLoading()method directly. Note that- isLoading()may be false for a network component if the component has been cached and is ready immediately.- MyApplication::MyApplication() { // ... component = new QQmlComponent(engine, QUrl("http://www.example.com/main.qml")); if (component->isLoading()) { QObject::connect(component, &QQmlComponent::statusChanged, this, &MyApplication::continueLoading); } else { continueLoading(); } } void MyApplication::continueLoading() { if (component->isError()) { qWarning() << component->errors(); } else { QObject *myObject = component->create(); } } - class CompilationMode¶
- Specifies whether the - QQmlComponentshould load the component immediately, or asynchonously.- Constant - Description - QQmlComponent.PreferSynchronous - Prefer loading/compiling the component immediately, blocking the thread. This is not always possible; for example, remote URLs will always load asynchronously. - QQmlComponent.Asynchronous - Load/compile the component in a background thread. 
 - class Status¶
- Specifies the loading status of the - QQmlComponent.- Constant - Description - QQmlComponent.Null - This - QQmlComponenthas no data. Call- loadUrl()or- setData()to add QML content.- QQmlComponent.Ready - This - QQmlComponentis ready and- create()may be called.- QQmlComponent.Loading - This - QQmlComponentis loading network data.- QQmlComponent.Error - An error has occurred. Call - errors()to retrieve a list of- errors.
 - Note - Properties can be used directly when - from __feature__ import true_propertyis used or via accessor functions otherwise.- property progressᅟ: float¶
 - The progress of loading the component, from 0.0 (nothing loaded) to 1.0 (finished). - Access functions:
- Signal - progressChanged()
 
 - property statusᅟ: QQmlComponent.Status¶
 - The component’s current - status.- Access functions:
- Signal - statusChanged()
 
 - The component URL. This is the URL passed to either the constructor, or the - loadUrl(), or- setData()methods.- Access functions:
 - __init__(engine[, parent=None])
- Parameters:
- engine – - QQmlEngine
- parent – - QObject
 
 
 - Create a - QQmlComponentwith no data and give it the specified- engineand- parent. Set the data with- setData().- __init__(engine, fileName[, parent=None])
- Parameters:
- engine – - QQmlEngine
- fileName – str 
- parent – - QObject
 
 
 - Create a - QQmlComponentfrom the given- fileNameand give it the specified- parentand- engine.- See also - __init__(engine, url[, parent=None])
- Parameters:
- engine – - QQmlEngine
- url – - QUrl
- parent – - QObject
 
 
 - Create a - QQmlComponentfrom the given- urland give it the specified- parentand- engine.- Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile() when loading a file from the local filesystem. - Relative paths will be resolved against - baseUrl(), which is the current working directory unless specified.- See also - __init__(engine, fileName, mode[, parent=None])
- Parameters:
- engine – - QQmlEngine
- fileName – str 
- mode – - CompilationMode
- parent – - QObject
 
 
 - Create a - QQmlComponentfrom the given- fileNameand give it the specified- parentand- engine. If- modeis- Asynchronous, the component will be loaded and compiled asynchronously.- See also - __init__(engine, url, mode[, parent=None])
- Parameters:
- engine – - QQmlEngine
- url – - QUrl
- mode – - CompilationMode
- parent – - QObject
 
 
 - Create a - QQmlComponentfrom the given- urland give it the specified- parentand- engine. If- modeis- Asynchronous, the component will be loaded and compiled asynchronously.- Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile() when loading a file from the local filesystem. - Relative paths will be resolved against - baseUrl(), which is the current working directory unless specified.- See also - __init__(engine, uri, typeName[, parent=None])
- Parameters:
- engine – - QQmlEngine
- uri – str 
- typeName – str 
- parent – - QObject
 
 
 - Create a - QQmlComponentfrom the given- uriand- typeNameand give it the specified- parentand- engine. If possible, the component will be loaded synchronously.- This is an overloaded function. - See also - __init__(engine, uri, typeName, mode[, parent=None])
- Parameters:
- engine – - QQmlEngine
- uri – str 
- typeName – str 
- mode – - CompilationMode
- parent – - QObject
 
 
 - Create a - QQmlComponentfrom the given- uriand- typeNameand give it the specified- parentand- engine. If- modeis- Asynchronous, the component will be loaded and compiled asynchronously.- This is an overloaded function. - See also - beginCreate(context)¶
- Parameters:
- context – - QQmlContext
- Return type:
 
 - Create an object instance from this component, within the specified - context. Returns- Noneif creation failed.- Note - This method provides advanced control over component instance creation. In general, programmers should use - create()to create object instances.- When - QQmlComponentconstructs an instance, it occurs in three steps:- The object hierarchy is created, and constant values are assigned. 
- Property bindings are evaluated for the first time. 
- If applicable, - componentComplete()is called on objects.
 - QQmlComponent::beginCreate() differs from - create()in that it only performs step 1.- 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 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()¶
 - This method provides advanced control over component instance creation. In general, programmers should use - create()to create a component.- This function completes the component creation begun with - beginCreate()and must be called afterwards.- See also - create([context=None])¶
- Parameters:
- context – - QQmlContext
- Return type:
 
 - Create an object instance from this component, within the specified - context. Returns- Noneif creation failed.- If - contextis- None(the default), it will create the instance in the- root contextof 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 Concepts - Visual Parent in Qt Quick for more details. - See also - create(incubator[, context=None[, forContext=None]])
- Parameters:
- incubator – - QQmlIncubator
- context – - QQmlContext
- forContext – - QQmlContext
 
 
 - Create an object instance from this component using the provided - incubator.- contextspecifies the context within which to create the object instance.- If - contextis- None(by default), it will create the instance in the engine’s- root context.- forContextspecifies a context that this object creation depends upon. If the- forContextis being created asynchronously, and the- IncubationModeis- AsynchronousIfNested, this object will also be created asynchronously. If- forContextis- None(by default), the- contextwill be used for this decision.- The created object and its creation status are available via the - incubator.- See also - createObject([parent=None[, properties={}]])¶
 - createWithInitialProperties(initialProperties[, context=None])¶
- Parameters:
- initialProperties – Dictionary with keys of type .QString and values of type QVariant. 
- context – - QQmlContext
 
- Return type:
 
 - Create an object instance of this component, within the specified - context, and initialize its top-level properties with- initialProperties.- If any of the - initialPropertiescannot be set, a warning is issued. If there are unset required properties, the object creation fails and returns- nullptr, in which case- isError()will return- true.- See also - creationContext()¶
- Return type:
 
 - Returns the - QQmlContextthe component was created in. This is only valid for components created directly from QML.- engine()¶
- Return type:
 
 - Returns the - QQmlEngineof this component.- errorString()¶
- Return type:
- str 
 
 - Returns the list of errors that occurred during the last compile or create operation. An empty list is returned if - isError()is not set.- isBound()¶
- Return type:
- bool 
 
 - Returns true if the component was created in a QML files that specifies - pragma ComponentBehavior: Bound, otherwise returns false.- isError()¶
- Return type:
- bool 
 
 - Returns true if - status()==- Error.- isLoading()¶
- Return type:
- bool 
 
 - Returns true if - status()==- Loading.- isNull()¶
- Return type:
- bool 
 
 - Returns true if - status()==- Null.- isReady()¶
- Return type:
- bool 
 
 - Returns true if - status()==- Ready.- loadFromModule(uri, typeName[, mode=QQmlComponent.CompilationMode.PreferSynchronous])¶
- Parameters:
- uri – str 
- typeName – str 
- mode – - CompilationMode
 
 
 - Load the - QQmlComponentfor- typeNamein the module- uri. If the type is implemented via a QML file,- modeis used to load it. Types backed by C++ are always loaded synchronously.- QQmlEngine engine; QQmlComponent component(&engine); component.loadFromModule("QtQuick", "Item"); // once the component is ready std::unique_ptr<QObject> item(component.create()); Q_ASSERT(item->metaObject() == &QQuickItem::staticMetaObject); - See also - Load the - QQmlComponentfrom the provided- url.- Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile() when loading a file from the local filesystem. - Relative paths will be resolved against - baseUrl(), which is the current working directory unless specified.- loadUrl(url, mode)
- Parameters:
- url – - QUrl
- mode – - CompilationMode
 
 
 - Load the - QQmlComponentfrom the provided- url. If- modeis- Asynchronous, the component will be loaded and compiled asynchronously.- Ensure that the URL provided is full and correct, in particular, use QUrl::fromLocalFile() when loading a file from the local filesystem. - Relative paths will be resolved against - baseUrl(), which is the current working directory unless specified.- progress()¶
- Return type:
- float 
 
 - Getter of property - progressᅟ.- progressChanged(progress)¶
- Parameters:
- progress – float 
 
 - Emitted whenever the component’s loading progress changes. - progresswill be the current progress between 0.0 (nothing loaded) and 1.0 (finished).- Notification signal of property - progressᅟ.- setData(data, baseUrl)¶
- Parameters:
- data – - QByteArray
- baseUrl – - QUrl
 
 
 - Sets the - QQmlComponentto use the given QML- data. If- urlis provided, it is used to set the component name and to provide a base path for items resolved by this component.- setInitialProperties(component, properties)¶
- Parameters:
- component – - QObject
- properties – Dictionary with keys of type .QString and values of type QVariant. 
 
 
 - Set top-level - propertiesof the- objectthat was created from a- QQmlComponent.- This method provides advanced control over component instance creation. In general, programmers should use - createWithInitialPropertiesto create an object instance from a component.- Use this method after - beginCreateand before- completeCreatehas been called. If a provided property does not exist, a warning is issued.- This method does not allow setting initial nested properties directly. Instead, setting an initial value for value type properties with nested properties can be achieved by creating that value type, assigning its nested property and then passing the value type as an initial property of the object to be constructed. - For example, in order to set fond.bold, you can create a QFont, set its weight to bold and then pass the font as an initial property. - Getter of property - statusᅟ.- Emitted whenever the component’s status changes. - statuswill be the new status.- Notification signal of property - statusᅟ.- Getter of property - urlᅟ.